global-state.ts 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /**
  2. * Copyright (c) 2018-2022 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Adam Midlik <midlik@gmail.com>
  5. */
  6. import { BehaviorSubject } from 'rxjs';
  7. import { PluginStateObject } from '../../mol-plugin-state/objects';
  8. import { PluginBehavior } from '../../mol-plugin/behavior';
  9. import { PluginContext } from '../../mol-plugin/context';
  10. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  11. import { VolsegEntry } from './entry-root';
  12. import { isDefined } from './helpers';
  13. export const VolsegGlobalStateParams = {
  14. tryUseGpu: PD.Boolean(true, { description: 'Attempt using GPU for faster rendering. \nCaution: with some hardware setups, this might render some objects incorrectly or not at all.' }),
  15. selectionMode: PD.Boolean(true, { description: 'Allow selecting/deselecting a segment by clicking on it.' }),
  16. };
  17. export type VolsegGlobalStateParamValues = PD.Values<typeof VolsegGlobalStateParams>;
  18. export class VolsegGlobalState extends PluginStateObject.CreateBehavior<VolsegGlobalStateData>({ name: 'Vol & Seg Global State' }) { }
  19. export class VolsegGlobalStateData extends PluginBehavior.WithSubscribers<VolsegGlobalStateParamValues> {
  20. private ref: string;
  21. currentState = new BehaviorSubject(PD.getDefaultValues(VolsegGlobalStateParams));
  22. constructor(plugin: PluginContext, params: VolsegGlobalStateParamValues) {
  23. super(plugin, params);
  24. this.currentState.next(params);
  25. }
  26. register(ref: string) {
  27. this.ref = ref;
  28. }
  29. unregister() {
  30. this.ref = '';
  31. }
  32. isRegistered() {
  33. return this.ref !== '';
  34. }
  35. async updateState(plugin: PluginContext, state: Partial<VolsegGlobalStateParamValues>) {
  36. const oldState = this.currentState.value;
  37. const promises = [];
  38. const allEntries = plugin.state.data.selectQ(q => q.ofType(VolsegEntry)).map(cell => cell.obj?.data).filter(isDefined);
  39. if (state.tryUseGpu !== undefined && state.tryUseGpu !== oldState.tryUseGpu) {
  40. for (const entry of allEntries) {
  41. promises.push(entry.setTryUseGpu(state.tryUseGpu));
  42. }
  43. }
  44. if (state.selectionMode !== undefined && state.selectionMode !== oldState.selectionMode) {
  45. for (const entry of allEntries) {
  46. promises.push(entry.setSelectionMode(state.selectionMode));
  47. }
  48. }
  49. await Promise.all(promises);
  50. await plugin.build().to(this.ref).update(state).commit();
  51. }
  52. static getGlobalState(plugin: PluginContext): VolsegGlobalStateParamValues | undefined {
  53. return plugin.state.data.selectQ(q => q.ofType(VolsegGlobalState))[0]?.obj?.data.currentState.value;
  54. }
  55. }