selection.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. /**
  2. * Copyright (c) 2019-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 { OrderedSet } from '../../../mol-data/int';
  8. import { BoundaryHelper } from '../../../mol-math/geometry/boundary-helper';
  9. import { Vec3 } from '../../../mol-math/linear-algebra';
  10. import { PrincipalAxes } from '../../../mol-math/linear-algebra/matrix/principal-axes';
  11. import { EmptyLoci, Loci } from '../../../mol-model/loci';
  12. import { QueryContext, Structure, StructureElement, StructureQuery, StructureSelection } from '../../../mol-model/structure';
  13. import { PluginContext } from '../../../mol-plugin/context';
  14. import { StateObjectRef } from '../../../mol-state';
  15. import { Task } from '../../../mol-task';
  16. import { structureElementStatsLabel } from '../../../mol-theme/label';
  17. import { arrayRemoveAtInPlace } from '../../../mol-util/array';
  18. import { StatefulPluginComponent } from '../../component';
  19. import { StructureSelectionQuery } from '../../helpers/structure-selection-query';
  20. import { PluginStateObject as PSO } from '../../objects';
  21. import { UUID } from '../../../mol-util';
  22. import { StructureRef } from './hierarchy-state';
  23. import { Boundary } from '../../../mol-math/geometry/boundary';
  24. import { iterableToArray } from '../../../mol-data/util';
  25. interface StructureSelectionManagerState {
  26. entries: Map<string, SelectionEntry>,
  27. additionsHistory: StructureSelectionHistoryEntry[],
  28. stats?: SelectionStats
  29. }
  30. const boundaryHelper = new BoundaryHelper('98');
  31. const HISTORY_CAPACITY = 24;
  32. export type StructureSelectionModifier = 'add' | 'remove' | 'intersect' | 'set'
  33. export class StructureSelectionManager extends StatefulPluginComponent<StructureSelectionManagerState> {
  34. readonly events = {
  35. changed: this.ev<undefined>(),
  36. additionsHistoryUpdated: this.ev<undefined>(),
  37. loci: {
  38. add: this.ev<StructureElement.Loci>(),
  39. remove: this.ev<StructureElement.Loci>(),
  40. clear: this.ev<undefined>()
  41. }
  42. };
  43. private referenceLoci: StructureElement.Loci | undefined;
  44. get entries() { return this.state.entries; }
  45. get additionsHistory() { return this.state.additionsHistory; }
  46. get stats() {
  47. if (this.state.stats) return this.state.stats;
  48. this.state.stats = this.calcStats();
  49. return this.state.stats;
  50. }
  51. private getEntry(s: Structure) {
  52. // ignore decorators to get stable ref
  53. const cell = this.plugin.helpers.substructureParent.get(s, true);
  54. if (!cell) return;
  55. const ref = cell.transform.ref;
  56. if (!this.entries.has(ref)) {
  57. const entry = new SelectionEntry(StructureElement.Loci(s, []));
  58. this.entries.set(ref, entry);
  59. return entry;
  60. }
  61. return this.entries.get(ref)!;
  62. }
  63. private calcStats(): SelectionStats {
  64. let structureCount = 0;
  65. let elementCount = 0;
  66. const stats = StructureElement.Stats.create();
  67. this.entries.forEach(v => {
  68. const { elements } = v.selection;
  69. if (elements.length) {
  70. structureCount += 1;
  71. for (let i = 0, il = elements.length; i < il; ++i) {
  72. elementCount += OrderedSet.size(elements[i].indices);
  73. }
  74. StructureElement.Stats.add(stats, stats, StructureElement.Stats.ofLoci(v.selection));
  75. }
  76. });
  77. const label = structureElementStatsLabel(stats, { countsOnly: true });
  78. return { structureCount, elementCount, label };
  79. }
  80. private add(loci: Loci): boolean {
  81. if (!StructureElement.Loci.is(loci)) return false;
  82. const entry = this.getEntry(loci.structure);
  83. if (!entry) return false;
  84. const sel = entry.selection;
  85. entry.selection = StructureElement.Loci.union(entry.selection, loci);
  86. this.tryAddHistory(loci);
  87. this.referenceLoci = loci;
  88. this.events.loci.add.next(loci);
  89. return !StructureElement.Loci.areEqual(sel, entry.selection);
  90. }
  91. private remove(loci: Loci) {
  92. if (!StructureElement.Loci.is(loci)) return false;
  93. const entry = this.getEntry(loci.structure);
  94. if (!entry) return false;
  95. const sel = entry.selection;
  96. entry.selection = StructureElement.Loci.subtract(entry.selection, loci);
  97. // this.addHistory(loci);
  98. this.referenceLoci = loci;
  99. this.events.loci.remove.next(loci);
  100. return !StructureElement.Loci.areEqual(sel, entry.selection);
  101. }
  102. private intersect(loci: Loci): boolean {
  103. if (!StructureElement.Loci.is(loci)) return false;
  104. const entry = this.getEntry(loci.structure);
  105. if (!entry) return false;
  106. const sel = entry.selection;
  107. entry.selection = StructureElement.Loci.intersect(entry.selection, loci);
  108. // this.addHistory(loci);
  109. this.referenceLoci = loci;
  110. return !StructureElement.Loci.areEqual(sel, entry.selection);
  111. }
  112. private set(loci: Loci) {
  113. if (!StructureElement.Loci.is(loci)) return false;
  114. const entry = this.getEntry(loci.structure);
  115. if (!entry) return false;
  116. const sel = entry.selection;
  117. entry.selection = loci;
  118. this.tryAddHistory(loci);
  119. this.referenceLoci = undefined;
  120. return !StructureElement.Loci.areEqual(sel, entry.selection);
  121. }
  122. modifyHistory(entry: StructureSelectionHistoryEntry, action: 'remove' | 'up' | 'down', modulus?: number, groupByStructure = false) {
  123. const history = this.additionsHistory;
  124. const idx = history.indexOf(entry);
  125. if (idx < 0) return;
  126. let swapWith: number | undefined = void 0;
  127. switch (action) {
  128. case 'remove': arrayRemoveAtInPlace(history, idx); break;
  129. case 'up': swapWith = idx - 1; break;
  130. case 'down': swapWith = idx + 1; break;
  131. }
  132. if (swapWith !== void 0) {
  133. const mod = modulus ? Math.min(history.length, modulus) : history.length;
  134. while (true) {
  135. swapWith = swapWith % mod;
  136. if (swapWith < 0) swapWith += mod;
  137. if (!groupByStructure || history[idx].loci.structure === history[swapWith].loci.structure) {
  138. const t = history[idx];
  139. history[idx] = history[swapWith];
  140. history[swapWith] = t;
  141. break;
  142. } else {
  143. swapWith += action === 'up' ? -1 : +1;
  144. }
  145. }
  146. }
  147. this.events.additionsHistoryUpdated.next(void 0);
  148. }
  149. private tryAddHistory(loci: StructureElement.Loci) {
  150. if (Loci.isEmpty(loci)) return;
  151. let idx = 0, entry: StructureSelectionHistoryEntry | undefined = void 0;
  152. for (const l of this.additionsHistory) {
  153. if (Loci.areEqual(l.loci, loci)) {
  154. entry = l;
  155. break;
  156. }
  157. idx++;
  158. }
  159. if (entry) {
  160. // move to top
  161. arrayRemoveAtInPlace(this.additionsHistory, idx);
  162. this.additionsHistory.unshift(entry);
  163. this.events.additionsHistoryUpdated.next(void 0);
  164. return;
  165. }
  166. const stats = StructureElement.Stats.ofLoci(loci);
  167. const label = structureElementStatsLabel(stats, { reverse: true });
  168. this.additionsHistory.unshift({ id: UUID.create22(), loci, label });
  169. if (this.additionsHistory.length > HISTORY_CAPACITY) this.additionsHistory.pop();
  170. this.events.additionsHistoryUpdated.next(void 0);
  171. }
  172. private clearHistory() {
  173. if (this.state.additionsHistory.length !== 0) {
  174. this.state.additionsHistory = [];
  175. this.events.additionsHistoryUpdated.next(void 0);
  176. }
  177. }
  178. private clearHistoryForStructure(structure: Structure) {
  179. const historyEntryToRemove: StructureSelectionHistoryEntry[] = [];
  180. for (const e of this.state.additionsHistory) {
  181. if (e.loci.structure.root === structure.root) {
  182. historyEntryToRemove.push(e);
  183. }
  184. }
  185. for (const e of historyEntryToRemove) {
  186. this.modifyHistory(e, 'remove');
  187. }
  188. if (historyEntryToRemove.length !== 0) {
  189. this.events.additionsHistoryUpdated.next(void 0);
  190. }
  191. }
  192. private onRemove(ref: string, obj: PSO.Molecule.Structure | undefined) {
  193. if (this.entries.has(ref)) {
  194. this.entries.delete(ref);
  195. if (obj?.data) {
  196. this.clearHistoryForStructure(obj.data);
  197. }
  198. if (this.referenceLoci?.structure === obj?.data) {
  199. this.referenceLoci = undefined;
  200. }
  201. this.state.stats = void 0;
  202. this.events.changed.next(void 0);
  203. }
  204. }
  205. private onUpdate(ref: string, oldObj: PSO.Molecule.Structure | undefined, obj: PSO.Molecule.Structure) {
  206. // no change to structure
  207. if (oldObj === obj || oldObj?.data === obj.data) return;
  208. // ignore decorators to get stable ref
  209. const cell = this.plugin.helpers.substructureParent.get(obj.data, true);
  210. if (!cell) return;
  211. // only need to update the root
  212. if (ref !== cell.transform.ref) return;
  213. if (!this.entries.has(ref)) return;
  214. // use structure from last decorator as reference
  215. const structure = this.plugin.helpers.substructureParent.get(obj.data)?.obj?.data;
  216. if (!structure) return;
  217. // oldObj is not defined for inserts (e.g. TransformStructureConformation)
  218. if (!oldObj?.data || Structure.areUnitIdsAndIndicesEqual(oldObj.data, obj.data)) {
  219. this.entries.set(ref, remapSelectionEntry(this.entries.get(ref)!, structure));
  220. // remap referenceLoci & prevHighlight if needed and possible
  221. if (this.referenceLoci?.structure.root === structure.root) {
  222. this.referenceLoci = StructureElement.Loci.remap(this.referenceLoci, structure);
  223. }
  224. // remap history locis if needed and possible
  225. let changedHistory = false;
  226. for (const e of this.state.additionsHistory) {
  227. if (e.loci.structure.root === structure.root) {
  228. e.loci = StructureElement.Loci.remap(e.loci, structure);
  229. changedHistory = true;
  230. }
  231. }
  232. if (changedHistory) this.events.additionsHistoryUpdated.next(void 0);
  233. } else {
  234. // clear the selection for ref
  235. this.entries.set(ref, new SelectionEntry(StructureElement.Loci(structure, [])));
  236. if (this.referenceLoci?.structure.root === structure.root) {
  237. this.referenceLoci = undefined;
  238. }
  239. this.clearHistoryForStructure(structure);
  240. this.state.stats = void 0;
  241. this.events.changed.next(void 0);
  242. }
  243. }
  244. /** Removes all selections and returns them */
  245. clear() {
  246. const keys = this.entries.keys();
  247. const selections: StructureElement.Loci[] = [];
  248. while (true) {
  249. const k = keys.next();
  250. if (k.done) break;
  251. const s = this.entries.get(k.value)!;
  252. if (!StructureElement.Loci.isEmpty(s.selection)) selections.push(s.selection);
  253. s.selection = StructureElement.Loci(s.selection.structure, []);
  254. }
  255. this.referenceLoci = undefined;
  256. this.state.stats = void 0;
  257. this.events.changed.next(void 0);
  258. this.events.loci.clear.next(void 0);
  259. this.clearHistory();
  260. return selections;
  261. }
  262. getLoci(structure: Structure) {
  263. const entry = this.getEntry(structure);
  264. if (!entry) return EmptyLoci;
  265. return entry.selection;
  266. }
  267. getStructure(structure: Structure) {
  268. const entry = this.getEntry(structure);
  269. if (!entry) return;
  270. return entry.structure;
  271. }
  272. structureHasSelection(structure: StructureRef) {
  273. const s = structure.cell?.obj?.data;
  274. if (!s) return false;
  275. const entry = this.getEntry(s);
  276. return !!entry && !StructureElement.Loci.isEmpty(entry.selection);
  277. }
  278. has(loci: Loci) {
  279. if (StructureElement.Loci.is(loci)) {
  280. const entry = this.getEntry(loci.structure);
  281. if (entry) {
  282. return StructureElement.Loci.isSubset(entry.selection, loci);
  283. }
  284. }
  285. return false;
  286. }
  287. tryGetRange(loci: Loci): StructureElement.Loci | undefined {
  288. if (!StructureElement.Loci.is(loci)) return;
  289. if (loci.elements.length !== 1) return;
  290. const entry = this.getEntry(loci.structure);
  291. if (!entry) return;
  292. const xs = loci.elements[0];
  293. if (!xs) return;
  294. const ref = this.referenceLoci;
  295. if (!ref || !StructureElement.Loci.is(ref) || ref.structure !== loci.structure) return;
  296. let e: StructureElement.Loci['elements'][0] | undefined;
  297. for (const _e of ref.elements) {
  298. if (xs.unit === _e.unit) {
  299. e = _e;
  300. break;
  301. }
  302. }
  303. if (!e) return;
  304. if (xs.unit !== e.unit) return;
  305. return getElementRange(loci.structure, e, xs);
  306. }
  307. /** Count of all selected elements */
  308. elementCount() {
  309. let count = 0;
  310. this.entries.forEach(v => {
  311. count += StructureElement.Loci.size(v.selection);
  312. });
  313. return count;
  314. }
  315. getBoundary() {
  316. const min = Vec3.create(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  317. const max = Vec3.create(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  318. boundaryHelper.reset();
  319. const boundaries: Boundary[] = [];
  320. this.entries.forEach(v => {
  321. const loci = v.selection;
  322. if (!StructureElement.Loci.isEmpty(loci)) {
  323. boundaries.push(StructureElement.Loci.getBoundary(loci));
  324. }
  325. });
  326. for (let i = 0, il = boundaries.length; i < il; ++i) {
  327. const { box, sphere } = boundaries[i];
  328. Vec3.min(min, min, box.min);
  329. Vec3.max(max, max, box.max);
  330. boundaryHelper.includePositionRadius(sphere.center, sphere.radius);
  331. }
  332. boundaryHelper.finishedIncludeStep();
  333. for (let i = 0, il = boundaries.length; i < il; ++i) {
  334. const { sphere } = boundaries[i];
  335. boundaryHelper.radiusPositionRadius(sphere.center, sphere.radius);
  336. }
  337. return { box: { min, max }, sphere: boundaryHelper.getSphere() };
  338. }
  339. getPrincipalAxes(): PrincipalAxes {
  340. const values = iterableToArray(this.entries.values());
  341. return StructureElement.Loci.getPrincipalAxesMany(values.map(v => v.selection));
  342. }
  343. modify(modifier: StructureSelectionModifier, loci: Loci) {
  344. let changed = false;
  345. switch (modifier) {
  346. case 'add': changed = this.add(loci); break;
  347. case 'remove': changed = this.remove(loci); break;
  348. case 'intersect': changed = this.intersect(loci); break;
  349. case 'set': changed = this.set(loci); break;
  350. }
  351. if (changed) {
  352. this.state.stats = void 0;
  353. this.events.changed.next(void 0);
  354. }
  355. }
  356. private get applicableStructures() {
  357. return this.plugin.managers.structure.hierarchy.selection.structures
  358. .filter(s => !!s.cell.obj)
  359. .map(s => s.cell.obj!.data);
  360. }
  361. private triggerInteraction(modifier: StructureSelectionModifier, loci: Loci, applyGranularity = true) {
  362. switch (modifier) {
  363. case 'add':
  364. this.plugin.managers.interactivity.lociSelects.select({ loci }, applyGranularity);
  365. break;
  366. case 'remove':
  367. this.plugin.managers.interactivity.lociSelects.deselect({ loci }, applyGranularity);
  368. break;
  369. case 'intersect':
  370. this.plugin.managers.interactivity.lociSelects.selectJoin({ loci }, applyGranularity);
  371. break;
  372. case 'set':
  373. this.plugin.managers.interactivity.lociSelects.selectOnly({ loci }, applyGranularity);
  374. break;
  375. }
  376. }
  377. fromLoci(modifier: StructureSelectionModifier, loci: Loci, applyGranularity = true) {
  378. this.triggerInteraction(modifier, loci, applyGranularity);
  379. }
  380. fromCompiledQuery(modifier: StructureSelectionModifier, query: StructureQuery, applyGranularity = true) {
  381. for (const s of this.applicableStructures) {
  382. const loci = query(new QueryContext(s));
  383. this.triggerInteraction(modifier, StructureSelection.toLociWithSourceUnits(loci), applyGranularity);
  384. }
  385. }
  386. fromSelectionQuery(modifier: StructureSelectionModifier, query: StructureSelectionQuery, applyGranularity = true) {
  387. this.plugin.runTask(Task.create('Structure Selection', async runtime => {
  388. for (const s of this.applicableStructures) {
  389. const loci = await query.getSelection(this.plugin, runtime, s);
  390. this.triggerInteraction(modifier, StructureSelection.toLociWithSourceUnits(loci), applyGranularity);
  391. }
  392. }));
  393. }
  394. fromSelections(ref: StateObjectRef<PSO.Molecule.Structure.Selections>) {
  395. const cell = StateObjectRef.resolveAndCheck(this.plugin.state.data, ref);
  396. if (!cell || !cell.obj) return;
  397. if (!PSO.Molecule.Structure.Selections.is(cell.obj)) {
  398. console.warn('fromSelections applied to wrong object type.', cell.obj);
  399. return;
  400. }
  401. this.clear();
  402. for (const s of cell.obj?.data) {
  403. this.fromLoci('set', s.loci);
  404. }
  405. }
  406. constructor(private plugin: PluginContext) {
  407. super({ entries: new Map(), additionsHistory: [], stats: SelectionStats() });
  408. // listen to events from substructureParent helper to ensure it is updated
  409. plugin.helpers.substructureParent.events.removed.subscribe(e => this.onRemove(e.ref, e.obj));
  410. plugin.helpers.substructureParent.events.updated.subscribe(e => this.onUpdate(e.ref, e.oldObj, e.obj));
  411. }
  412. }
  413. interface SelectionStats {
  414. structureCount: number,
  415. elementCount: number,
  416. label: string
  417. }
  418. function SelectionStats(): SelectionStats { return { structureCount: 0, elementCount: 0, label: 'Nothing Selected' }; };
  419. class SelectionEntry {
  420. private _selection: StructureElement.Loci;
  421. private _structure?: Structure = void 0;
  422. get selection() { return this._selection; }
  423. set selection(value: StructureElement.Loci) {
  424. this._selection = value;
  425. this._structure = void 0;
  426. }
  427. get structure(): Structure | undefined {
  428. if (this._structure) return this._structure;
  429. if (Loci.isEmpty(this._selection)) {
  430. this._structure = void 0;
  431. } else {
  432. this._structure = StructureElement.Loci.toStructure(this._selection);
  433. }
  434. return this._structure;
  435. }
  436. constructor(selection: StructureElement.Loci) {
  437. this._selection = selection;
  438. }
  439. }
  440. export interface StructureSelectionHistoryEntry {
  441. id: UUID,
  442. loci: StructureElement.Loci,
  443. label: string
  444. }
  445. /** remap `selection-entry` to be related to `structure` if possible */
  446. function remapSelectionEntry(e: SelectionEntry, s: Structure): SelectionEntry {
  447. return new SelectionEntry(StructureElement.Loci.remap(e.selection, s));
  448. }
  449. /**
  450. * Assumes `ref` and `ext` belong to the same unit in the same structure
  451. */
  452. function getElementRange(structure: Structure, ref: StructureElement.Loci['elements'][0], ext: StructureElement.Loci['elements'][0]) {
  453. const min = Math.min(OrderedSet.min(ref.indices), OrderedSet.min(ext.indices));
  454. const max = Math.max(OrderedSet.max(ref.indices), OrderedSet.max(ext.indices));
  455. return StructureElement.Loci(structure, [{
  456. unit: ref.unit,
  457. indices: OrderedSet.ofRange(min as StructureElement.UnitIndex, max as StructureElement.UnitIndex)
  458. }]);
  459. }