component.ts 24 KB

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