component.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. /**
  2. * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { VisualQualityOptions } from '../../../mol-geo/geometry/base';
  7. import { InteractionsProvider } from '../../../mol-model-props/computed/interactions';
  8. import { Structure, StructureElement, StructureSelection } from '../../../mol-model/structure';
  9. import { structureAreEqual, structureAreIntersecting, structureIntersect, structureSubtract, structureUnion } from '../../../mol-model/structure/query/utils/structure-set';
  10. import { setSubtreeVisibility } from '../../../mol-plugin/behavior/static/state';
  11. import { PluginContext } from '../../../mol-plugin/context';
  12. import { StateBuilder, StateObjectRef, StateTransformer } from '../../../mol-state';
  13. import { Task } from '../../../mol-task';
  14. import { ColorTheme } from '../../../mol-theme/color';
  15. import { SizeTheme } from '../../../mol-theme/size';
  16. import { UUID } from '../../../mol-util';
  17. import { ColorNames } from '../../../mol-util/color/names';
  18. import { objectForEach } from '../../../mol-util/object';
  19. import { ParamDefinition as PD } from '../../../mol-util/param-definition';
  20. import { StructureRepresentationPresetProvider } from '../../builder/structure/representation-preset';
  21. import { StatefulPluginComponent } from '../../component';
  22. import { StructureComponentParams } from '../../helpers/structure-component';
  23. import { clearStructureOverpaint, setStructureOverpaint } from '../../helpers/structure-overpaint';
  24. import { createStructureColorThemeParams, createStructureSizeThemeParams } from '../../helpers/structure-representation-params';
  25. import { StructureSelectionQueries, StructureSelectionQuery } from '../../helpers/structure-selection-query';
  26. import { StructureRepresentation3D } from '../../transforms/representation';
  27. import { StructureHierarchyRef, StructureComponentRef, StructureRef, StructureRepresentationRef } from './hierarchy-state';
  28. import { Clipping } from '../../../mol-theme/clipping';
  29. import { setStructureClipping } from '../../helpers/structure-clipping';
  30. export { StructureComponentManager };
  31. interface StructureComponentManagerState {
  32. options: StructureComponentManager.Options
  33. }
  34. class StructureComponentManager extends StatefulPluginComponent<StructureComponentManagerState> {
  35. readonly events = {
  36. optionsUpdated: this.ev<undefined>()
  37. }
  38. get currentStructures() {
  39. return this.plugin.managers.structure.hierarchy.selection.structures;
  40. }
  41. get pivotStructure(): StructureRef | undefined {
  42. return this.currentStructures[0];
  43. }
  44. async setOptions(options: StructureComponentManager.Options) {
  45. const interactionChanged = options.interactions !== this.state.options.interactions;
  46. this.updateState({ options });
  47. this.events.optionsUpdated.next();
  48. const update = this.dataState.build();
  49. for (const s of this.currentStructures) {
  50. for (const c of s.components) {
  51. this.updateReprParams(update, c);
  52. }
  53. }
  54. return this.plugin.dataTransaction(async () => {
  55. await update.commit();
  56. if (interactionChanged) await this.updateInterationProps();
  57. });
  58. }
  59. private updateReprParams(update: StateBuilder.Root, component: StructureComponentRef) {
  60. const { showHydrogens, visualQuality: quality } = this.state.options;
  61. const ignoreHydrogens = !showHydrogens;
  62. for (const r of component.representations) {
  63. if (r.cell.transform.transformer !== StructureRepresentation3D) continue;
  64. const params = r.cell.transform.params as StateTransformer.Params<StructureRepresentation3D>;
  65. if (!!params.type.params.ignoreHydrogens !== ignoreHydrogens || params.type.params.quality !== quality) {
  66. update.to(r.cell).update(old => {
  67. old.type.params.ignoreHydrogens = ignoreHydrogens;
  68. old.type.params.quality = quality;
  69. });
  70. }
  71. }
  72. }
  73. private async updateInterationProps() {
  74. for (const s of this.currentStructures) {
  75. const interactionParams = InteractionsProvider.getParams(s.cell.obj?.data!);
  76. if (s.properties) {
  77. const oldParams = s.properties.cell.transform.params?.properties[InteractionsProvider.descriptor.name];
  78. if (PD.areEqual(interactionParams, oldParams, this.state.options.interactions)) continue;
  79. await this.dataState.build().to(s.properties.cell)
  80. .update(old => {
  81. old.properties[InteractionsProvider.descriptor.name] = this.state.options.interactions;
  82. })
  83. .commit();
  84. } else {
  85. const pd = this.plugin.customStructureProperties.getParams(s.cell.obj?.data);
  86. const params = PD.getDefaultValues(pd);
  87. if (PD.areEqual(interactionParams, params.properties[InteractionsProvider.descriptor.name], this.state.options.interactions)) continue;
  88. params.properties[InteractionsProvider.descriptor.name] = this.state.options.interactions;
  89. await this.plugin.builders.structure.insertStructureProperties(s.cell, params);
  90. }
  91. }
  92. }
  93. applyPreset<P extends StructureRepresentationPresetProvider>(structures: ReadonlyArray<StructureRef>, provider: P, params?: StructureRepresentationPresetProvider.Params<P>): Promise<any> {
  94. return this.plugin.dataTransaction(async () => {
  95. for (const s of structures) {
  96. const preset = await this.plugin.builders.structure.representation.applyPreset(s.cell, provider, params);
  97. await this.syncPreset(s, preset);
  98. }
  99. }, { canUndo: 'Preset' });
  100. }
  101. private syncPreset(root: StructureRef, preset?: StructureRepresentationPresetProvider.Result) {
  102. if (!preset || !preset.components) return this.clearComponents([root]);
  103. const keptRefs = new Set<string>();
  104. objectForEach(preset.components, c => {
  105. if (c) keptRefs.add(c.ref);
  106. });
  107. if (preset.representations) {
  108. objectForEach(preset.representations, r => {
  109. if (r) keptRefs.add(r.ref);
  110. });
  111. }
  112. if (keptRefs.size === 0) return this.clearComponents([root]);
  113. let changed = false;
  114. const update = this.dataState.build();
  115. const sync = (r: StructureHierarchyRef) => {
  116. if (!keptRefs.has(r.cell.transform.ref)) {
  117. changed = true;
  118. update.delete(r.cell);
  119. }
  120. };
  121. for (const c of root.components) {
  122. sync(c);
  123. for (const r of c.representations) sync(r);
  124. if (c.genericRepresentations) {
  125. for (const r of c.genericRepresentations) sync(r);
  126. }
  127. }
  128. if (root.genericRepresentations) {
  129. for (const r of root.genericRepresentations) {
  130. sync(r);
  131. }
  132. }
  133. if (changed) return update.commit();
  134. }
  135. clear(structures: ReadonlyArray<StructureRef>) {
  136. return this.clearComponents(structures);
  137. }
  138. selectThis(components: ReadonlyArray<StructureComponentRef>) {
  139. const mng = this.plugin.managers.structure.selection;
  140. mng.clear();
  141. for (const c of components) {
  142. const loci = Structure.toSubStructureElementLoci(c.structure.cell.obj!.data, c.cell.obj?.data!);
  143. mng.fromLoci('set', loci);
  144. }
  145. }
  146. canBeModified(ref: StructureHierarchyRef) {
  147. return this.plugin.builders.structure.isComponentTransform(ref.cell);
  148. }
  149. modifyByCurrentSelection(components: ReadonlyArray<StructureComponentRef>, action: StructureComponentManager.ModifyAction) {
  150. return this.plugin.runTask(Task.create('Modify Component', async taskCtx => {
  151. const b = this.dataState.build();
  152. for (const c of components) {
  153. if (!this.canBeModified(c)) continue;
  154. const selection = this.plugin.managers.structure.selection.getStructure(c.structure.cell.obj!.data);
  155. if (!selection || selection.elementCount === 0) continue;
  156. this.modifyComponent(b, c, selection, action);
  157. }
  158. await this.dataState.updateTree(b, { canUndo: 'Modify Selection' }).runInContext(taskCtx);
  159. }));
  160. }
  161. toggleVisibility(components: ReadonlyArray<StructureComponentRef>, reprPivot?: StructureRepresentationRef) {
  162. if (components.length === 0) return;
  163. if (!reprPivot) {
  164. const isHidden = !components[0].cell.state.isHidden;
  165. for (const c of components) {
  166. setSubtreeVisibility(this.dataState, c.cell.transform.ref, isHidden);
  167. }
  168. } else {
  169. const index = components[0].representations.indexOf(reprPivot);
  170. const isHidden = !reprPivot.cell.state.isHidden;
  171. for (const c of components) {
  172. // TODO: is it ok to use just the index here? Could possible lead to ugly edge cases, but perhaps not worth the trouble to "fix".
  173. const repr = c.representations[index];
  174. if (!repr) continue;
  175. setSubtreeVisibility(this.dataState, repr.cell.transform.ref, isHidden);
  176. }
  177. }
  178. }
  179. removeRepresentations(components: ReadonlyArray<StructureComponentRef>, pivot?: StructureRepresentationRef) {
  180. if (components.length === 0) return;
  181. const toRemove: StructureHierarchyRef[] = [];
  182. if (pivot) {
  183. const index = components[0].representations.indexOf(pivot);
  184. if (index < 0) return;
  185. for (const c of components) {
  186. if (c.representations[index]) toRemove.push(c.representations[index]);
  187. }
  188. } else {
  189. for (const c of components) {
  190. for (const r of c.representations) {
  191. toRemove.push(r);
  192. }
  193. }
  194. }
  195. return this.plugin.managers.structure.hierarchy.remove(toRemove, true);
  196. }
  197. updateRepresentations(components: ReadonlyArray<StructureComponentRef>, pivot: StructureRepresentationRef, params: StateTransformer.Params<StructureRepresentation3D>) {
  198. if (components.length === 0) return Promise.resolve();
  199. const index = components[0].representations.indexOf(pivot);
  200. if (index < 0) return Promise.resolve();
  201. const update = this.dataState.build();
  202. for (const c of components) {
  203. // TODO: is it ok to use just the index here? Could possible lead to ugly edge cases, but perhaps not worth the trouble to "fix".
  204. const repr = c.representations[index];
  205. if (!repr) continue;
  206. if (repr.cell.transform.transformer !== pivot.cell.transform.transformer) continue;
  207. update.to(repr.cell).update(params);
  208. }
  209. return update.commit({ canUndo: 'Update Representation' });
  210. }
  211. /**
  212. * To update theme for all selected structures, use
  213. * plugin.dataTransaction(async () => {
  214. * for (const s of structure.hierarchy.selection.structures) await updateRepresentationsTheme(s.componets, ...);
  215. * }, { canUndo: 'Update Theme' });
  216. */
  217. updateRepresentationsTheme<C extends ColorTheme.BuiltIn, S extends SizeTheme.BuiltIn>(components: ReadonlyArray<StructureComponentRef>, params: StructureComponentManager.UpdateThemeParams<C, S>): Promise<any> | undefined
  218. updateRepresentationsTheme<C extends ColorTheme.BuiltIn, S extends SizeTheme.BuiltIn>(components: ReadonlyArray<StructureComponentRef>, params: (c: StructureComponentRef, r: StructureRepresentationRef) => StructureComponentManager.UpdateThemeParams<C, S>): Promise<any> | undefined
  219. updateRepresentationsTheme(components: ReadonlyArray<StructureComponentRef>, paramsOrProvider: StructureComponentManager.UpdateThemeParams<any, any> | ((c: StructureComponentRef, r: StructureRepresentationRef) => StructureComponentManager.UpdateThemeParams<any, any>)) {
  220. if (components.length === 0) return;
  221. const update = this.dataState.build();
  222. for (const c of components) {
  223. for (const repr of c.representations) {
  224. const old = repr.cell.transform.params;
  225. const params: StructureComponentManager.UpdateThemeParams<any, any> = typeof paramsOrProvider === 'function' ? paramsOrProvider(c, repr) : paramsOrProvider;
  226. const colorTheme = params.color === 'default'
  227. ? createStructureColorThemeParams(this.plugin, c.structure.cell.obj?.data, old?.type.name)
  228. : params.color
  229. ? createStructureColorThemeParams(this.plugin, c.structure.cell.obj?.data, old?.type.name, params.color, params.colorParams)
  230. : void 0;
  231. const sizeTheme = params.size === 'default'
  232. ? createStructureSizeThemeParams(this.plugin, c.structure.cell.obj?.data, old?.type.name)
  233. : params.color
  234. ? createStructureSizeThemeParams(this.plugin, c.structure.cell.obj?.data, old?.type.name, params.size, params.sizeParams)
  235. : void 0;
  236. if (colorTheme || sizeTheme) {
  237. update.to(repr.cell).update(prev => {
  238. if (colorTheme) prev.colorTheme = colorTheme;
  239. if (sizeTheme) prev.sizeTheme = sizeTheme;
  240. });
  241. }
  242. }
  243. }
  244. return update.commit({ canUndo: 'Update Theme' });
  245. }
  246. addRepresentation(components: ReadonlyArray<StructureComponentRef>, type: string) {
  247. if (components.length === 0) return;
  248. const { showHydrogens, visualQuality: quality } = this.state.options;
  249. const ignoreHydrogens = !showHydrogens;
  250. const typeParams = { ignoreHydrogens, quality };
  251. return this.plugin.dataTransaction(async () => {
  252. for (const component of components) {
  253. await this.plugin.builders.structure.representation.addRepresentation(component.cell, {
  254. type: this.plugin.representation.structure.registry.get(type),
  255. typeParams
  256. });
  257. }
  258. }, { canUndo: 'Add Representation' });
  259. }
  260. private tryFindComponent(structure: StructureRef, selection: StructureSelectionQuery) {
  261. if (structure.components.length === 0) return;
  262. return this.plugin.runTask(Task.create('Find Component', async taskCtx => {
  263. const data = structure.cell.obj?.data;
  264. if (!data) return;
  265. const sel = StructureSelection.unionStructure(await selection.getSelection(this.plugin, taskCtx, data));
  266. for (const c of structure.components) {
  267. const comp = c.cell.obj?.data;
  268. if (!comp || !c.cell.parent) continue;
  269. if (structureAreEqual(sel, comp)) return c.cell;
  270. }
  271. }));
  272. }
  273. async add(params: StructureComponentManager.AddParams, structures?: ReadonlyArray<StructureRef>) {
  274. return this.plugin.dataTransaction(async () => {
  275. const xs = structures || this.currentStructures;
  276. if (xs.length === 0) return;
  277. const { showHydrogens, visualQuality: quality } = this.state.options;
  278. const ignoreHydrogens = !showHydrogens;
  279. const typeParams = { ignoreHydrogens, quality };
  280. const componentKey = UUID.create22();
  281. for (const s of xs) {
  282. let component: StateObjectRef | undefined = void 0;
  283. if (params.options.checkExisting) {
  284. component = await this.tryFindComponent(s, params.selection);
  285. }
  286. if (!component) {
  287. component = await this.plugin.builders.structure.tryCreateComponentFromSelection(s.cell, params.selection, componentKey, {
  288. label: params.options.label || (params.selection === StructureSelectionQueries.current ? 'Custom Selection' : ''),
  289. });
  290. }
  291. if (params.representation === 'none' || !component) continue;
  292. await this.plugin.builders.structure.representation.addRepresentation(component, {
  293. type: this.plugin.representation.structure.registry.get(params.representation),
  294. typeParams
  295. });
  296. }
  297. }, { canUndo: 'Add Selection' });
  298. }
  299. async applyTheme(params: StructureComponentManager.ThemeParams, structures?: ReadonlyArray<StructureRef>) {
  300. return this.plugin.dataTransaction(async () => {
  301. const xs = structures || this.currentStructures;
  302. if (xs.length === 0) return;
  303. const getLoci = (s: Structure) => this.plugin.managers.structure.selection.getLoci(s);
  304. for (const s of xs) {
  305. if (params.action.name === 'reset') {
  306. await clearStructureOverpaint(this.plugin, s.components, params.representations);
  307. } else if (params.action.name === 'color') {
  308. const p = params.action.params;
  309. await setStructureOverpaint(this.plugin, s.components, p.color, getLoci, params.representations, p.opacity);
  310. } else if (params.action.name === 'clipping') {
  311. const p = params.action.params;
  312. await setStructureClipping(this.plugin, s.components, Clipping.Groups.fromNames(p.excludeGroups), getLoci, params.representations);
  313. }
  314. }
  315. }, { canUndo: 'Apply Theme' });
  316. }
  317. private modifyComponent(builder: StateBuilder.Root, component: StructureComponentRef, by: Structure, action: StructureComponentManager.ModifyAction) {
  318. const structure = component.cell.obj?.data;
  319. if (!structure) return;
  320. if ((action === 'subtract' || action === 'intersect') && !structureAreIntersecting(structure, by)) return;
  321. const parent = component.structure.cell.obj?.data!;
  322. const modified = action === 'union'
  323. ? structureUnion(parent, [structure, by])
  324. : action === 'intersect'
  325. ? structureIntersect(structure, by)
  326. : structureSubtract(structure, by);
  327. if (modified.elementCount === 0) {
  328. builder.delete(component.cell.transform.ref);
  329. } else {
  330. const bundle = StructureElement.Bundle.fromSubStructure(parent, modified);
  331. const params: StructureComponentParams = {
  332. type: { name: 'bundle', params: bundle },
  333. nullIfEmpty: true,
  334. label: component.cell.obj?.label!
  335. };
  336. builder.to(component.cell).update(params);
  337. }
  338. }
  339. updateLabel(component: StructureComponentRef, label: string) {
  340. const params: StructureComponentParams = {
  341. type: component.cell.params?.values.type,
  342. nullIfEmpty: component.cell.params?.values.nullIfEmpty,
  343. label
  344. };
  345. this.dataState.build().to(component.cell).update(params).commit();
  346. }
  347. private get dataState() {
  348. return this.plugin.state.data;
  349. }
  350. private clearComponents(structures: ReadonlyArray<StructureRef>) {
  351. const deletes = this.dataState.build();
  352. for (const s of structures) {
  353. for (const c of s.components) {
  354. deletes.delete(c.cell.transform.ref);
  355. }
  356. }
  357. return deletes.commit({ canUndo: 'Clear Selections' });
  358. }
  359. constructor(public plugin: PluginContext) {
  360. super({ options: PD.getDefaultValues(StructureComponentManager.OptionsParams) });
  361. }
  362. }
  363. namespace StructureComponentManager {
  364. export const OptionsParams = {
  365. showHydrogens: PD.Boolean(true, { description: 'Toggle display of hydrogen atoms in representations' }),
  366. visualQuality: PD.Select('auto', VisualQualityOptions, { description: 'Control the visual/rendering quality of representations' }),
  367. interactions: PD.Group(InteractionsProvider.defaultParams, { label: 'Non-covalent Interactions' }),
  368. };
  369. export type Options = PD.Values<typeof OptionsParams>
  370. export function getAddParams(plugin: PluginContext, params?: { pivot?: StructureRef, allowNone: boolean, hideSelection?: boolean, checkExisting?: boolean, defaultSelection?: StructureSelectionQuery }) {
  371. const { options } = plugin.query.structure.registry;
  372. params = {
  373. pivot: plugin.managers.structure.component.pivotStructure,
  374. allowNone: true,
  375. hideSelection: false,
  376. checkExisting: false,
  377. defaultSelection: StructureSelectionQueries.current,
  378. ...params
  379. };
  380. return {
  381. selection: PD.Select(options[1][0], options, { isHidden: params?.hideSelection }),
  382. representation: getRepresentationTypesSelect(plugin, params?.pivot, params?.allowNone ? [['none', '< Create Later >']] : []),
  383. options: PD.Group({
  384. label: PD.Text(''),
  385. checkExisting: PD.Boolean(!!params?.checkExisting, { help: () => ({ description: 'Checks if a selection with the specifield elements already exists to avoid creating duplicate components.' }) }),
  386. })
  387. };
  388. }
  389. export type AddParams = { selection: StructureSelectionQuery, options: { checkExisting: boolean, label: string }, representation: string }
  390. export function getThemeParams(plugin: PluginContext, pivot: StructureRef | StructureComponentRef | undefined) {
  391. return {
  392. action: PD.MappedStatic('color', {
  393. color: PD.Group({
  394. color: PD.Color(ColorNames.blue, { isExpanded: true }),
  395. opacity: PD.Numeric(1, { min: 0, max: 1, step: 0.01 }),
  396. }, { isFlat: true }),
  397. reset: PD.EmptyGroup(),
  398. clipping: PD.Group({
  399. excludeGroups: PD.MultiSelect([] as Clipping.Groups.Names[], PD.objectToOptions(Clipping.Groups.Names)),
  400. }, { isFlat: true }),
  401. }),
  402. representations: PD.MultiSelect([], getRepresentationTypes(plugin, pivot), { emptyValue: 'All' })
  403. };
  404. }
  405. export type ThemeParams = PD.Values<ReturnType<typeof getThemeParams>>
  406. export function getRepresentationTypes(plugin: PluginContext, pivot: StructureRef | StructureComponentRef | undefined) {
  407. return pivot?.cell.obj?.data
  408. ? plugin.representation.structure.registry.getApplicableTypes(pivot.cell.obj?.data!)
  409. : plugin.representation.structure.registry.types;
  410. }
  411. function getRepresentationTypesSelect(plugin: PluginContext, pivot: StructureRef | undefined, custom: [string, string][], label?: string) {
  412. const types = [
  413. ...custom,
  414. ...getRepresentationTypes(plugin, pivot)
  415. ] as [string, string][];
  416. return PD.Select(types[0][0], types, { label });
  417. }
  418. export type ModifyAction = 'union' | 'subtract' | 'intersect'
  419. export interface UpdateThemeParams<C extends ColorTheme.BuiltIn, S extends SizeTheme.BuiltIn> {
  420. /**
  421. * this works for any theme name (use 'name as any'), but code completion will break
  422. */
  423. color?: C | 'default',
  424. colorParams?: ColorTheme.BuiltInParams<C>,
  425. size?: S | 'default',
  426. sizeParams?: SizeTheme.BuiltInParams<S>
  427. }
  428. }