representation.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. /**
  2. * Copyright (c) 2018-2021 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 { MarkerAction } from '../../../mol-util/marker-action';
  8. import { PluginContext } from '../../../mol-plugin/context';
  9. import { PluginStateObject as SO } from '../../../mol-plugin-state/objects';
  10. import { lociLabel } from '../../../mol-theme/label';
  11. import { PluginBehavior } from '../behavior';
  12. import { StateTreeSpine } from '../../../mol-state/tree/spine';
  13. import { StateSelection } from '../../../mol-state';
  14. import { ButtonsType, ModifiersKeys } from '../../../mol-util/input/input-observer';
  15. import { Binding } from '../../../mol-util/binding';
  16. import { ParamDefinition as PD } from '../../../mol-util/param-definition';
  17. import { EmptyLoci, Loci } from '../../../mol-model/loci';
  18. import { Structure, StructureElement, StructureProperties } from '../../../mol-model/structure';
  19. import { arrayMax } from '../../../mol-util/array';
  20. import { Representation } from '../../../mol-repr/representation';
  21. import { LociLabel } from '../../../mol-plugin-state/manager/loci-label';
  22. const B = ButtonsType;
  23. const M = ModifiersKeys;
  24. const Trigger = Binding.Trigger;
  25. //
  26. const DefaultHighlightLociBindings = {
  27. hoverHighlightOnly: Binding([Trigger(B.Flag.None)], 'Highlight', 'Hover element using ${triggers}'),
  28. hoverHighlightOnlyExtend: Binding([Trigger(B.Flag.None, M.create({ shift: true }))], 'Extend highlight', 'From selected to hovered element along polymer using ${triggers}'),
  29. };
  30. const HighlightLociParams = {
  31. bindings: PD.Value(DefaultHighlightLociBindings, { isHidden: true }),
  32. ignore: PD.Value<Loci['kind'][]>([], { isHidden: true }),
  33. mark: PD.Boolean(true)
  34. };
  35. type HighlightLociProps = PD.Values<typeof HighlightLociParams>
  36. export const HighlightLoci = PluginBehavior.create({
  37. name: 'representation-highlight-loci',
  38. category: 'interaction',
  39. ctor: class extends PluginBehavior.Handler<HighlightLociProps> {
  40. private lociMarkProvider = (interactionLoci: Representation.Loci, action: MarkerAction, noRender?: boolean) => {
  41. if (!this.ctx.canvas3d || !this.params.mark) return;
  42. this.ctx.canvas3d.mark(interactionLoci, action, noRender);
  43. }
  44. register() {
  45. this.subscribeObservable(this.ctx.behaviors.interaction.hover, ({ current, buttons, modifiers }) => {
  46. if (!this.ctx.canvas3d || this.ctx.isBusy) return;
  47. if (this.params.ignore?.indexOf(current.loci.kind) >= 0) {
  48. this.ctx.managers.interactivity.lociHighlights.highlightOnly({ repr: current.repr, loci: EmptyLoci });
  49. return;
  50. }
  51. let matched = false;
  52. if (Binding.match(this.params.bindings.hoverHighlightOnly, buttons, modifiers)) {
  53. // remove repr to highlight loci everywhere on hover
  54. this.ctx.managers.interactivity.lociHighlights.highlightOnly({ loci: current.loci });
  55. matched = true;
  56. }
  57. if (Binding.match(this.params.bindings.hoverHighlightOnlyExtend, buttons, modifiers)) {
  58. // remove repr to highlight loci everywhere on hover
  59. this.ctx.managers.interactivity.lociHighlights.highlightOnlyExtend({ loci: current.loci });
  60. matched = true;
  61. }
  62. if (!matched) {
  63. this.ctx.managers.interactivity.lociHighlights.highlightOnly({ repr: current.repr, loci: EmptyLoci });
  64. }
  65. });
  66. this.ctx.managers.interactivity.lociHighlights.addProvider(this.lociMarkProvider);
  67. }
  68. unregister() {
  69. this.ctx.managers.interactivity.lociHighlights.removeProvider(this.lociMarkProvider);
  70. }
  71. },
  72. params: () => HighlightLociParams,
  73. display: { name: 'Highlight Loci on Canvas' }
  74. });
  75. //
  76. const DefaultSelectLociBindings = {
  77. clickSelect: Binding.Empty,
  78. clickToggleExtend: Binding([Trigger(B.Flag.Primary, M.create({ shift: true }))], 'Toggle extended selection', '${triggers} to extend selection along polymer'),
  79. clickSelectOnly: Binding.Empty,
  80. clickToggle: Binding([Trigger(B.Flag.Primary, M.create())], 'Toggle selection', '${triggers} on element'),
  81. clickDeselect: Binding.Empty,
  82. clickDeselectAllOnEmpty: Binding([Trigger(B.Flag.Primary, M.create())], 'Deselect all', 'Click on nothing using ${triggers}'),
  83. };
  84. const SelectLociParams = {
  85. bindings: PD.Value(DefaultSelectLociBindings, { isHidden: true }),
  86. ignore: PD.Value<Loci['kind'][]>([], { isHidden: true }),
  87. mark: PD.Boolean(true)
  88. };
  89. type SelectLociProps = PD.Values<typeof SelectLociParams>
  90. export const SelectLoci = PluginBehavior.create({
  91. name: 'representation-select-loci',
  92. category: 'interaction',
  93. ctor: class extends PluginBehavior.Handler<SelectLociProps> {
  94. private spine: StateTreeSpine.Impl
  95. private lociMarkProvider = (reprLoci: Representation.Loci, action: MarkerAction, noRender?: boolean) => {
  96. if (!this.ctx.canvas3d || !this.params.mark) return;
  97. this.ctx.canvas3d.mark({ loci: reprLoci.loci }, action, noRender);
  98. }
  99. private applySelectMark(ref: string, clear?: boolean) {
  100. const cell = this.ctx.state.data.cells.get(ref);
  101. if (cell && SO.isRepresentation3D(cell.obj)) {
  102. this.spine.current = cell;
  103. const so = this.spine.getRootOfType(SO.Molecule.Structure);
  104. if (so) {
  105. if (clear) {
  106. this.lociMarkProvider({ loci: Structure.Loci(so.data) }, MarkerAction.Deselect);
  107. }
  108. const loci = this.ctx.managers.structure.selection.getLoci(so.data);
  109. this.lociMarkProvider({ loci }, MarkerAction.Select);
  110. }
  111. }
  112. }
  113. register() {
  114. const lociIsEmpty = (current: Representation.Loci) => Loci.isEmpty(current.loci);
  115. const lociIsNotEmpty = (current: Representation.Loci) => !Loci.isEmpty(current.loci);
  116. const actions: [keyof typeof DefaultSelectLociBindings, (current: Representation.Loci) => void, ((current: Representation.Loci) => boolean) | undefined][] = [
  117. ['clickSelect', current => this.ctx.managers.interactivity.lociSelects.select(current), lociIsNotEmpty],
  118. ['clickToggle', current => this.ctx.managers.interactivity.lociSelects.toggle(current), lociIsNotEmpty],
  119. ['clickToggleExtend', current => this.ctx.managers.interactivity.lociSelects.toggleExtend(current), lociIsNotEmpty],
  120. ['clickSelectOnly', current => this.ctx.managers.interactivity.lociSelects.selectOnly(current), lociIsNotEmpty],
  121. ['clickDeselect', current => this.ctx.managers.interactivity.lociSelects.deselect(current), lociIsNotEmpty],
  122. ['clickDeselectAllOnEmpty', () => this.ctx.managers.interactivity.lociSelects.deselectAll(), lociIsEmpty],
  123. ];
  124. // sort the action so that the ones with more modifiers trigger sooner.
  125. actions.sort((a, b) => {
  126. const x = this.params.bindings[a[0]], y = this.params.bindings[b[0]];
  127. const k = x.triggers.length === 0 ? 0 : arrayMax(x.triggers.map(t => M.size(t.modifiers)));
  128. const l = y.triggers.length === 0 ? 0 : arrayMax(y.triggers.map(t => M.size(t.modifiers)));
  129. return l - k;
  130. });
  131. this.subscribeObservable(this.ctx.behaviors.interaction.click, ({ current, button, modifiers }) => {
  132. if (!this.ctx.canvas3d || this.ctx.isBusy || !this.ctx.selectionMode) return;
  133. if (this.params.ignore?.indexOf(current.loci.kind) >= 0) return;
  134. // only trigger the 1st action that matches
  135. for (const [binding, action, condition] of actions) {
  136. if (Binding.match(this.params.bindings[binding], button, modifiers) && (!condition || condition(current))) {
  137. action(current);
  138. break;
  139. }
  140. }
  141. });
  142. this.ctx.managers.interactivity.lociSelects.addProvider(this.lociMarkProvider);
  143. this.subscribeObservable(this.ctx.state.events.object.created, ({ ref }) => this.applySelectMark(ref));
  144. // re-apply select-mark to all representation of an updated structure
  145. this.subscribeObservable(this.ctx.state.events.object.updated, ({ ref, obj, oldObj, oldData, action }) => {
  146. const cell = this.ctx.state.data.cells.get(ref);
  147. if (cell && SO.Molecule.Structure.is(cell.obj)) {
  148. const structure: Structure = obj.data;
  149. const oldStructure: Structure | undefined = action === 'recreate' ? oldObj?.data :
  150. action === 'in-place' ? oldData : undefined;
  151. if (oldStructure &&
  152. Structure.areEquivalent(structure, oldStructure) &&
  153. Structure.areHierarchiesEqual(structure, oldStructure)) return;
  154. const reprs = this.ctx.state.data.select(StateSelection.Generators.ofType(SO.Molecule.Structure.Representation3D, ref));
  155. for (const repr of reprs) this.applySelectMark(repr.transform.ref, true);
  156. }
  157. });
  158. }
  159. unregister() {
  160. this.ctx.managers.interactivity.lociSelects.removeProvider(this.lociMarkProvider);
  161. }
  162. constructor(ctx: PluginContext, params: SelectLociProps) {
  163. super(ctx, params);
  164. this.spine = new StateTreeSpine.Impl(ctx.state.data.cells);
  165. }
  166. },
  167. params: () => SelectLociParams,
  168. display: { name: 'Select Loci on Canvas' }
  169. });
  170. //
  171. export const DefaultLociLabelProvider = PluginBehavior.create({
  172. name: 'default-loci-label-provider',
  173. category: 'interaction',
  174. ctor: class implements PluginBehavior<undefined> {
  175. private f = {
  176. label: (loci: Loci) => {
  177. const label: string[] = [];
  178. if (StructureElement.Loci.is(loci) && loci.elements.length === 1) {
  179. const { unit: u } = loci.elements[0];
  180. const l = StructureElement.Location.create(loci.structure, u, u.elements[0]);
  181. const name = StructureProperties.entity.pdbx_description(l).join(', ');
  182. label.push(name);
  183. }
  184. label.push(lociLabel(loci));
  185. return label.filter(l => !!l).join('</br>');
  186. },
  187. group: (label: LociLabel) => label.toString().replace(/Model [0-9]+/g, 'Models'),
  188. priority: 100
  189. };
  190. register() { this.ctx.managers.lociLabels.addProvider(this.f); }
  191. unregister() { this.ctx.managers.lociLabels.removeProvider(this.f); }
  192. constructor(protected ctx: PluginContext) { }
  193. },
  194. display: { name: 'Provide Default Loci Label' }
  195. });
  196. //
  197. const DefaultFocusLociBindings = {
  198. clickFocus: Binding([
  199. Trigger(B.Flag.Primary, M.create()),
  200. ], 'Representation Focus', 'Click element using ${triggers}'),
  201. clickFocusAdd: Binding([
  202. Trigger(B.Flag.Primary, M.create({ shift: true })),
  203. ], 'Representation Focus Add', 'Click element using ${triggers}'),
  204. clickFocusSelectMode: Binding([
  205. // default is empty
  206. ], 'Representation Focus', 'Click element using ${triggers}'),
  207. clickFocusAddSelectMode: Binding([
  208. // default is empty
  209. ], 'Representation Focus Add', 'Click element using ${triggers}'),
  210. };
  211. const FocusLociParams = {
  212. bindings: PD.Value(DefaultFocusLociBindings, { isHidden: true }),
  213. };
  214. type FocusLociProps = PD.Values<typeof FocusLociParams>
  215. export const FocusLoci = PluginBehavior.create<FocusLociProps>({
  216. name: 'representation-focus-loci',
  217. category: 'interaction',
  218. ctor: class extends PluginBehavior.Handler<FocusLociProps> {
  219. register(): void {
  220. this.subscribeObservable(this.ctx.behaviors.interaction.click, ({ current, button, modifiers }) => {
  221. const { clickFocus, clickFocusAdd, clickFocusSelectMode, clickFocusAddSelectMode } = this.params.bindings;
  222. // only apply structure focus for appropriate granularity
  223. const { granularity } = this.ctx.managers.interactivity.props;
  224. if (granularity !== 'residue' && granularity !== 'element') return;
  225. const binding = this.ctx.selectionMode ? clickFocusSelectMode : clickFocus;
  226. const matched = Binding.match(binding, button, modifiers);
  227. const bindingAdd = this.ctx.selectionMode ? clickFocusAddSelectMode : clickFocusAdd;
  228. const matchedAdd = Binding.match(bindingAdd, button, modifiers);
  229. if (!matched && !matchedAdd) return;
  230. const loci = Loci.normalize(current.loci, 'residue');
  231. const entry = this.ctx.managers.structure.focus.current;
  232. if (entry && Loci.areEqual(entry.loci, loci)) {
  233. this.ctx.managers.structure.focus.clear();
  234. } else {
  235. if (matched) {
  236. this.ctx.managers.structure.focus.setFromLoci(loci);
  237. } else {
  238. this.ctx.managers.structure.focus.addFromLoci(loci);
  239. // focus-add is not handled in camera behavior, doing it here
  240. const current = this.ctx.managers.structure.focus.current?.loci;
  241. if (current) this.ctx.managers.camera.focusLoci(current);
  242. }
  243. }
  244. });
  245. }
  246. },
  247. params: () => FocusLociParams,
  248. display: { name: 'Representation Focus Loci on Canvas' }
  249. });