File size: 24,206 Bytes
71174bc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 | import { randomID } from "@/Core/Utils/MiscUtils";
import { FileInfo } from "@/FileSystem/FileInfo";
import {
getMoleculesFromStore,
pushToStoreList,
setStoreVar,
} from "@/Store/StoreExternalAccess";
import type { GLModel } from "@/UI/Panels/Viewer/GLModelType";
import {
TreeNodeType,
SelectedType,
ITreeNodeData,
IAtom,
IRegion,
IBox,
RegionType,
} from "../../UI/Navigation/TreeView/TreeInterfaces";
import { TreeNodeList } from "../TreeNodeList/TreeNodeList";
import { newTreeNodeList, setupMakerFuncs } from "../TreeNodeMakers";
import { TreeNodeAncestry } from "./_Ancestry";
import { TreeNodeDescriptions } from "./_Descriptions";
import { store } from "@/Store";
import { visualizationApi } from "@/Api/Visualization";
import { expandAndShowAllMolsInTree } from "@/Testing/SetupTests";
import { IFileInfo } from "@/FileSystem/Types";
import { makeEasyParser } from "@/FileSystem/LoadSaveMolModels/ParseMolModels/EasyParser";
import { ILoadMolParams } from "@/FileSystem/LoadSaveMolModels/ParseMolModels/Types";
import { ISelAndStyle } from "@/Core/Styling/SelAndStyleInterfaces";
import { updateStylesInViewer } from "@/Core/Styling/StyleManager";
import { getSetting } from "@/Plugins/Core/Settings/LoadSaveSettings";
import { isTest } from "@/Core/GlobalVars";
import { _convertTreeNodeList } from "@/FileSystem/LoadSaveMolModels/ConvertMolModels/_ConvertTreeNodeList";
// Deserialized (object-based) version of TreeNode
export interface ITreeNode {
// Properties common to both non-terminal and terminal nodes.
title: string; // appears in tree
type?: TreeNodeType;
id?: string; // random id for nodes
parentId?: string; // parent id for tree
src?: string; // typically, the file name
treeExpanded: boolean;
visible: boolean;
selected: SelectedType; // Not bool (string enum). "false" vs. false.
focused: boolean;
viewerDirty: boolean; // triggers 3dmoljs viewer
data?: { [key: string]: ITreeNodeData }; // key is title of chart, etc.
tags?: string[]; // tags for this node. Mostly just plugin ids of plugins used to generate this node.
// These are specifically for terminal nodes
styles?: ISelAndStyle[]; // styles and selections for this node
model?: IAtom[] | GLModel | IFileInfo;
region?: IRegion;
// These are specifically for non-terminal nodes
nodes?: TreeNodeList; // Next level down in menu. So if molecule,
}
/**
* TreeNode class.
*/
export class TreeNode {
// Properties common to both non-terminal and terminal nodes.
title: string; // appears in tree
type?: TreeNodeType;
id?: string; // random id for nodes
parentId?: string; // parent id for tree
src?: string; // typically, the file name
treeExpanded: boolean;
_visible: boolean;
_selected: SelectedType; // Not bool (string enum). "false" vs. false.
focused: boolean;
viewerDirty: boolean; // triggers 3dmoljs viewer
data?: { [key: string]: ITreeNodeData }; // key is title of chart, etc.
tags?: string[]; // tags for this node. Mostly just plugin ids of plugins used to generate this node.
// These are specifically for non-terminal nodes
nodes?: TreeNodeList; // Next level down in menu. So if molecule,
// These are specifically for terminal nodes
model?: IAtom[] | GLModel | IFileInfo; // IAtom in worker, GLMoldel in main thread
styles?: ISelAndStyle[]; // styles and selections for this node
region?: IRegion;
public triggerId = ""; // Purpose of this is just to trigger reactivity if needed
private _descriptions: TreeNodeDescriptions;
private _ancestry: TreeNodeAncestry;
/**
* The constructor.
*
* @param {ITreeNode} params The parameters.
*/
constructor(params: ITreeNode) {
// this._title = this.fixTitle(params.title);
this.title = params.title;
this.type = params.type;
// If no id, create one.
if (!params.id) {
params.id = randomID();
}
this.id = params.id;
this.parentId = params.parentId;
this.src = params.src;
this.treeExpanded = params.treeExpanded;
this._visible = params.visible;
this._selected = params.selected;
this.focused = params.focused;
this.viewerDirty = params.viewerDirty;
this.data = params.data;
this.tags = params.tags;
this.nodes = params.nodes;
this.model = params.model;
this.styles = params.styles;
this.region = params.region;
this._descriptions = new TreeNodeDescriptions(this);
this._ancestry = new TreeNodeAncestry(this);
// For chaining
return this;
}
/**
* Get the selected state.
*
* @returns {SelectedType} The selected state.
*/
get selected(): SelectedType {
return this._selected;
}
/**
* Set the selected state.
*
* @param {SelectedType} val The selected state.
*/
set selected(val: SelectedType) {
// Set to dirty to trigger rerender of molecule (with yellow outline to
// indicate selected).
this.viewerDirty = true;
this._selected = val;
}
/**
* Triggers reactivity. This is useful on rare occasions you need to trigger
* reactivity explicitly. Tested on the main, root node. May work on others.
*/
public triggerReactivity() {
this.triggerId = randomID();
}
// private fixTitle(title: string): string {
// if (title === undefined) {
// // eslint-disable-next-line @typescript-eslint/ban-ts-comment
// // @ts-ignore
// return undefined;
// }
// // If there is "(" in the title, update it to : (trying to enforce
// // consistency).
// title = title.replace("(", ":");
// title = title.replace(")", ":");
// while (title.indexOf(" :") !== -1) {
// title = title.replace(" :", ":");
// }
// while (title.indexOf(": ") !== -1) {
// title = title.replace(": ", ":");
// }
// title = title.trim();
// // If ends in :, remove
// if (title.endsWith(":")) {
// title = title.slice(0, title.length - 1);
// }
// return title;
// }
// public get title(): string {
// return this._title;
// }
// public set title(val: string) {
// val = this.fixTitle(val);
// this._title = val;
// }
/**
* Get whether this node is visible.
*
* @returns {boolean} Whether this node is visible.
*/
public get visible(): boolean {
return this._visible;
}
/**
* Set whether this node is visible.
*
* @param {boolean} val Whether this node is visible.
*/
public set visible(val: boolean) {
// Make this one visible as well as all its children.
this.nodes?.flattened.forEach((nd) => {
nd._visible = val;
});
this._visible = val;
}
/**
* Set this node's visibility without affecting its children.
*/
public set visibleWithoutChildren(val: boolean) {
// Regular visible propogates to children. This just affects this node.
this._visible = val;
}
/**
* Get the descriptions subclass.
*
* @returns {TreeNodeDescriptions} The descriptions subclass.
*/
public get descriptions(): TreeNodeDescriptions {
return this._descriptions;
}
/**
* Get the parent node of the current node.
*
* @returns {TreeNode | undefined} The parent node, or undefined if there
* is no parent.
*/
public get parentTreeNode(): TreeNode | undefined {
const ancestors = this.getAncestry(store.state.molecules);
return ancestors.get(ancestors.length - 2);
}
/**
* Serialize the TreeNode (removes objects).
*
* @returns {ITreeNode} The serialized TreeNode.
*/
public serialize(): ITreeNode {
const obj: { [key: string]: any } = {};
for (const key in this) {
if (key === "nodes" && this.nodes) {
obj["nodes"] =
(this.nodes as TreeNodeList).serialize !== undefined
? (this.nodes as TreeNodeList).serialize()
: this.nodes;
} else if (key === "model" && this.model) {
// If stored as GLModel (depreciated), convert to IAtom[] so
// serializable.
if ((this.model as GLModel).selectedAtoms !== undefined) {
obj["model"] = (this.model as GLModel).selectedAtoms({});
// Remove some data that's not likely needed to reduce file
// size.
const keysToRemove = [
"pdbline",
"uMat",
// "intersectionShape", // This is needed
];
obj["model"] = obj["model"].map((atom: IAtom) => {
for (const key of keysToRemove) {
if ((atom as any)[key]) {
delete (atom as any)[key];
}
}
return atom;
});
} else {
obj["model"] = JSON.parse(JSON.stringify(this.model));
}
} else {
const element = this[key];
if (element !== undefined) {
if (key.startsWith("_")) {
// Skip this one
continue;
}
obj[key] = JSON.parse(JSON.stringify(element));
}
}
}
// You must add "visible" manually because it's a getter, not a
// property.
obj["visible"] = this.visible;
return obj as ITreeNode;
}
/**
* Shallow copy the TreeNode. Doesn't recreate GLModel objects, for example.
*
* @returns {TreeNode} The shallow copy.
*/
public shallowCopy(): TreeNode {
const prop: { [key: string]: any } = {};
for (const key in this) {
prop[key] = this[key];
}
if (prop.nodes) {
prop.nodes = (prop.nodes as TreeNodeList).copy.shallow;
}
return new TreeNode(prop as ITreeNode);
}
/**
* Clears the children of the node.
*/
public clearChildren() {
if (this.nodes) {
this.nodes.clear();
}
}
/**
* Get a nodes ancestory. First element is most distant ancestor (greatest
* grandparent), and last is this node itself.
*
* @param {TreeNodeList} [mols=undefined] The list of molecules to
* search. If undefined, uses all
* molecules.
* @returns {TreeNodeList} The list of nodes in the ancestory.
*/
public getAncestry(mols?: TreeNodeList): TreeNodeList {
if (mols === undefined) {
mols = getMoleculesFromStore();
}
return this._ancestry.getAncestry(mols);
}
/**
* Convert this TreeNode to a specified molecular format.
*
* @param {string} targetExt The extension of the format to
* convert to.
* @param {boolean} [considerDescendants=false] If true and this is a container node,
* its descendants will be merged into a single file.
* @returns {Promise<FileInfo>} The text-formatted (e.g., PDB, MOL2) string as a FileInfo object.
*/
public toFileInfo(
targetExt: string,
considerDescendants = false
): Promise<FileInfo> {
let nodesToConvert: TreeNodeList;
let merge = false;
if (this.model) {
// It's a terminal node with a model. Always convert just this node.
nodesToConvert = new TreeNodeList([this]);
merge = false;
} else if (this.nodes && this.nodes.terminals.length > 0) {
// It's a container node.
if (considerDescendants) {
// Get all its terminal descendants and merge them.
nodesToConvert = this.nodes.terminals;
merge = true;
} else {
// Default behavior for a container: cannot be converted directly.
return Promise.reject(
new Error(
`Cannot convert container node "${this.title}" directly. To convert its contents, set considerDescendants to true.`
)
);
}
} else {
// It's an empty or non-convertible node.
return Promise.reject(
new Error(
`Node "${this.title}" has no model or descendant nodes with models to convert.`
)
);
}
return _convertTreeNodeList(nodesToConvert, targetExt, merge)
.then((fileInfos: FileInfo[]) => {
if (fileInfos.length === 0) {
// This can happen if conversion yields no output.
throw new Error(
`Conversion of node "${this.title}" to "${targetExt}" resulted in an empty file.`
);
}
return fileInfos[0];
})
.catch((err: Error) => {
throw err;
});
}
/**
* Creates a new TreeNode. Putting this in a function here helps with circular
* dependencies.
*
* @param {ITreeNode} params The parameters to create the TreeNode with.
* @returns {TreeNode} The new TreeNode.
*/
public newTreeNode(params: ITreeNode): TreeNode {
// To help with circular dependencies.
return new TreeNode(params);
}
/**
* Get the depth of the tree (number of descendents).
*
* @returns {number} The depth of the tree.
*/
public get depth(): number {
let maxDepthFound = 1;
const recurse = (node: TreeNode, depthSoFar: number) => {
if (node.nodes) {
node.nodes.forEach((child: TreeNode) => {
recurse(child, depthSoFar + 1);
});
}
if (depthSoFar > maxDepthFound) {
maxDepthFound = depthSoFar;
}
return depthSoFar;
};
recurse(this, 1);
return maxDepthFound;
}
/**
* Merge another node into this one. In place.
*
* @param {TreeNode} otherNode The node to merge into this one.
*/
public mergeInto(otherNode: TreeNode) {
// Verify that both have the same depth
// if (this.depth !== otherNode.depth) {
// throw new Error("Cannot merge nodes with different depths.");
// }
// if (this.nodes === undefined) {
// throw new Error("Cannot merge nodes with undefined children.");
// }
otherNode.nodes?.forEach((otherChild: TreeNode) => {
const otherNodeType = otherChild.type;
// Does this type exist in this node?
const thisChild = this.nodes?.find((child: TreeNode) => {
return child.type === otherNodeType;
});
if (thisChild === undefined) {
// No, so just add it. Straightforward.
otherChild.parentId = this.id;
this.nodes?.push(otherChild);
} else {
// This one does have a child node of the same type.
if (
thisChild.nodes === undefined &&
otherChild.nodes === undefined
) {
// They are both terminal nodes. Add as siblings.
otherChild.parentId = this.id;
this.nodes?.push(otherChild);
} else {
// Not temrinal nodes, so need to merge each of the children
// in other one into this one.
thisChild.mergeInto(otherChild);
}
}
});
}
/**
* Assigns new ids to all nodes in the tree. This is useful when cloning a
* tree, for example. This is done in place. It also fixed all parentIds.
*/
reassignAllIds() {
// Get all the nodes (flat).
const allNodes = new TreeNodeList([this]).flattened;
// Go through each node and assign a new id.
allNodes.forEach((node: TreeNode) => {
node.id = randomID();
});
// Go through each node that has children and assign the new parentIds.
allNodes.forEach((node: TreeNode) => {
if (node.nodes) {
node.nodes.forEach((child: TreeNode) => {
child.parentId = node.id;
});
}
});
}
/**
* A helper function. Adds this node to the molecules in the vuex store.
*
* @param {string | null} tag The tag to add to this
* node.
* @param {boolean} [reassignIds=true] Whether to reassign
* IDs to the new nodes
* to avoid collisions.
* Set to false when
* loading a saved
* session.
* @param {boolean} [terminalNodeTitleRevisable=true] Whether the title of
* the terminal node
* should be revisable.
* Revised if there is
* only one terminal
* node. If you're adding
* nodes incrementally,
* good to set to false.
* @param {boolean} [resetVisibilityAndSelection=true] Whether to make the molecule
* visible and unselected. Set to false
* when loading a saved session where these
* properties should be preserved.
*/
public async addToMainTree(
tag: string | null,
reassignIds = true,
terminalNodeTitleRevisable = true,
resetVisibilityAndSelection = true
) {
if (reassignIds) {
this.reassignAllIds();
}
if (isTest) {
// If it's a test, open it with all nodes expanded.
expandAndShowAllMolsInTree();
}
// Get all nodes in the subtree to set selection and tags.
const allNodesInSubtree = new TreeNodeList([this]).flattened;
// Add tag if provided.
if (tag) {
allNodesInSubtree.forEach((node) => {
if (node.tags === undefined) {
node.tags = [];
}
// Avoid adding duplicate tags.
if (!node.tags.includes(tag)) {
node.tags.push(tag);
}
});
}
if (resetVisibilityAndSelection) {
// Set visibility to true for this node and all its non-terminal children.
allNodesInSubtree.forEach((node) => {
if (node.nodes) {
// It's a container node
node.visible = true;
}
});
this.visible = true;
// For terminal nodes, make only the first few visible.
const terminalNodes = this.nodes
? this.nodes.terminals
: new TreeNodeList([]);
if (this.model) {
// This node is a terminal node itself.
terminalNodes.push(this);
}
const initialCompoundsVisible = await getSetting(
"initialCompoundsVisible"
);
terminalNodes.forEach((node, i) => {
node.visible = i < initialCompoundsVisible;
});
// Ensure nodes are not selected when added.
allNodesInSubtree.forEach((node) => {
node.selected = SelectedType.False;
});
}
// If this node has only one terminal node, and that terminal, prepend
// the top-level title to the title of the terminal node.
if (
terminalNodeTitleRevisable &&
this.nodes &&
this.nodes.terminals.length === 1
) {
this.nodes.terminals.get(0).title = `${this.title}:${
this.nodes.terminals.get(0).title
}`;
}
pushToStoreList("molecules", this);
if (store.state.projectTitle === "") {
const topAncestor = this.getAncestry(getMoleculesFromStore()).get(
0
);
if (topAncestor && topAncestor.title) {
setStoreVar("projectTitle", topAncestor.title);
}
}
// If you add new molecules to the tree, focus on everything.
const viewer = await visualizationApi.viewer;
// Set the style according to the current user specs.
updateStylesInViewer();
viewer.zoomOnFocused();
}
/**
* Gets the box surrounding the model.
*
* @param {number} [padding=3.4] The padding to add to the box.
* @returns {IBox} The box.
*/
public getBoxRegion(padding = 3.4): IBox {
// Note 3.4 is approximate vdw diameter of carbon.
// Get all the nodes and subnodes with models (including this one).
const nodesWithModels = newTreeNodeList([this]).filters.keepModels(
true,
true
).nodes;
const xs: number[] = [];
const ys: number[] = [];
const zs: number[] = [];
nodesWithModels.forEach((node: TreeNode) => {
const model = node.model as GLModel;
// Get atoms
const { atoms } = makeEasyParser(model);
xs.push(...atoms.map((atom: IAtom) => atom.x as number));
ys.push(...atoms.map((atom: IAtom) => atom.y as number));
zs.push(...atoms.map((atom: IAtom) => atom.z as number));
});
// Get min and max x, y, and z
const minX = Math.min(...xs);
const maxX = Math.max(...xs);
const minY = Math.min(...ys);
const maxY = Math.max(...ys);
const minZ = Math.min(...zs);
const maxZ = Math.max(...zs);
// Get box center
const centerX = (minX + maxX) / 2;
const centerY = (minY + maxY) / 2;
const centerZ = (minZ + maxZ) / 2;
// Try to get color of this node if you can find it.
let color: string | undefined = undefined;
if (this.styles && this.styles.length > 0) {
for (const style of this.styles) {
const colors = [
style.surface?.color,
style.sphere?.color,
style.cartoon?.color,
style.stick?.color,
style.line?.color,
];
// Get first color in colors that is not undefined
color = colors.find((c: string | undefined) => c !== undefined);
if (color !== undefined) {
break;
}
}
}
if (color === undefined) {
// If none of the styles can a color attribute set, just use red.
color = "red";
}
return {
type: RegionType.Box,
center: [centerX, centerY, centerZ],
opacity: 0.5,
color: color,
movable: true,
dimensions: [
maxX - minX + padding,
maxY - minY + padding,
maxZ - minZ + padding,
],
} as IBox;
}
}
/**
* Defines the maker functions for TreeNode and TreeNodeList. This is done
* here to avoid circular dependencies.
*/
export function defineMakerFuncs() {
setupMakerFuncs(
new TreeNode({} as ITreeNode).newTreeNode,
new TreeNodeList([]).newTreeNodeList
);
}
|