structure-query.ts 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * Copyright (c) 2019 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import Expression from '../../mol-script/language/expression';
  7. import { QueryFn, Structure, StructureSelection as Sel, QueryContext } from '../../mol-model/structure';
  8. import { Script } from '../../mol-script/script';
  9. import { compile } from '../../mol-script/runtime/query/compiler';
  10. import { PluginStateObject as SO } from '../state/objects';
  11. export { StructureQueryHelper }
  12. namespace StructureQueryHelper {
  13. export interface CacheEntry {
  14. script?: Script,
  15. expression: Expression,
  16. compiled: QueryFn<Sel>,
  17. originalStructure: Structure,
  18. currentStructure: Structure
  19. }
  20. export function isUnchanged(entry: CacheEntry, query: Script | Expression, structure: Structure) {
  21. if (entry.currentStructure !== structure) return false;
  22. if (Script.is(query)) {
  23. return !!entry.script && Script.areEqual(entry.script, query);
  24. }
  25. return entry.expression === query;
  26. }
  27. export function create(structure: Structure, query: Script | Expression): CacheEntry {
  28. const script = Script.is(query) ? query : void 0;
  29. const expression = Script.is(query) ? Script.toExpression(query) : query;
  30. const compiled = compile<Sel>(expression);
  31. return { script, expression, compiled, originalStructure: structure, currentStructure: structure };
  32. }
  33. export function run(entry: CacheEntry, structure: Structure) {
  34. return entry.compiled(new QueryContext(structure))
  35. }
  36. export function createAndRun(structure: Structure, query: Script | Expression) {
  37. const entry = create(structure, query);
  38. return { entry, selection: run(entry, structure) };
  39. }
  40. export function updateStructure(entry: CacheEntry, structure: Structure) {
  41. entry.currentStructure = structure;
  42. return entry.compiled(new QueryContext(structure));
  43. }
  44. export function updateStructureObject(obj: SO.Molecule.Structure, selection: Sel, label?: string) {
  45. const s = Sel.unionStructure(selection);
  46. obj.label = `${label || 'Selection'}`;
  47. obj.description = Structure.elementDescription(s);
  48. obj.data = s;
  49. }
  50. }