context.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. /**
  2. * Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import produce, { setAutoFreeze } from 'immer';
  8. import { List } from 'immutable';
  9. import { merge, Subscription } from 'rxjs';
  10. import { Canvas3D, Canvas3DContext, DefaultCanvas3DParams } from '../mol-canvas3d/canvas3d';
  11. import { CustomProperty } from '../mol-model-props/common/custom-property';
  12. import { Model, Structure } from '../mol-model/structure';
  13. import { DataBuilder } from '../mol-plugin-state/builder/data';
  14. import { StructureBuilder } from '../mol-plugin-state/builder/structure';
  15. import { DataFormatRegistry } from '../mol-plugin-state/formats/registry';
  16. import { StructureSelectionQueryRegistry } from '../mol-plugin-state/helpers/structure-selection-query';
  17. import { CameraManager } from '../mol-plugin-state/manager/camera';
  18. import { InteractivityManager } from '../mol-plugin-state/manager/interactivity';
  19. import { LociLabel, LociLabelManager } from '../mol-plugin-state/manager/loci-label';
  20. import { StructureComponentManager } from '../mol-plugin-state/manager/structure/component';
  21. import { StructureFocusManager } from '../mol-plugin-state/manager/structure/focus';
  22. import { StructureHierarchyManager } from '../mol-plugin-state/manager/structure/hierarchy';
  23. import { StructureHierarchyRef } from '../mol-plugin-state/manager/structure/hierarchy-state';
  24. import { StructureMeasurementManager } from '../mol-plugin-state/manager/structure/measurement';
  25. import { StructureSelectionManager } from '../mol-plugin-state/manager/structure/selection';
  26. import { PluginUIComponent } from '../mol-plugin-ui/base';
  27. import { StateTransformParameters } from '../mol-plugin-ui/state/common';
  28. import { Representation } from '../mol-repr/representation';
  29. import { StructureRepresentationRegistry } from '../mol-repr/structure/registry';
  30. import { VolumeRepresentationRegistry } from '../mol-repr/volume/registry';
  31. import { StateTransform } from '../mol-state';
  32. import { Task, RuntimeContext } from '../mol-task';
  33. import { ColorTheme } from '../mol-theme/color';
  34. import { SizeTheme } from '../mol-theme/size';
  35. import { ThemeRegistryContext } from '../mol-theme/theme';
  36. import { Color } from '../mol-util/color';
  37. import { ajaxGet } from '../mol-util/data-source';
  38. import { isDebugMode, isProductionMode } from '../mol-util/debug';
  39. import { ModifiersKeys } from '../mol-util/input/input-observer';
  40. import { LogEntry } from '../mol-util/log-entry';
  41. import { RxEventHelper } from '../mol-util/rx-event-helper';
  42. import { BuiltInPluginBehaviors } from './behavior';
  43. import { PluginBehavior } from './behavior/behavior';
  44. import { PluginCommandManager } from './command';
  45. import { PluginCommands } from './commands';
  46. import { PluginConfig, PluginConfigManager } from './config';
  47. import { LeftPanelTabName, PluginLayout } from './layout';
  48. import { PluginSpec } from './spec';
  49. import { PluginState } from './state';
  50. import { SubstructureParentHelper } from './util/substructure-parent-helper';
  51. import { TaskManager } from './util/task-manager';
  52. import { PluginToastManager } from './util/toast';
  53. import { ViewportScreenshotHelper } from './util/viewport-screenshot';
  54. import { PLUGIN_VERSION, PLUGIN_VERSION_DATE } from './version';
  55. import { AssetManager } from '../mol-util/assets';
  56. import { PluginStateSnapshotManager } from '../mol-plugin-state/manager/snapshots';
  57. import { PluginAnimationManager } from '../mol-plugin-state/manager/animation';
  58. import { objectForEach } from '../mol-util/object';
  59. import { VolumeHierarchyManager } from '../mol-plugin-state/manager/volume/hierarchy';
  60. import { filter, take } from 'rxjs/operators';
  61. import { Vec2 } from '../mol-math/linear-algebra';
  62. import { PluginAnimationLoop } from './animation-loop';
  63. import { resizeCanvas } from '../mol-canvas3d/util';
  64. export class PluginContext {
  65. runTask = <T>(task: Task<T>, params?: { useOverlay?: boolean }) => this.managers.task.run(task, params);
  66. resolveTask = <T>(object: Task<T> | T | undefined) => {
  67. if (!object) return void 0;
  68. if (Task.is(object)) return this.runTask(object);
  69. return object;
  70. }
  71. private subs: Subscription[] = [];
  72. private disposed = false;
  73. private ev = RxEventHelper.create();
  74. readonly config = new PluginConfigManager(this.spec.config); // needed to init state
  75. readonly state = new PluginState(this);
  76. readonly commands = new PluginCommandManager();
  77. private canvas3dInit = this.ev.behavior<boolean>(false);
  78. readonly behaviors = {
  79. state: {
  80. isAnimating: this.ev.behavior<boolean>(false),
  81. isUpdating: this.ev.behavior<boolean>(false),
  82. // TODO: should there be separate "updated" event?
  83. // Often, this is used to indicate that the state has updated
  84. // and it might not be the best way to react to state updates.
  85. isBusy: this.ev.behavior<boolean>(false)
  86. },
  87. interaction: {
  88. hover: this.ev.behavior<InteractivityManager.HoverEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  89. click: this.ev.behavior<InteractivityManager.ClickEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  90. drag: this.ev.behavior<InteractivityManager.DragEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0, pageStart: Vec2(), pageEnd: Vec2() }),
  91. selectionMode: this.ev.behavior<boolean>(false)
  92. },
  93. labels: {
  94. highlight: this.ev.behavior<{ labels: ReadonlyArray<LociLabel> }>({ labels: [] })
  95. },
  96. layout: {
  97. leftPanelTabName: this.ev.behavior<LeftPanelTabName>('root')
  98. },
  99. canvas3d: {
  100. initialized: this.canvas3dInit.pipe(filter(v => !!v), take(1))
  101. }
  102. } as const;
  103. readonly canvas3dContext: Canvas3DContext | undefined;
  104. readonly canvas3d: Canvas3D | undefined;
  105. readonly animationLoop = new PluginAnimationLoop(this);
  106. readonly layout = new PluginLayout(this);
  107. readonly representation = {
  108. structure: {
  109. registry: new StructureRepresentationRegistry(),
  110. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext,
  111. },
  112. volume: {
  113. registry: new VolumeRepresentationRegistry(),
  114. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  115. }
  116. } as const;
  117. readonly query = {
  118. structure: {
  119. registry: new StructureSelectionQueryRegistry()
  120. }
  121. } as const;
  122. readonly dataFormats = new DataFormatRegistry();
  123. readonly builders = {
  124. data: new DataBuilder(this),
  125. structure: void 0 as any as StructureBuilder
  126. };
  127. build() {
  128. return this.state.data.build();
  129. }
  130. readonly helpers = {
  131. substructureParent: new SubstructureParentHelper(this),
  132. viewportScreenshot: void 0 as ViewportScreenshotHelper | undefined
  133. } as const;
  134. readonly managers = {
  135. structure: {
  136. hierarchy: new StructureHierarchyManager(this),
  137. component: new StructureComponentManager(this),
  138. measurement: new StructureMeasurementManager(this),
  139. selection: new StructureSelectionManager(this),
  140. focus: new StructureFocusManager(this),
  141. },
  142. volume: {
  143. hierarchy: new VolumeHierarchyManager(this)
  144. },
  145. interactivity: void 0 as any as InteractivityManager,
  146. camera: new CameraManager(this),
  147. animation: new PluginAnimationManager(this),
  148. snapshot: new PluginStateSnapshotManager(this),
  149. lociLabels: void 0 as any as LociLabelManager,
  150. toast: new PluginToastManager(this),
  151. asset: new AssetManager(),
  152. task: new TaskManager()
  153. } as const;
  154. readonly events = {
  155. log: this.ev<LogEntry>(),
  156. task: this.managers.task.events,
  157. canvas3d: {
  158. settingsUpdated: this.ev(),
  159. }
  160. } as const;
  161. readonly customModelProperties = new CustomProperty.Registry<Model>();
  162. readonly customStructureProperties = new CustomProperty.Registry<Structure>();
  163. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  164. readonly customStructureControls = new Map<string, { new(): PluginUIComponent<any, any, any> }>();
  165. readonly genericRepresentationControls = new Map<string, (selection: StructureHierarchyManager['selection']) => [StructureHierarchyRef[], string]>();
  166. /**
  167. * Used to store application specific custom state which is then available
  168. * to State Actions and similar constructs via the PluginContext.
  169. */
  170. readonly customState: unknown = Object.create(null);
  171. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  172. try {
  173. this.layout.setRoot(container);
  174. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  175. const antialias = !(this.config.get(PluginConfig.General.DisableAntialiasing) ?? false);
  176. const preserveDrawingBuffer = !(this.config.get(PluginConfig.General.DisablePreserveDrawingBuffer) ?? false);
  177. const pixelScale = this.config.get(PluginConfig.General.PixelScale) || 1;
  178. const pickScale = this.config.get(PluginConfig.General.PickScale) || 0.25;
  179. const enableWboit = this.config.get(PluginConfig.General.EnableWboit) || false;
  180. (this.canvas3dContext as Canvas3DContext) = Canvas3DContext.fromCanvas(canvas, { antialias, preserveDrawingBuffer, pixelScale, pickScale, enableWboit });
  181. (this.canvas3d as Canvas3D) = Canvas3D.create(this.canvas3dContext!);
  182. this.canvas3dInit.next(true);
  183. let props = this.spec.components?.viewport?.canvas3d;
  184. const backgroundColor = Color(0xFCFBF9);
  185. if (!props) {
  186. this.canvas3d?.setProps({ renderer: { backgroundColor } });
  187. } else {
  188. if (props.renderer?.backgroundColor === void 0) {
  189. props = produce(props, p => {
  190. if (p.renderer) p.renderer.backgroundColor = backgroundColor;
  191. else p.renderer = { backgroundColor };
  192. });
  193. }
  194. this.canvas3d?.setProps(props);
  195. }
  196. this.animationLoop.start();
  197. (this.helpers.viewportScreenshot as ViewportScreenshotHelper) = new ViewportScreenshotHelper(this);
  198. this.subs.push(this.canvas3d!.interaction.click.subscribe(e => this.behaviors.interaction.click.next(e)));
  199. this.subs.push(this.canvas3d!.interaction.drag.subscribe(e => this.behaviors.interaction.drag.next(e)));
  200. this.subs.push(this.canvas3d!.interaction.hover.subscribe(e => this.behaviors.interaction.hover.next(e)));
  201. this.subs.push(this.canvas3d!.input.resize.subscribe(() => this.handleResize()));
  202. this.subs.push(this.layout.events.updated.subscribe(() => requestAnimationFrame(() => this.handleResize())));
  203. this.handleResize();
  204. return true;
  205. } catch (e) {
  206. this.log.error('' + e);
  207. console.error(e);
  208. return false;
  209. }
  210. }
  211. handleResize() {
  212. const canvas = this.canvas3dContext?.canvas;
  213. const container = this.layout.root;
  214. if (container && canvas) {
  215. const pixelScale = this.config.get(PluginConfig.General.PixelScale) || 1;
  216. resizeCanvas(canvas, container, pixelScale);
  217. this.canvas3d?.requestResize();
  218. }
  219. }
  220. readonly log = {
  221. entries: List<LogEntry>(),
  222. entry: (e: LogEntry) => this.events.log.next(e),
  223. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  224. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  225. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  226. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  227. };
  228. /**
  229. * This should be used in all transform related request so that it could be "spoofed" to allow
  230. * "static" access to resources.
  231. */
  232. readonly fetch = ajaxGet
  233. /** return true is animating or updating */
  234. get isBusy() {
  235. return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value;
  236. }
  237. get selectionMode() {
  238. return this.behaviors.interaction.selectionMode.value;
  239. }
  240. set selectionMode(mode: boolean) {
  241. this.behaviors.interaction.selectionMode.next(mode);
  242. }
  243. dataTransaction(f: (ctx: RuntimeContext) => Promise<void> | void, options?: { canUndo?: string | boolean, rethrowErrors?: boolean }) {
  244. return this.runTask(this.state.data.transaction(f, options));
  245. }
  246. clear(resetViewportSettings = false) {
  247. if (resetViewportSettings) this.canvas3d?.setProps(DefaultCanvas3DParams);
  248. return PluginCommands.State.RemoveObject(this, { state: this.state.data, ref: StateTransform.RootRef });
  249. }
  250. dispose(options?: { doNotForceWebGLContextLoss?: boolean }) {
  251. if (this.disposed) return;
  252. for (const s of this.subs) {
  253. s.unsubscribe();
  254. }
  255. this.subs = [];
  256. this.commands.dispose();
  257. this.canvas3d?.dispose();
  258. this.canvas3dContext?.dispose(options);
  259. this.ev.dispose();
  260. this.state.dispose();
  261. this.managers.task.dispose();
  262. this.layout.dispose();
  263. this.helpers.substructureParent.dispose();
  264. objectForEach(this.managers, m => (m as any)?.dispose?.());
  265. objectForEach(this.managers.structure, m => (m as any)?.dispose?.());
  266. this.disposed = true;
  267. }
  268. private initBehaviorEvents() {
  269. this.subs.push(merge(this.state.data.behaviors.isUpdating, this.state.behaviors.behaviors.isUpdating).subscribe(u => {
  270. if (this.behaviors.state.isUpdating.value !== u) this.behaviors.state.isUpdating.next(u);
  271. }));
  272. const timeoutMs = this.config.get(PluginConfig.General.IsBusyTimeoutMs) || 750;
  273. const isBusy = this.behaviors.state.isBusy;
  274. let timeout: any = void 0;
  275. const setBusy = () => {
  276. if (!isBusy.value) isBusy.next(true);
  277. };
  278. const reset = () => {
  279. if (timeout !== void 0) clearTimeout(timeout);
  280. timeout = void 0;
  281. };
  282. this.subs.push(merge(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(v => {
  283. const isUpdating = this.behaviors.state.isUpdating.value;
  284. const isAnimating = this.behaviors.state.isAnimating.value;
  285. if (isUpdating || isAnimating) {
  286. if (!isBusy.value) {
  287. reset();
  288. timeout = setTimeout(setBusy, timeoutMs);
  289. }
  290. } else {
  291. reset();
  292. isBusy.next(false);
  293. }
  294. }));
  295. this.subs.push(this.behaviors.interaction.selectionMode.subscribe(v => {
  296. if (!v) {
  297. this.managers.interactivity?.lociSelects.deselectAll();
  298. }
  299. }));
  300. }
  301. private initBuiltInBehavior() {
  302. BuiltInPluginBehaviors.State.registerDefault(this);
  303. BuiltInPluginBehaviors.Representation.registerDefault(this);
  304. BuiltInPluginBehaviors.Camera.registerDefault(this);
  305. BuiltInPluginBehaviors.Misc.registerDefault(this);
  306. this.subs.push(merge(this.state.data.events.log, this.state.behaviors.events.log).subscribe(e => this.events.log.next(e)));
  307. }
  308. private async initBehaviors() {
  309. let tree = this.state.behaviors.build();
  310. for (const cat of Object.keys(PluginBehavior.Categories)) {
  311. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  312. }
  313. // Init custom properties 1st
  314. for (const b of this.spec.behaviors) {
  315. const cat = PluginBehavior.getCategoryId(b.transformer);
  316. if (cat !== 'custom-props') continue;
  317. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  318. }
  319. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  320. tree = this.state.behaviors.build();
  321. for (const b of this.spec.behaviors) {
  322. const cat = PluginBehavior.getCategoryId(b.transformer);
  323. if (cat === 'custom-props') continue;
  324. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  325. }
  326. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  327. }
  328. private initCustomFormats() {
  329. if (!this.spec.customFormats) return;
  330. for (const f of this.spec.customFormats) {
  331. this.dataFormats.add(f[0], f[1]);
  332. }
  333. }
  334. private initDataActions() {
  335. for (const a of this.spec.actions) {
  336. this.state.data.actions.add(a.action);
  337. }
  338. }
  339. private initAnimations() {
  340. if (!this.spec.animations) return;
  341. for (const anim of this.spec.animations) {
  342. this.managers.animation.register(anim);
  343. }
  344. }
  345. private initCustomParamEditors() {
  346. if (!this.spec.customParamEditors) return;
  347. for (const [t, e] of this.spec.customParamEditors) {
  348. this.customParamEditors.set(t.id, e);
  349. }
  350. }
  351. async init() {
  352. this.subs.push(this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e)));
  353. this.initCustomFormats();
  354. this.initBehaviorEvents();
  355. this.initBuiltInBehavior();
  356. (this.managers.interactivity as InteractivityManager) = new InteractivityManager(this);
  357. (this.managers.lociLabels as LociLabelManager) = new LociLabelManager(this);
  358. (this.builders.structure as StructureBuilder) = new StructureBuilder(this);
  359. this.initDataActions();
  360. this.initAnimations();
  361. this.initCustomParamEditors();
  362. await this.initBehaviors();
  363. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  364. if (!isProductionMode) this.log.message(`Development mode enabled`);
  365. if (isDebugMode) this.log.message(`Debug mode enabled`);
  366. }
  367. constructor(public spec: PluginSpec) {
  368. // the reason for this is that sometimes, transform params get modified inline (i.e. palette.valueLabel)
  369. // and freezing the params object causes "read-only exception"
  370. // TODO: is this the best place to do it?
  371. setAutoFreeze(false);
  372. }
  373. }