component.ts 24 KB

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