context.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. /**
  2. * Copyright (c) 2018-2020 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 { setAutoFreeze } from 'immer';
  8. import { List } from 'immutable';
  9. import { merge } from 'rxjs';
  10. import { Canvas3D, 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 { HierarchyRef } 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 { Progress, Task } 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. export class PluginContext {
  60. runTask = <T>(task: Task<T>) => this.tasks.run(task);
  61. private disposed = false;
  62. private ev = RxEventHelper.create();
  63. private tasks = new TaskManager();
  64. readonly state = new PluginState(this);
  65. readonly commands = new PluginCommandManager();
  66. readonly events = {
  67. log: this.ev<LogEntry>(),
  68. task: this.tasks.events,
  69. canvas3d: {
  70. initialized: this.ev(),
  71. settingsUpdated: this.ev(),
  72. }
  73. } as const
  74. readonly config = new PluginConfigManager(this.spec.config);
  75. readonly behaviors = {
  76. state: {
  77. isAnimating: this.ev.behavior<boolean>(false),
  78. isUpdating: this.ev.behavior<boolean>(false),
  79. isBusy: this.ev.behavior<boolean>(false)
  80. },
  81. interaction: {
  82. hover: this.ev.behavior<InteractivityManager.HoverEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  83. click: this.ev.behavior<InteractivityManager.ClickEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  84. selectionMode: this.ev.behavior<boolean>(false)
  85. },
  86. labels: {
  87. highlight: this.ev.behavior<{ labels: ReadonlyArray<LociLabel> }>({ labels: [] })
  88. },
  89. layout: {
  90. leftPanelTabName: this.ev.behavior<LeftPanelTabName>('root')
  91. }
  92. } as const
  93. readonly canvas3d: Canvas3D | undefined;
  94. readonly layout = new PluginLayout(this);
  95. readonly representation = {
  96. structure: {
  97. registry: new StructureRepresentationRegistry(),
  98. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext,
  99. },
  100. volume: {
  101. registry: new VolumeRepresentationRegistry(),
  102. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  103. }
  104. } as const;
  105. readonly query = {
  106. structure: {
  107. registry: new StructureSelectionQueryRegistry()
  108. }
  109. } as const;
  110. readonly dataFormats = new DataFormatRegistry();
  111. readonly builders = {
  112. data: new DataBuilder(this),
  113. structure: void 0 as any as StructureBuilder
  114. };
  115. build() {
  116. return this.state.data.build();
  117. }
  118. readonly managers = {
  119. structure: {
  120. hierarchy: new StructureHierarchyManager(this),
  121. component: new StructureComponentManager(this),
  122. measurement: new StructureMeasurementManager(this),
  123. selection: new StructureSelectionManager(this),
  124. focus: new StructureFocusManager(this),
  125. },
  126. interactivity: void 0 as any as InteractivityManager,
  127. camera: new CameraManager(this),
  128. animation: new PluginAnimationManager(this),
  129. snapshot: new PluginStateSnapshotManager(this),
  130. lociLabels: void 0 as any as LociLabelManager,
  131. toast: new PluginToastManager(this),
  132. asset: new AssetManager()
  133. } as const
  134. readonly customModelProperties = new CustomProperty.Registry<Model>();
  135. readonly customStructureProperties = new CustomProperty.Registry<Structure>();
  136. readonly customParamEditors = new Map<string, StateTransformParameters.Class>();
  137. readonly customStructureControls = new Map<string, { new(): PluginUIComponent<any, any, any> }>();
  138. readonly genericRepresentationControls = new Map<string, (selection: StructureHierarchyManager['selection']) => [HierarchyRef[], string]>();
  139. readonly helpers = {
  140. substructureParent: new SubstructureParentHelper(this),
  141. viewportScreenshot: void 0 as ViewportScreenshotHelper | undefined
  142. } as const;
  143. /**
  144. * Used to store application specific custom state which is then available
  145. * to State Actions and similar constructs via the PluginContext.
  146. */
  147. readonly customState: unknown = Object.create(null);
  148. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement) {
  149. try {
  150. this.layout.setRoot(container);
  151. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  152. (this.canvas3d as Canvas3D) = Canvas3D.fromCanvas(canvas);
  153. this.events.canvas3d.initialized.next();
  154. this.events.canvas3d.initialized.isStopped = true; // TODO is this a good way?
  155. const renderer = this.canvas3d!.props.renderer;
  156. PluginCommands.Canvas3D.SetSettings(this, { settings: { renderer: { ...renderer, backgroundColor: Color(0xFCFBF9) } } });
  157. this.canvas3d!.animate();
  158. (this.helpers.viewportScreenshot as ViewportScreenshotHelper) = new ViewportScreenshotHelper(this);
  159. return true;
  160. } catch (e) {
  161. this.log.error('' + e);
  162. console.error(e);
  163. return false;
  164. }
  165. }
  166. readonly log = {
  167. entries: List<LogEntry>(),
  168. entry: (e: LogEntry) => this.events.log.next(e),
  169. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  170. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  171. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  172. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  173. };
  174. /**
  175. * This should be used in all transform related request so that it could be "spoofed" to allow
  176. * "static" access to resources.
  177. */
  178. readonly fetch = ajaxGet
  179. /** return true is animating or updating */
  180. get isBusy() {
  181. return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value;
  182. }
  183. get selectionMode() {
  184. return this.behaviors.interaction.selectionMode.value;
  185. }
  186. set selectionMode(mode: boolean) {
  187. this.behaviors.interaction.selectionMode.next(mode);
  188. }
  189. dataTransaction(f: () => Promise<void> | void, options?: { canUndo?: string | boolean }) {
  190. return this.runTask(this.state.data.transaction(f, options));
  191. }
  192. requestTaskAbort(progress: Progress, reason?: string) {
  193. this.tasks.requestAbort(progress, reason);
  194. }
  195. clear(resetViewportSettings = false) {
  196. if (resetViewportSettings) this.canvas3d?.setProps(DefaultCanvas3DParams);
  197. return PluginCommands.State.RemoveObject(this, { state: this.state.data, ref: StateTransform.RootRef });
  198. }
  199. dispose() {
  200. if (this.disposed) return;
  201. this.commands.dispose();
  202. this.canvas3d?.dispose();
  203. this.ev.dispose();
  204. this.state.dispose();
  205. this.tasks.dispose();
  206. this.layout.dispose();
  207. objectForEach(this.managers, m => (m as any)?.dispose?.());
  208. objectForEach(this.managers.structure, m => (m as any)?.dispose?.());
  209. this.disposed = true;
  210. }
  211. private initBehaviorEvents() {
  212. merge(this.state.data.behaviors.isUpdating, this.state.behaviors.behaviors.isUpdating).subscribe(u => {
  213. if (this.behaviors.state.isUpdating.value !== u) this.behaviors.state.isUpdating.next(u);
  214. });
  215. const timeoutMs = this.config.get(PluginConfig.General.IsBusyTimeoutMs) || 750;
  216. const isBusy = this.behaviors.state.isBusy;
  217. let timeout: any = void 0;
  218. const setBusy = () => {
  219. isBusy.next(true);
  220. };
  221. merge(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(v => {
  222. const isUpdating = this.behaviors.state.isUpdating.value;
  223. const isAnimating = this.behaviors.state.isAnimating.value;
  224. if ((isUpdating || isAnimating) && !isBusy.value) {
  225. if (timeout !== void 0) clearTimeout(timeout);
  226. timeout = setTimeout(setBusy, timeoutMs);
  227. // isBusy.next(true);
  228. } else {
  229. if (timeout !== void 0) clearTimeout(timeout);
  230. timeout = void 0;
  231. if (isBusy.value) {
  232. isBusy.next(false);
  233. }
  234. }
  235. });
  236. this.behaviors.interaction.selectionMode.subscribe(v => {
  237. if (!v) {
  238. this.managers.interactivity?.lociSelects.deselectAll();
  239. }
  240. });
  241. }
  242. private initBuiltInBehavior() {
  243. BuiltInPluginBehaviors.State.registerDefault(this);
  244. BuiltInPluginBehaviors.Representation.registerDefault(this);
  245. BuiltInPluginBehaviors.Camera.registerDefault(this);
  246. BuiltInPluginBehaviors.Misc.registerDefault(this);
  247. merge(this.state.data.events.log, this.state.behaviors.events.log).subscribe(e => this.events.log.next(e));
  248. }
  249. private async initBehaviors() {
  250. let tree = this.state.behaviors.build();
  251. for (const cat of Object.keys(PluginBehavior.Categories)) {
  252. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  253. }
  254. // Init custom properties 1st
  255. for (const b of this.spec.behaviors) {
  256. const cat = PluginBehavior.getCategoryId(b.transformer);
  257. if (cat !== 'custom-props') continue;
  258. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  259. }
  260. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  261. tree = this.state.behaviors.build();
  262. for (const b of this.spec.behaviors) {
  263. const cat = PluginBehavior.getCategoryId(b.transformer);
  264. if (cat === 'custom-props') continue;
  265. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  266. }
  267. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  268. }
  269. private initDataActions() {
  270. for (const a of this.spec.actions) {
  271. this.state.data.actions.add(a.action);
  272. }
  273. }
  274. private initAnimations() {
  275. if (!this.spec.animations) return;
  276. for (const anim of this.spec.animations) {
  277. this.managers.animation.register(anim);
  278. }
  279. }
  280. private initCustomParamEditors() {
  281. if (!this.spec.customParamEditors) return;
  282. for (const [t, e] of this.spec.customParamEditors) {
  283. this.customParamEditors.set(t.id, e);
  284. }
  285. }
  286. constructor(public spec: PluginSpec) {
  287. // the reason for this is that sometimes, transform params get modified inline (i.e. palette.valueLabel)
  288. // and freezing the params object causes "read-only exception"
  289. // TODO: is this the best place to do it?
  290. setAutoFreeze(false);
  291. this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e));
  292. this.initBehaviorEvents();
  293. this.initBuiltInBehavior();
  294. this.initBehaviors();
  295. this.initDataActions();
  296. this.initAnimations();
  297. this.initCustomParamEditors();
  298. (this.managers.interactivity as InteractivityManager) = new InteractivityManager(this);
  299. (this.managers.lociLabels as LociLabelManager) = new LociLabelManager(this);
  300. (this.builders.structure as StructureBuilder) = new StructureBuilder(this);
  301. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  302. if (!isProductionMode) this.log.message(`Development mode enabled`);
  303. if (isDebugMode) this.log.message(`Debug mode enabled`);
  304. }
  305. }