context.ts 19 KB

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