context.ts 15 KB

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