context.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  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, Scheduler, 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 initCanvas3dPromiseCallbacks: [res: () => void, rej: (err: any) => void] = [() => {}, () => {}];
  72. private disposed = false;
  73. private canvasContainer: HTMLDivElement | undefined = void 0;
  74. private ev = RxEventHelper.create();
  75. readonly config = new PluginConfigManager(this.spec.config); // needed to init state
  76. readonly state = new PluginState(this);
  77. readonly commands = new PluginCommandManager();
  78. private canvas3dInit = this.ev.behavior<boolean>(false);
  79. readonly behaviors = {
  80. state: {
  81. isAnimating: this.ev.behavior<boolean>(false),
  82. isUpdating: this.ev.behavior<boolean>(false),
  83. // TODO: should there be separate "updated" event?
  84. // Often, this is used to indicate that the state has updated
  85. // and it might not be the best way to react to state updates.
  86. isBusy: this.ev.behavior<boolean>(false)
  87. },
  88. interaction: {
  89. hover: this.ev.behavior<InteractivityManager.HoverEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  90. click: this.ev.behavior<InteractivityManager.ClickEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0 }),
  91. drag: this.ev.behavior<InteractivityManager.DragEvent>({ current: Representation.Loci.Empty, modifiers: ModifiersKeys.None, buttons: 0, button: 0, pageStart: Vec2(), pageEnd: Vec2() }),
  92. selectionMode: this.ev.behavior<boolean>(false)
  93. },
  94. labels: {
  95. highlight: this.ev.behavior<{ labels: ReadonlyArray<LociLabel> }>({ labels: [] })
  96. },
  97. layout: {
  98. leftPanelTabName: this.ev.behavior<LeftPanelTabName>('root')
  99. },
  100. canvas3d: {
  101. // TODO: remove in 4.0?
  102. initialized: this.canvas3dInit.pipe(filter(v => !!v), take(1))
  103. }
  104. } as const;
  105. readonly canvas3dInitialized = new Promise<void>((res, rej) => {
  106. this.initCanvas3dPromiseCallbacks = [res, rej];
  107. });
  108. readonly canvas3dContext: Canvas3DContext | undefined;
  109. readonly canvas3d: Canvas3D | undefined;
  110. readonly layout = new PluginLayout(this);
  111. readonly animationLoop = new PluginAnimationLoop(this);
  112. readonly representation = {
  113. structure: {
  114. registry: new StructureRepresentationRegistry(),
  115. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext,
  116. },
  117. volume: {
  118. registry: new VolumeRepresentationRegistry(),
  119. themes: { colorThemeRegistry: ColorTheme.createRegistry(), sizeThemeRegistry: SizeTheme.createRegistry() } as ThemeRegistryContext
  120. }
  121. } as const;
  122. readonly query = {
  123. structure: {
  124. registry: new StructureSelectionQueryRegistry()
  125. }
  126. } as const;
  127. readonly dataFormats = new DataFormatRegistry();
  128. readonly builders = {
  129. data: new DataBuilder(this),
  130. structure: void 0 as any as StructureBuilder
  131. };
  132. build() {
  133. return this.state.data.build();
  134. }
  135. readonly helpers = {
  136. substructureParent: new SubstructureParentHelper(this),
  137. viewportScreenshot: void 0 as ViewportScreenshotHelper | undefined
  138. } as const;
  139. readonly managers = {
  140. structure: {
  141. hierarchy: new StructureHierarchyManager(this),
  142. component: new StructureComponentManager(this),
  143. measurement: new StructureMeasurementManager(this),
  144. selection: new StructureSelectionManager(this),
  145. focus: new StructureFocusManager(this),
  146. },
  147. volume: {
  148. hierarchy: new VolumeHierarchyManager(this)
  149. },
  150. interactivity: void 0 as any as InteractivityManager,
  151. camera: new CameraManager(this),
  152. animation: new PluginAnimationManager(this),
  153. snapshot: new PluginStateSnapshotManager(this),
  154. lociLabels: void 0 as any as LociLabelManager,
  155. toast: new PluginToastManager(this),
  156. asset: new AssetManager(),
  157. task: new TaskManager()
  158. } as const;
  159. readonly events = {
  160. log: this.ev<LogEntry>(),
  161. task: this.managers.task.events,
  162. canvas3d: {
  163. settingsUpdated: this.ev(),
  164. }
  165. } as const;
  166. readonly customModelProperties = new CustomProperty.Registry<Model>();
  167. readonly customStructureProperties = new CustomProperty.Registry<Structure>();
  168. readonly customStructureControls = new Map<string, { new(): any /* constructible react components with <action.customControl /> */ }>();
  169. readonly customImportControls = new Map<string, { new(): any /* constructible react components with <action.customControl /> */ }>();
  170. readonly genericRepresentationControls = new Map<string, (selection: StructureHierarchyManager['selection']) => [StructureHierarchyRef[], string]>();
  171. /**
  172. * Used to store application specific custom state which is then available
  173. * to State Actions and similar constructs via the PluginContext.
  174. */
  175. readonly customState: unknown = Object.create(null);
  176. initContainer(canvas3dContext?: Canvas3DContext) {
  177. if (this.canvasContainer) return true;
  178. const container = document.createElement('div');
  179. Object.assign(container.style, {
  180. position: 'absolute',
  181. left: 0,
  182. top: 0,
  183. right: 0,
  184. bottom: 0,
  185. '-webkit-user-select': 'none',
  186. 'user-select': 'none',
  187. '-webkit-tap-highlight-color': 'rgba(0,0,0,0)',
  188. '-webkit-touch-callout': 'none',
  189. 'touch-action': 'manipulation',
  190. });
  191. let canvas = canvas3dContext?.canvas;
  192. if (!canvas) {
  193. canvas = document.createElement('canvas');
  194. Object.assign(canvas.style, {
  195. 'background-image': 'linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%, lightgrey), linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%, lightgrey)',
  196. 'background-size': '60px 60px',
  197. 'background-position': '0 0, 30px 30px'
  198. });
  199. container.appendChild(canvas);
  200. }
  201. if (!this.initViewer(canvas, container, canvas3dContext)) {
  202. return false;
  203. }
  204. this.canvasContainer = container;
  205. return true;
  206. }
  207. mount(target: HTMLElement) {
  208. if (this.disposed) throw new Error('Cannot mount a disposed context');
  209. if (!this.initContainer()) return false;
  210. if (this.canvasContainer!.parentElement !== target) {
  211. this.canvasContainer!.parentElement?.removeChild(this.canvasContainer!);
  212. }
  213. target.appendChild(this.canvasContainer!);
  214. this.handleResize();
  215. return true;
  216. }
  217. unmount() {
  218. this.canvasContainer?.parentElement?.removeChild(this.canvasContainer);
  219. }
  220. initViewer(canvas: HTMLCanvasElement, container: HTMLDivElement, canvas3dContext?: Canvas3DContext) {
  221. try {
  222. this.layout.setRoot(container);
  223. if (this.spec.layout && this.spec.layout.initial) this.layout.setProps(this.spec.layout.initial);
  224. if (canvas3dContext) {
  225. (this.canvas3dContext as Canvas3DContext) = canvas3dContext;
  226. } else {
  227. const antialias = !(this.config.get(PluginConfig.General.DisableAntialiasing) ?? false);
  228. const preserveDrawingBuffer = !(this.config.get(PluginConfig.General.DisablePreserveDrawingBuffer) ?? false);
  229. const pixelScale = this.config.get(PluginConfig.General.PixelScale) || 1;
  230. const pickScale = this.config.get(PluginConfig.General.PickScale) || 0.25;
  231. const pickPadding = this.config.get(PluginConfig.General.PickPadding) ?? 1;
  232. const enableWboit = this.config.get(PluginConfig.General.EnableWboit) || false;
  233. const enableDpoit = this.config.get(PluginConfig.General.EnableDpoit) || false;
  234. const preferWebGl1 = this.config.get(PluginConfig.General.PreferWebGl1) || false;
  235. const failIfMajorPerformanceCaveat = !(this.config.get(PluginConfig.General.AllowMajorPerformanceCaveat) ?? false);
  236. (this.canvas3dContext as Canvas3DContext) = Canvas3DContext.fromCanvas(canvas, this.managers.asset, { antialias, preserveDrawingBuffer, pixelScale, pickScale, pickPadding, enableWboit, enableDpoit, preferWebGl1, failIfMajorPerformanceCaveat });
  237. }
  238. (this.canvas3d as Canvas3D) = Canvas3D.create(this.canvas3dContext!);
  239. this.canvas3dInit.next(true);
  240. let props = this.spec.canvas3d;
  241. const backgroundColor = Color(0xFCFBF9);
  242. if (!props) {
  243. this.canvas3d?.setProps({ renderer: { backgroundColor } });
  244. } else {
  245. if (props.renderer?.backgroundColor === void 0) {
  246. props = produce(props, p => {
  247. if (p.renderer) p.renderer.backgroundColor = backgroundColor;
  248. else p.renderer = { backgroundColor };
  249. });
  250. }
  251. this.canvas3d?.setProps(props);
  252. }
  253. this.animationLoop.start();
  254. (this.helpers.viewportScreenshot as ViewportScreenshotHelper) = new ViewportScreenshotHelper(this);
  255. this.subs.push(this.canvas3d!.interaction.click.subscribe(e => this.behaviors.interaction.click.next(e)));
  256. this.subs.push(this.canvas3d!.interaction.drag.subscribe(e => this.behaviors.interaction.drag.next(e)));
  257. this.subs.push(this.canvas3d!.interaction.hover.subscribe(e => this.behaviors.interaction.hover.next(e)));
  258. this.subs.push(this.canvas3d!.input.resize.subscribe(() => this.handleResize()));
  259. this.subs.push(this.layout.events.updated.subscribe(() => requestAnimationFrame(() => this.handleResize())));
  260. this.handleResize();
  261. Scheduler.setImmediate(() => this.initCanvas3dPromiseCallbacks[0]());
  262. return true;
  263. } catch (e) {
  264. this.log.error('' + e);
  265. console.error(e);
  266. Scheduler.setImmediate(() => this.initCanvas3dPromiseCallbacks[1](e));
  267. return false;
  268. }
  269. }
  270. handleResize() {
  271. const canvas = this.canvas3dContext?.canvas;
  272. const container = this.layout.root;
  273. if (container && canvas) {
  274. const pixelScale = this.config.get(PluginConfig.General.PixelScale) || 1;
  275. resizeCanvas(canvas, container, pixelScale);
  276. this.canvas3d?.requestResize();
  277. }
  278. }
  279. readonly log = {
  280. entries: List<LogEntry>(),
  281. entry: (e: LogEntry) => this.events.log.next(e),
  282. error: (msg: string) => this.events.log.next(LogEntry.error(msg)),
  283. message: (msg: string) => this.events.log.next(LogEntry.message(msg)),
  284. info: (msg: string) => this.events.log.next(LogEntry.info(msg)),
  285. warn: (msg: string) => this.events.log.next(LogEntry.warning(msg)),
  286. };
  287. /**
  288. * This should be used in all transform related request so that it could be "spoofed" to allow
  289. * "static" access to resources.
  290. */
  291. readonly fetch = ajaxGet;
  292. /** return true is animating or updating */
  293. get isBusy() {
  294. return this.behaviors.state.isAnimating.value || this.behaviors.state.isUpdating.value;
  295. }
  296. get selectionMode() {
  297. return this.behaviors.interaction.selectionMode.value;
  298. }
  299. set selectionMode(mode: boolean) {
  300. this.behaviors.interaction.selectionMode.next(mode);
  301. }
  302. dataTransaction(f: (ctx: RuntimeContext) => Promise<void> | void, options?: { canUndo?: string | boolean, rethrowErrors?: boolean }) {
  303. return this.runTask(this.state.data.transaction(f, options));
  304. }
  305. clear(resetViewportSettings = false) {
  306. if (resetViewportSettings) this.canvas3d?.setProps(DefaultCanvas3DParams);
  307. return PluginCommands.State.RemoveObject(this, { state: this.state.data, ref: StateTransform.RootRef });
  308. }
  309. dispose(options?: { doNotForceWebGLContextLoss?: boolean }) {
  310. if (this.disposed) return;
  311. for (const s of this.subs) {
  312. s.unsubscribe();
  313. }
  314. this.subs = [];
  315. this.commands.dispose();
  316. this.canvas3d?.dispose();
  317. this.canvas3dContext?.dispose(options);
  318. this.ev.dispose();
  319. this.state.dispose();
  320. this.managers.task.dispose();
  321. this.helpers.substructureParent.dispose();
  322. objectForEach(this.managers, m => (m as any)?.dispose?.());
  323. objectForEach(this.managers.structure, m => (m as any)?.dispose?.());
  324. this.unmount();
  325. this.canvasContainer = undefined;
  326. this.disposed = true;
  327. }
  328. private initBehaviorEvents() {
  329. this.subs.push(merge(this.state.data.behaviors.isUpdating, this.state.behaviors.behaviors.isUpdating).subscribe(u => {
  330. if (this.behaviors.state.isUpdating.value !== u) this.behaviors.state.isUpdating.next(u);
  331. }));
  332. const timeoutMs = this.config.get(PluginConfig.General.IsBusyTimeoutMs) || 750;
  333. const isBusy = this.behaviors.state.isBusy;
  334. let timeout: any = void 0;
  335. const setBusy = () => {
  336. if (!isBusy.value) isBusy.next(true);
  337. };
  338. const reset = () => {
  339. if (timeout !== void 0) clearTimeout(timeout);
  340. timeout = void 0;
  341. };
  342. this.subs.push(merge(this.behaviors.state.isUpdating, this.behaviors.state.isAnimating).subscribe(v => {
  343. const isUpdating = this.behaviors.state.isUpdating.value;
  344. const isAnimating = this.behaviors.state.isAnimating.value;
  345. if (isUpdating || isAnimating) {
  346. if (!isBusy.value) {
  347. reset();
  348. timeout = setTimeout(setBusy, timeoutMs);
  349. }
  350. } else {
  351. reset();
  352. isBusy.next(false);
  353. }
  354. }));
  355. this.subs.push(this.behaviors.interaction.selectionMode.subscribe(v => {
  356. if (!v) {
  357. this.managers.interactivity?.lociSelects.deselectAll();
  358. }
  359. }));
  360. }
  361. private initBuiltInBehavior() {
  362. BuiltInPluginBehaviors.State.registerDefault(this);
  363. BuiltInPluginBehaviors.Representation.registerDefault(this);
  364. BuiltInPluginBehaviors.Camera.registerDefault(this);
  365. BuiltInPluginBehaviors.Misc.registerDefault(this);
  366. this.subs.push(merge(this.state.data.events.log, this.state.behaviors.events.log).subscribe(e => this.events.log.next(e)));
  367. }
  368. private async initBehaviors() {
  369. let tree = this.state.behaviors.build();
  370. for (const cat of Object.keys(PluginBehavior.Categories)) {
  371. tree.toRoot().apply(PluginBehavior.CreateCategory, { label: (PluginBehavior.Categories as any)[cat] }, { ref: cat, state: { isLocked: true } });
  372. }
  373. // Init custom properties 1st
  374. for (const b of this.spec.behaviors) {
  375. const cat = PluginBehavior.getCategoryId(b.transformer);
  376. if (cat !== 'custom-props') continue;
  377. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  378. }
  379. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  380. tree = this.state.behaviors.build();
  381. for (const b of this.spec.behaviors) {
  382. const cat = PluginBehavior.getCategoryId(b.transformer);
  383. if (cat === 'custom-props') continue;
  384. tree.to(PluginBehavior.getCategoryId(b.transformer)).apply(b.transformer, b.defaultParams, { ref: b.transformer.id });
  385. }
  386. await this.runTask(this.state.behaviors.updateTree(tree, { doNotUpdateCurrent: true, doNotLogTiming: true }));
  387. }
  388. private initCustomFormats() {
  389. if (!this.spec.customFormats) return;
  390. for (const f of this.spec.customFormats) {
  391. this.dataFormats.add(f[0], f[1]);
  392. }
  393. }
  394. private initAnimations() {
  395. if (!this.spec.animations) return;
  396. for (const anim of this.spec.animations) {
  397. this.managers.animation.register(anim);
  398. }
  399. }
  400. private initDataActions() {
  401. if (!this.spec.actions) return;
  402. for (const a of this.spec.actions) {
  403. this.state.data.actions.add(a.action);
  404. }
  405. }
  406. async init() {
  407. this.subs.push(this.events.log.subscribe(e => this.log.entries = this.log.entries.push(e)));
  408. this.initCustomFormats();
  409. this.initBehaviorEvents();
  410. this.initBuiltInBehavior();
  411. (this.managers.interactivity as InteractivityManager) = new InteractivityManager(this);
  412. (this.managers.lociLabels as LociLabelManager) = new LociLabelManager(this);
  413. (this.builders.structure as StructureBuilder) = new StructureBuilder(this);
  414. this.initAnimations();
  415. this.initDataActions();
  416. await this.initBehaviors();
  417. this.log.message(`Mol* Plugin ${PLUGIN_VERSION} [${PLUGIN_VERSION_DATE.toLocaleString()}]`);
  418. if (!isProductionMode) this.log.message(`Development mode enabled`);
  419. if (isDebugMode) this.log.message(`Debug mode enabled`);
  420. }
  421. constructor(public spec: PluginSpec) {
  422. // the reason for this is that sometimes, transform params get modified inline (i.e. palette.valueLabel)
  423. // and freezing the params object causes "read-only exception"
  424. // TODO: is this the best place to do it?
  425. setAutoFreeze(false);
  426. setSaccharideCompIdMapType(this.config.get(PluginConfig.Structure.SaccharideCompIdMapType) ?? 'default');
  427. }
  428. }