File size: 8,942 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
// You can load some molecule files using 3Dmol.js directly, without requiring
// any conversion. See https://3dmol.csb.pitt.edu/doc/types.html#FileFormats
import { messagesApi } from "@/Api/Messages";
import type { TreeNodeList } from "@/TreeNodes/TreeNodeList/TreeNodeList";
import { parseUsing3DMolJs } from "./_ParseUsing3DMolJs";
import { parseUsingOpenBabel } from "./_ParseUsingOpenBabel";
import { parseUsingMolModa } from "./_ParseUsingMolModa";
import { molFormatInformation, MolLoader } from "../Types/MolFormats";
import { getFileNameParts } from "@/FileSystem/FilenameManipulation";
import { addDefaultLoadMolParams, ILoadMolParams } from "./Types";
import { stopAllWaitSpinners } from "@/UI/MessageAlerts/WaitSpinner";
import { isAnyPopupOpen } from "@/UI/MessageAlerts/Popups/OpenPopupList";
import { getSetting } from "@/Plugins/Core/Settings/LoadSaveSettings";
import { PopupVariant } from "@/UI/MessageAlerts/Popups/InterfacesAndEnums";
// import { parseUsingJsZip } from "./ParseUsingJsZip";

// TODO: Might want to load other data too. Could add here. Perhaps a hook that
// plugins can use...

// Create a list of extensions (upper case).
const _allAcceptableFileTypes = Object.values(molFormatInformation).reduce(
    (acc, val) => acc.concat(val.exts.map((x) => x.toUpperCase())),
    [] as string[]
);
_allAcceptableFileTypes.sort();

// And list of extensions for use in input file type "accept" parameter.
export const fileTypesAccepts =
    _allAcceptableFileTypes.map((f) => `.${f.toLowerCase()}`).join(",") +
    ",.zip";

/**
 * Given a title, correct common problems with the title.
 *
 * @param  {string} title  The title to fix.
 * @param  {string} defaultTitle  The default title to use if none is found.
 * @returns {string}  The fixed title.
 */
function _fixTitle(title: string, defaultTitle: string): string {
    if ([undefined, ""].indexOf(title) !== -1) {
        return defaultTitle;
    }
    title = title.replace("*****", defaultTitle);

    // If t.title starts with ":", remove that.
    if (title.startsWith(":")) {
        title = title.slice(1);
    }

    return title;
}

/**
 * Given an IFileInfo object (name, contents, type), load the molecule.
 * Handles parsing, post-processing titles, checking visibility limits, and optionally adding to the tree.
 *
 * @param  {ILoadMolParams} params  The parameters for loading the molecule.
 * @returns {Promise<void | TreeNodeList>}  A promise that resolves when the
 *  molecule is loaded.
 */
export function parseAndLoadMoleculeFile(
    params: ILoadMolParams
): Promise<void | TreeNodeList> {
    params = addDefaultLoadMolParams(params);
    const spinnerId = messagesApi.startWaitSpinner();

    const formatInfo = params.fileInfo.getFormatInfo();
    if (formatInfo === undefined) {
        const errorMessage = `Could not determine file format for "${params.fileInfo.name}".`;
        messagesApi.popupError(errorMessage);
        return Promise.reject(new Error(errorMessage));
    }

    // Adjust desalt perameter if needed
    if (formatInfo.neverDesalt === true) {
        console.warn(
            `File format ${formatInfo.description} does not support desalting.`
        );
        params.desalt = false;
    }

    // Apply text pre processor.
    if (formatInfo.textPreProcessor) {
        params.fileInfo.contents = formatInfo.textPreProcessor(
            params.fileInfo.contents
        );
    }

    // For 3dmoljs and openbabel loading, models should be merged. So save the
    // promise instead of returning immediately.
    let promise: Promise<TreeNodeList>;

    let { loader } = formatInfo;

    // Here we must deal with a difficult situation. If would be MUCH faster to
    // load MOL2 files using Mol3D, not OpenBabel. But MOL2 uses OpenBabel by
    // default for desalting. If desalting isn't needed, let's switch back to Mol3D.
    if (formatInfo.primaryExt === "mol2" && !params.desalt) {
        loader = MolLoader.Mol3D;
    }

    switch (loader) {
        case MolLoader.Mol3D: {
            promise = parseUsing3DMolJs(params.fileInfo, formatInfo);
            break;
        }
        case MolLoader.OpenBabel: {
            promise = parseUsingOpenBabel(
                params.fileInfo,
                formatInfo,
                params.desalt,
                params.gen3D,
                params.surpressMsgs
            );
            break;
        }
        case MolLoader.MolModaFormat: {
            return parseUsingMolModa(params.fileInfo).then((payload: any) => {
                messagesApi.stopWaitSpinner(spinnerId);
                return payload;
            });
        }
        // case MolLoader.Zip: {
        //     return parseUsingJsZip(fileInfo);
        // }
    }

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    return promise
  .then(async (treeNodeList: TreeNodeList) => {
            // Merge the TreeNodeLists into one
            // for (let i = 1; i < treeNodeLists.length; i++) {
   //  treeNodeList.extend(treeNodeLists[i]);
            // }

            if (treeNodeList.length === 0) {
                if (isAnyPopupOpen()) {
                    stopAllWaitSpinners(); // Still need to stop the spinner
                    return treeNodeList; // Abort showing a new error message
                }
                let msg =
                    "<p>File contained no valid molecules. Are you certain it's correctly formatted?</p>";

                stopAllWaitSpinners();

                // Get first 5 lines of fileInfo.contents
                if (params.fileInfo.contents.trim() !== "") {
                    // const first5Lines = fileInfo.contents
     //  .split("\n")
     //  .slice(0, 5);
                    // let first5LinesStr = first5Lines.join("\n");

                    // // Add line ... if appropriate
                    // first5LinesStr +=
     //  fileInfo.contents.length > first5LinesStr.length
     //   ? "\n..."
     //   : "";
                    msg += `<p>File contents:</p><code><textarea disabled class="form-control" rows="3">${params.fileInfo.contents}</textarea>`;
                }
                messagesApi.popupError(msg);
                return treeNodeList;
            }

            // Merge the tree nodes into one (so all compounds of multi-compound
            // file under single "Compounds").
            const topLevelName = getFileNameParts(
                params.fileInfo.name
            ).basename;
            const mergedTreeNodeList = treeNodeList.merge(topLevelName);

            // Make sure all molecules have a title. A title of a
            // terminal can be undefined if pasting, for example,
            // `C1C(N(C2=C(N1)N=C(NC2=O)N)C=O)CNC3=CC=C(C=C3)C(=O)NC(CCC(=O)[O-])C(=O)[O-].O.[Ca+2]`
            // TODO: Would be good to figure out why this happens, rather than fixing it here.
            mergedTreeNodeList.flattened.forEach((t) => {
                t.title = _fixTitle(t.title, params.defaultTitle as string);
            });

   // Get all the terminal nodes to process titles and visibility.
   const terminalNodes = mergedTreeNodeList.terminals;

   // Rename the nodes in treeNodeList and make some of them
   // invisible.
   for (let i = 0; i < terminalNodes.length; i++) {
    const node = terminalNodes.get(i);
    // If "undefined" in title, rename based on filename
    if (node.title.indexOf("undefined") >= 0) {
     const { basename } = getFileNameParts(params.fileInfo.name);
     node.title = basename + ":" + (i + 1).toString();
    }
   }

   // If hideOnLoad is true, set all nodes (including parents) to invisible.
   if (params.hideOnLoad) {
    mergedTreeNodeList.flattened.forEach((n) => {
     n.visible = false;
    });
   }

            if (params.addToTree) {
    // Pass !params.hideOnLoad as resetVisibilityAndSelection.
    // If hideOnLoad is true, we do NOT want addToMainTree to reset visibility to true.
    mergedTreeNodeList.addToMainTree(
     params.tag,
     true,
     true,
     !params.hideOnLoad
    );

    // If not hiding on load, check if we need to warn about too many visible molecules.
    if (!params.hideOnLoad) {
     const initialCompoundsVisible = await getSetting(
      "initialCompoundsVisible"
     );
     if (terminalNodes.length > initialCompoundsVisible) {
      messagesApi.popupMessage(
       "Some Molecules not Visible",
       `The ${params.fileInfo.name} file contained ${terminalNodes.length} molecules. Only ${initialCompoundsVisible} are initially shown for performance's sake. Use the Navigator to toggle the visibility of the remaining molecules.`,
       PopupVariant.Info,
       undefined,
       false,
       {}
      );
     }
    }
   }

            messagesApi.stopWaitSpinner(spinnerId);
            return mergedTreeNodeList;
        })
        .catch((err) => {
            messagesApi.stopWaitSpinner(spinnerId);
            throw err;
        });
}