selection.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. /**
  2. * Copyright (c) 2019-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import * as React from 'react';
  8. import { Structure } from '../../mol-model/structure/structure/structure';
  9. import { getElementQueries, getNonStandardResidueQueries, getPolymerAndBranchedEntityQueries, StructureSelectionQueries, StructureSelectionQuery } from '../../mol-plugin-state/helpers/structure-selection-query';
  10. import { InteractivityManager } from '../../mol-plugin-state/manager/interactivity';
  11. import { StructureComponentManager } from '../../mol-plugin-state/manager/structure/component';
  12. import { StructureComponentRef, StructureRef } from '../../mol-plugin-state/manager/structure/hierarchy-state';
  13. import { StructureSelectionModifier } from '../../mol-plugin-state/manager/structure/selection';
  14. import { PluginContext } from '../../mol-plugin/context';
  15. import { compileIdListSelection } from '../../mol-script/util/id-list';
  16. import { memoizeLatest } from '../../mol-util/memoize';
  17. import { ParamDefinition } from '../../mol-util/param-definition';
  18. import { capitalize, stripTags } from '../../mol-util/string';
  19. import { PluginUIComponent, PurePluginUIComponent } from '../base';
  20. import { ActionMenu } from '../controls/action-menu';
  21. import { Button, ControlGroup, IconButton, ToggleButton } from '../controls/common';
  22. import { BrushSvg, CancelOutlinedSvg, CloseSvg, CubeOutlineSvg, HelpOutlineSvg, Icon, IntersectSvg, RemoveSvg, RestoreSvg, SelectionModeSvg, SetSvg, SubtractSvg, UnionSvg } from '../controls/icons';
  23. import { ParameterControls, ParamOnChange, PureSelectControl } from '../controls/parameters';
  24. import { HelpGroup, HelpText, ViewportHelpContent } from '../viewport/help';
  25. import { AddComponentControls } from './components';
  26. export class ToggleSelectionModeButton extends PurePluginUIComponent<{ inline?: boolean }> {
  27. componentDidMount() {
  28. this.subscribe(this.plugin.events.canvas3d.settingsUpdated, () => this.forceUpdate());
  29. this.subscribe(this.plugin.layout.events.updated, () => this.forceUpdate());
  30. this.subscribe(this.plugin.behaviors.interaction.selectionMode, () => this.forceUpdate());
  31. }
  32. _toggleSelMode = () => {
  33. this.plugin.selectionMode = !this.plugin.selectionMode;
  34. }
  35. render() {
  36. const style = this.props.inline
  37. ? { background: 'transparent', width: 'auto', height: 'auto', lineHeight: 'unset' }
  38. : { background: 'transparent' };
  39. return <IconButton svg={SelectionModeSvg} onClick={this._toggleSelMode} title={'Toggle Selection Mode'} style={style} toggleState={this.plugin.selectionMode} />;
  40. }
  41. }
  42. const StructureSelectionParams = {
  43. granularity: InteractivityManager.Params.granularity,
  44. };
  45. type SelectionHelperType = 'residue-list'
  46. interface StructureSelectionActionsControlsState {
  47. isEmpty: boolean,
  48. isBusy: boolean,
  49. canUndo: boolean,
  50. action?: StructureSelectionModifier | 'theme' | 'add-component' | 'help',
  51. helper?: SelectionHelperType,
  52. }
  53. const ActionHeader = new Map<StructureSelectionModifier, string>([
  54. ['add', 'Add/Union Selection'],
  55. ['remove', 'Remove/Subtract Selection'],
  56. ['intersect', 'Intersect Selection'],
  57. ['set', 'Set Selection']
  58. ] as const);
  59. export class StructureSelectionActionsControls extends PluginUIComponent<{}, StructureSelectionActionsControlsState> {
  60. state = {
  61. action: void 0 as StructureSelectionActionsControlsState['action'],
  62. helper: void 0 as StructureSelectionActionsControlsState['helper'],
  63. isEmpty: true,
  64. isBusy: false,
  65. canUndo: false,
  66. }
  67. componentDidMount() {
  68. this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, c => {
  69. const isEmpty = c.hierarchy.structures.length === 0;
  70. if (this.state.isEmpty !== isEmpty) {
  71. this.setState({ isEmpty });
  72. }
  73. // trigger elementQueries and nonStandardResidueQueries recalculation
  74. this.queriesVersion = -1;
  75. this.forceUpdate();
  76. });
  77. this.subscribe(this.plugin.behaviors.state.isBusy, v => {
  78. this.setState({ isBusy: v, action: void 0 });
  79. });
  80. this.subscribe(this.plugin.managers.interactivity.events.propsUpdated, () => {
  81. this.forceUpdate();
  82. });
  83. this.subscribe(this.plugin.state.data.events.historyUpdated, ({ state }) => {
  84. this.setState({ canUndo: state.canUndo });
  85. });
  86. }
  87. get isDisabled() {
  88. return this.state.isBusy || this.state.isEmpty;
  89. }
  90. set = (modifier: StructureSelectionModifier, selectionQuery: StructureSelectionQuery) => {
  91. this.plugin.managers.structure.selection.fromSelectionQuery(modifier, selectionQuery, false);
  92. }
  93. selectQuery: ActionMenu.OnSelect = (item, e) => {
  94. if (!item || !this.state.action) {
  95. this.setState({ action: void 0 });
  96. return;
  97. }
  98. const q = this.state.action! as StructureSelectionModifier;
  99. if (e?.shiftKey) {
  100. this.set(q, item.value as StructureSelectionQuery);
  101. } else {
  102. this.setState({ action: void 0 }, () => {
  103. this.set(q, item.value as StructureSelectionQuery);
  104. });
  105. }
  106. }
  107. selectHelper: ActionMenu.OnSelect = (item, e) => {
  108. console.log(item);
  109. if (!item || !this.state.action) {
  110. this.setState({ action: void 0, helper: void 0 });
  111. return;
  112. }
  113. this.setState({ helper: (item.value as { kind: SelectionHelperType }).kind });
  114. }
  115. get structures() {
  116. const structures: Structure[] = [];
  117. for (const s of this.plugin.managers.structure.hierarchy.selection.structures) {
  118. const structure = s.cell.obj?.data;
  119. if (structure) structures.push(structure);
  120. }
  121. return structures;
  122. }
  123. private queriesItems: ActionMenu.Items[] = []
  124. private queriesVersion = -1
  125. get queries() {
  126. const { registry } = this.plugin.query.structure;
  127. if (registry.version !== this.queriesVersion) {
  128. const structures = this.structures;
  129. const queries = [
  130. ...registry.list,
  131. ...getPolymerAndBranchedEntityQueries(structures),
  132. ...getNonStandardResidueQueries(structures),
  133. ...getElementQueries(structures)
  134. ].sort((a, b) => b.priority - a.priority);
  135. this.queriesItems = ActionMenu.createItems(queries, {
  136. filter: q => q !== StructureSelectionQueries.current && !q.isHidden,
  137. label: q => q.label,
  138. category: q => q.category,
  139. description: q => q.description
  140. });
  141. this.queriesVersion = registry.version;
  142. }
  143. return this.queriesItems;
  144. }
  145. private helpersItems?: ActionMenu.Items[] = void 0;
  146. get helpers() {
  147. if (this.helpersItems) return this.helpersItems;
  148. // TODO: this is an initial implementation of the helper UI
  149. // the plan is to add support to input queries in different languages
  150. // after this has been implemented in mol-script
  151. const helpers = [
  152. { kind: 'residue-list' as SelectionHelperType, category: 'Helpers', label: 'Atom/Residue Identifier List', description: 'Create a selection from a list of atom/residue ranges.' }
  153. ];
  154. this.helpersItems = ActionMenu.createItems(helpers, {
  155. label: q => q.label,
  156. category: q => q.category,
  157. description: q => q.description
  158. });
  159. return this.helpersItems;
  160. }
  161. private showAction(q: StructureSelectionActionsControlsState['action']) {
  162. return () => this.setState({ action: this.state.action === q ? void 0 : q, helper: void 0 });
  163. }
  164. toggleAdd = this.showAction('add')
  165. toggleRemove = this.showAction('remove')
  166. toggleIntersect = this.showAction('intersect')
  167. toggleSet = this.showAction('set')
  168. toggleTheme = this.showAction('theme')
  169. toggleAddComponent = this.showAction('add-component')
  170. toggleHelp = this.showAction('help')
  171. setGranuality: ParamOnChange = ({ value }) => {
  172. this.plugin.managers.interactivity.setProps({ granularity: value });
  173. }
  174. turnOff = () => this.plugin.selectionMode = false;
  175. undo = () => {
  176. const task = this.plugin.state.data.undo();
  177. if (task) this.plugin.runTask(task);
  178. }
  179. subtract = () => {
  180. const sel = this.plugin.managers.structure.hierarchy.getStructuresWithSelection();
  181. const components: StructureComponentRef[] = [];
  182. for (const s of sel) components.push(...s.components);
  183. if (components.length === 0) return;
  184. this.plugin.managers.structure.component.modifyByCurrentSelection(components, 'subtract');
  185. }
  186. render() {
  187. const granularity = this.plugin.managers.interactivity.props.granularity;
  188. const undoTitle = this.state.canUndo
  189. ? `Undo ${this.plugin.state.data.latestUndoLabel}`
  190. : 'Some mistakes of the past can be undone.';
  191. let children: React.ReactNode | undefined = void 0;
  192. if (this.state.action && !this.state.helper) {
  193. children = <>
  194. {(this.state.action && this.state.action !== 'theme' && this.state.action !== 'add-component' && this.state.action !== 'help') && <div className='msp-selection-viewport-controls-actions'>
  195. <ActionMenu header={ActionHeader.get(this.state.action as StructureSelectionModifier)} title='Click to close.' items={this.queries} onSelect={this.selectQuery} noOffset />
  196. <ActionMenu items={this.helpers} onSelect={this.selectHelper} noOffset />
  197. </div>}
  198. {this.state.action === 'theme' && <div className='msp-selection-viewport-controls-actions'>
  199. <ControlGroup header='Theme' title='Click to close.' initialExpanded={true} hideExpander={true} hideOffset={true} onHeaderClick={this.toggleTheme} topRightIcon={CloseSvg}>
  200. <ApplyThemeControls onApply={this.toggleTheme} />
  201. </ControlGroup>
  202. </div>}
  203. {this.state.action === 'add-component' && <div className='msp-selection-viewport-controls-actions'>
  204. <ControlGroup header='Add Component' title='Click to close.' initialExpanded={true} hideExpander={true} hideOffset={true} onHeaderClick={this.toggleAddComponent} topRightIcon={CloseSvg}>
  205. <AddComponentControls onApply={this.toggleAddComponent} forSelection />
  206. </ControlGroup>
  207. </div>}
  208. {this.state.action === 'help' && <div className='msp-selection-viewport-controls-actions'>
  209. <ControlGroup header='Help' title='Click to close.' initialExpanded={true} hideExpander={true} hideOffset={true} onHeaderClick={this.toggleHelp} topRightIcon={CloseSvg} maxHeight='300px'>
  210. <HelpGroup header='Selection Operations'>
  211. <HelpText>Use <Icon svg={UnionSvg} inline /> <Icon svg={SubtractSvg} inline /> <Icon svg={IntersectSvg} inline /> <Icon svg={SetSvg} inline /> to modify the selection.</HelpText>
  212. </HelpGroup>
  213. <HelpGroup header='Representation Operations'>
  214. <HelpText>Use <Icon svg={BrushSvg} inline /> <Icon svg={CubeOutlineSvg} inline /> <Icon svg={RemoveSvg} inline /> <Icon svg={RestoreSvg} inline /> to color, create components, remove from components, or undo actions.</HelpText>
  215. </HelpGroup>
  216. <ViewportHelpContent selectOnly={true} />
  217. </ControlGroup>
  218. </div>}
  219. </>;
  220. } else if (ActionHeader.has(this.state.action as any) && this.state.helper === 'residue-list') {
  221. const close = () => this.setState({ action: void 0, helper: void 0 });
  222. children = <div className='msp-selection-viewport-controls-actions'>
  223. <ControlGroup header='Atom/Residue Identifier List' title='Click to close.' initialExpanded={true} hideExpander={true} hideOffset={true} onHeaderClick={close} topRightIcon={CloseSvg}>
  224. <ResidueListSelectionHelper modifier={this.state.action as any} plugin={this.plugin} close={close} />
  225. </ControlGroup>
  226. </div>;
  227. }
  228. return <>
  229. <div className='msp-flex-row' style={{ background: 'none' }}>
  230. <PureSelectControl title={`Picking Level for selecting and highlighting`} param={StructureSelectionParams.granularity} name='granularity' value={granularity} onChange={this.setGranuality} isDisabled={this.isDisabled} />
  231. <ToggleButton icon={UnionSvg} title={`${ActionHeader.get('add')}. Hold shift key to keep menu open.`} toggle={this.toggleAdd} isSelected={this.state.action === 'add'} disabled={this.isDisabled} />
  232. <ToggleButton icon={SubtractSvg} title={`${ActionHeader.get('remove')}. Hold shift key to keep menu open.`} toggle={this.toggleRemove} isSelected={this.state.action === 'remove'} disabled={this.isDisabled} />
  233. <ToggleButton icon={IntersectSvg} title={`${ActionHeader.get('intersect')}. Hold shift key to keep menu open.`} toggle={this.toggleIntersect} isSelected={this.state.action === 'intersect'} disabled={this.isDisabled} />
  234. <ToggleButton icon={SetSvg} title={`${ActionHeader.get('set')}. Hold shift key to keep menu open.`} toggle={this.toggleSet} isSelected={this.state.action === 'set'} disabled={this.isDisabled} />
  235. <ToggleButton icon={BrushSvg} title='Apply Theme to Selection' toggle={this.toggleTheme} isSelected={this.state.action === 'theme'} disabled={this.isDisabled} style={{ marginLeft: '10px' }} />
  236. <ToggleButton icon={CubeOutlineSvg} title='Create Component of Selection with Representation' toggle={this.toggleAddComponent} isSelected={this.state.action === 'add-component'} disabled={this.isDisabled} />
  237. <IconButton svg={RemoveSvg} title='Remove/subtract Selection from all Components' onClick={this.subtract} disabled={this.isDisabled} />
  238. <IconButton svg={RestoreSvg} onClick={this.undo} disabled={!this.state.canUndo || this.isDisabled} title={undoTitle} />
  239. <ToggleButton icon={HelpOutlineSvg} title='Show/hide help' toggle={this.toggleHelp} style={{ marginLeft: '10px' }} isSelected={this.state.action === 'help'} />
  240. <IconButton svg={CancelOutlinedSvg} title='Turn selection mode off' onClick={this.turnOff} />
  241. </div>
  242. {children}
  243. </>;
  244. }
  245. }
  246. export class StructureSelectionStatsControls extends PluginUIComponent<{ hideOnEmpty?: boolean }, { isEmpty: boolean, isBusy: boolean }> {
  247. state = {
  248. isEmpty: true,
  249. isBusy: false
  250. }
  251. componentDidMount() {
  252. this.subscribe(this.plugin.managers.structure.selection.events.changed, () => {
  253. this.forceUpdate();
  254. });
  255. this.subscribe(this.plugin.managers.structure.hierarchy.behaviors.selection, c => {
  256. const isEmpty = c.structures.length === 0;
  257. if (this.state.isEmpty !== isEmpty) {
  258. this.setState({ isEmpty });
  259. }
  260. });
  261. this.subscribe(this.plugin.behaviors.state.isBusy, v => {
  262. this.setState({ isBusy: v });
  263. });
  264. }
  265. get isDisabled() {
  266. return this.state.isBusy || this.state.isEmpty;
  267. }
  268. get stats() {
  269. const stats = this.plugin.managers.structure.selection.stats;
  270. if (stats.structureCount === 0 || stats.elementCount === 0) {
  271. return 'Nothing Selected';
  272. } else {
  273. return `${stripTags(stats.label)} Selected`;
  274. }
  275. }
  276. clear = () => this.plugin.managers.interactivity.lociSelects.deselectAll();
  277. focus = () => {
  278. if (this.plugin.managers.structure.selection.stats.elementCount === 0) return;
  279. const { sphere } = this.plugin.managers.structure.selection.getBoundary();
  280. this.plugin.managers.camera.focusSphere(sphere);
  281. }
  282. highlight = (e: React.MouseEvent<HTMLElement>) => {
  283. this.plugin.managers.interactivity.lociHighlights.clearHighlights();
  284. this.plugin.managers.structure.selection.entries.forEach(e => {
  285. this.plugin.managers.interactivity.lociHighlights.highlight({ loci: e.selection }, false);
  286. });
  287. }
  288. clearHighlight = () => {
  289. this.plugin.managers.interactivity.lociHighlights.clearHighlights();
  290. }
  291. render() {
  292. const stats = this.plugin.managers.structure.selection.stats;
  293. const empty = stats.structureCount === 0 || stats.elementCount === 0;
  294. if (empty && this.props.hideOnEmpty) return null;
  295. return <>
  296. <div className='msp-flex-row'>
  297. <Button noOverflow onClick={this.focus} title='Click to Focus Selection' disabled={empty} onMouseEnter={this.highlight} onMouseLeave={this.clearHighlight}
  298. style={{ textAlignLast: !empty ? 'left' : void 0 }}>
  299. {this.stats}
  300. </Button>
  301. {!empty && <IconButton svg={CancelOutlinedSvg} onClick={this.clear} title='Clear' className='msp-form-control' flex />}
  302. </div>
  303. </>;
  304. }
  305. }
  306. interface ApplyThemeControlsState {
  307. values: StructureComponentManager.ThemeParams
  308. }
  309. interface ApplyThemeControlsProps {
  310. onApply?: () => void
  311. }
  312. class ApplyThemeControls extends PurePluginUIComponent<ApplyThemeControlsProps, ApplyThemeControlsState> {
  313. _params = memoizeLatest((pivot: StructureRef | undefined) => StructureComponentManager.getThemeParams(this.plugin, pivot));
  314. get params() { return this._params(this.plugin.managers.structure.component.pivotStructure); }
  315. state = { values: ParamDefinition.getDefaultValues(this.params) };
  316. apply = () => {
  317. this.plugin.managers.structure.component.applyTheme(this.state.values, this.plugin.managers.structure.hierarchy.current.structures);
  318. this.props.onApply?.();
  319. }
  320. paramsChanged = (values: any) => this.setState({ values })
  321. render() {
  322. return <>
  323. <ParameterControls params={this.params} values={this.state.values} onChangeValues={this.paramsChanged} />
  324. <Button icon={BrushSvg} className='msp-btn-commit msp-btn-commit-on' onClick={this.apply} style={{ marginTop: '1px' }}>
  325. Apply Theme
  326. </Button>
  327. </>;
  328. }
  329. }
  330. const ResidueListIdTypeParams = {
  331. idType: ParamDefinition.Select<'auth' | 'label' | 'atom-id'>('auth', ParamDefinition.arrayToOptions(['auth', 'label', 'atom-id'])),
  332. identifiers: ParamDefinition.Text('', { description: 'A comma separated list of atom identifiers (e.g. 10, 15-25) or residue ranges in given chain (e.g. A 10-15, B 25, C 30:i)' })
  333. };
  334. const DefaultResidueListIdTypeParams = ParamDefinition.getDefaultValues(ResidueListIdTypeParams);
  335. function ResidueListSelectionHelper({ modifier, plugin, close }: { modifier: StructureSelectionModifier, plugin: PluginContext, close: () => void }) {
  336. const [state, setState] = React.useState(DefaultResidueListIdTypeParams);
  337. const apply = () => {
  338. if (state.identifiers.trim().length === 0) return;
  339. try {
  340. close();
  341. const query = compileIdListSelection(state.identifiers, state.idType);
  342. plugin.managers.structure.selection.fromCompiledQuery(modifier, query, false);
  343. } catch (e) {
  344. console.error(e);
  345. plugin.log.error('Failed to create selection');
  346. }
  347. };
  348. return <>
  349. <ParameterControls params={ResidueListIdTypeParams} values={state} onChangeValues={setState} onEnter={apply} />
  350. <Button className='msp-btn-commit msp-btn-commit-on' disabled={state.identifiers.trim().length === 0} onClick={apply} style={{ marginTop: '1px' }}>
  351. {capitalize(modifier)} Selection
  352. </Button>
  353. </>;
  354. }