state.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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 { Structure } from '../../../mol-model/structure';
  8. import { PluginStateSnapshotManager } from '../../../mol-plugin-state/manager/snapshots';
  9. import { PluginStateObject as SO } from '../../../mol-plugin-state/objects';
  10. import { State, StateTransform, StateTree } from '../../../mol-state';
  11. import { getFormattedTime } from '../../../mol-util/date';
  12. import { download } from '../../../mol-util/download';
  13. import { urlCombine } from '../../../mol-util/url';
  14. import { PluginCommands } from '../../commands';
  15. import { PluginConfig } from '../../config';
  16. import { PluginContext } from '../../context';
  17. export function registerDefault(ctx: PluginContext) {
  18. SyncBehaviors(ctx);
  19. SetCurrentObject(ctx);
  20. Update(ctx);
  21. ApplyAction(ctx);
  22. RemoveObject(ctx);
  23. ToggleExpanded(ctx);
  24. ToggleVisibility(ctx);
  25. Highlight(ctx);
  26. ClearHighlights(ctx);
  27. Snapshots(ctx);
  28. }
  29. export function SyncBehaviors(ctx: PluginContext) {
  30. ctx.state.events.object.created.subscribe(o => {
  31. if (!SO.isBehavior(o.obj)) return;
  32. o.obj.data.register(o.ref);
  33. });
  34. ctx.state.events.object.removed.subscribe(o => {
  35. if (!SO.isBehavior(o.obj)) return;
  36. o.obj.data.unregister();
  37. });
  38. ctx.state.events.object.updated.subscribe(o => {
  39. if (o.action === 'recreate') {
  40. if (o.oldObj && SO.isBehavior(o.oldObj)) o.oldObj.data.unregister();
  41. if (o.obj && SO.isBehavior(o.obj)) o.obj.data.register(o.ref);
  42. }
  43. });
  44. }
  45. export function SetCurrentObject(ctx: PluginContext) {
  46. PluginCommands.State.SetCurrentObject.subscribe(ctx, ({ state, ref }) => state.setCurrent(ref));
  47. }
  48. export function Update(ctx: PluginContext) {
  49. PluginCommands.State.Update.subscribe(ctx, ({ state, tree, options }) => ctx.runTask(state.updateTree(tree, options)));
  50. }
  51. export function ApplyAction(ctx: PluginContext) {
  52. PluginCommands.State.ApplyAction.subscribe(ctx, ({ state, action, ref }) => ctx.runTask(state.applyAction(action.action, action.params, ref)));
  53. }
  54. export function RemoveObject(ctx: PluginContext) {
  55. function remove(state: State, ref: string) {
  56. const tree = state.build().delete(ref);
  57. return ctx.runTask(state.updateTree(tree));
  58. }
  59. PluginCommands.State.RemoveObject.subscribe(ctx, ({ state, ref, removeParentGhosts }) => {
  60. if (removeParentGhosts) {
  61. const tree = state.tree;
  62. let curr = tree.transforms.get(ref);
  63. if (curr.parent === ref) return remove(state, ref);
  64. while (true) {
  65. const children = tree.children.get(curr.parent);
  66. if (curr.parent === curr.ref || children.size > 1) return remove(state, curr.ref);
  67. const parent = tree.transforms.get(curr.parent);
  68. // TODO: should this use "cell state" instead?
  69. if (!parent.state.isGhost) return remove(state, curr.ref);
  70. curr = parent;
  71. }
  72. } else {
  73. return remove(state, ref);
  74. }
  75. });
  76. }
  77. export function ToggleExpanded(ctx: PluginContext) {
  78. PluginCommands.State.ToggleExpanded.subscribe(ctx, ({ state, ref }) => state.updateCellState(ref, ({ isCollapsed }) => ({ isCollapsed: !isCollapsed })));
  79. }
  80. export function ToggleVisibility(ctx: PluginContext) {
  81. PluginCommands.State.ToggleVisibility.subscribe(ctx, ({ state, ref }) => setSubtreeVisibility(state, ref, !state.cells.get(ref)!.state.isHidden));
  82. }
  83. export function setSubtreeVisibility(state: State, root: StateTransform.Ref, value: boolean) {
  84. StateTree.doPreOrder(state.tree, state.transforms.get(root), { state, value }, setVisibilityVisitor);
  85. }
  86. function setVisibilityVisitor(t: StateTransform, tree: StateTree, ctx: { state: State, value: boolean }) {
  87. ctx.state.updateCellState(t.ref, { isHidden: ctx.value });
  88. }
  89. export function Highlight(ctx: PluginContext) {
  90. PluginCommands.Interactivity.Object.Highlight.subscribe(ctx, ({ state, ref }) => {
  91. ctx.managers.interactivity.lociHighlights.clearHighlights();
  92. const refs = typeof ref === 'string' ? [ref] : ref;
  93. for (const r of refs) {
  94. const cell = state.cells.get(r);
  95. if (!cell) continue;
  96. if (SO.Molecule.Structure.is(cell.obj)) {
  97. ctx.managers.interactivity.lociHighlights.highlight({ loci: Structure.Loci(cell.obj.data) }, false);
  98. } else if (cell && SO.isRepresentation3D(cell.obj)) {
  99. const { repr } = cell.obj.data;
  100. ctx.managers.interactivity.lociHighlights.highlight({ loci: repr.getLoci(), repr }, false);
  101. } else if (SO.Molecule.Structure.Selections.is(cell.obj)) {
  102. for (const entry of cell.obj.data) {
  103. ctx.managers.interactivity.lociHighlights.highlight({ loci: entry.loci }, false);
  104. }
  105. }
  106. }
  107. // TODO: highlight volumes?
  108. // TODO: select structures of subtree?
  109. });
  110. }
  111. export function ClearHighlights(ctx: PluginContext) {
  112. PluginCommands.Interactivity.ClearHighlights.subscribe(ctx, () => {
  113. ctx.managers.interactivity.lociHighlights.clearHighlights();
  114. });
  115. }
  116. export function Snapshots(ctx: PluginContext) {
  117. ctx.config.set(PluginConfig.State.CurrentServer, ctx.config.get(PluginConfig.State.DefaultServer));
  118. PluginCommands.State.Snapshots.Clear.subscribe(ctx, () => {
  119. ctx.managers.snapshot.clear();
  120. });
  121. PluginCommands.State.Snapshots.Remove.subscribe(ctx, ({ id }) => {
  122. ctx.managers.snapshot.remove(id);
  123. });
  124. PluginCommands.State.Snapshots.Add.subscribe(ctx, ({ name, description, params }) => {
  125. const entry = PluginStateSnapshotManager.Entry(ctx.state.getSnapshot(params), { name, description });
  126. ctx.managers.snapshot.add(entry);
  127. });
  128. PluginCommands.State.Snapshots.Replace.subscribe(ctx, ({ id, params }) => {
  129. ctx.managers.snapshot.replace(id, ctx.state.getSnapshot(params));
  130. });
  131. PluginCommands.State.Snapshots.Move.subscribe(ctx, ({ id, dir }) => {
  132. ctx.managers.snapshot.move(id, dir);
  133. });
  134. PluginCommands.State.Snapshots.Apply.subscribe(ctx, ({ id }) => {
  135. const snapshot = ctx.managers.snapshot.setCurrent(id);
  136. if (!snapshot) return;
  137. return ctx.state.setSnapshot(snapshot);
  138. });
  139. PluginCommands.State.Snapshots.Upload.subscribe(ctx, ({ name, description, playOnLoad, serverUrl, params }) => {
  140. return fetch(urlCombine(serverUrl, `set?name=${encodeURIComponent(name || '')}&description=${encodeURIComponent(description || '')}`), {
  141. method: 'POST',
  142. mode: 'cors',
  143. referrer: 'no-referrer',
  144. headers: { 'Content-Type': 'application/json; charset=utf-8' },
  145. body: JSON.stringify(ctx.managers.snapshot.getStateSnapshot({ name, description, playOnLoad }))
  146. }) as any as Promise<void>;
  147. });
  148. PluginCommands.State.Snapshots.Fetch.subscribe(ctx, async ({ url }) => {
  149. const json = await ctx.runTask(ctx.fetch({ url, type: 'json' })); // fetch(url, { referrer: 'no-referrer' });
  150. await ctx.managers.snapshot.setStateSnapshot(json.data);
  151. });
  152. PluginCommands.State.Snapshots.DownloadToFile.subscribe(ctx, async ({ name, type }) => {
  153. const filename = `mol-star_state_${(name || getFormattedTime())}.${type === 'json' ? 'molj' : 'molx'}`;
  154. const data = await ctx.managers.snapshot.serialize(type);
  155. download(data, `${filename}`);
  156. });
  157. PluginCommands.State.Snapshots.OpenFile.subscribe(ctx, ({ file }) => {
  158. return ctx.managers.snapshot.open(file);
  159. });
  160. }