4 import java.io.IOException;
5 import java.util.AbstractMap;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Locale;
14 import java.util.Map.Entry;
16 import jalview.analysis.AlignmentUtils;
17 import jalview.bin.argparser.Arg;
18 import jalview.bin.argparser.ArgParser;
19 import jalview.bin.argparser.ArgValue;
20 import jalview.bin.argparser.ArgValues;
21 import jalview.bin.argparser.ArgValuesMap;
22 import jalview.bin.argparser.SubVals;
23 import jalview.datamodel.AlignmentAnnotation;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.PDBEntry;
26 import jalview.datamodel.SequenceI;
27 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
28 import jalview.gui.AlignFrame;
29 import jalview.gui.AlignmentPanel;
30 import jalview.gui.AssociatePdbFileWithSeq;
31 import jalview.gui.Desktop;
32 import jalview.gui.Preferences;
33 import jalview.gui.StructureChooser;
34 import jalview.gui.StructureViewer;
35 import jalview.io.AppletFormatAdapter;
36 import jalview.io.DataSourceType;
37 import jalview.io.FileFormat;
38 import jalview.io.FileFormatException;
39 import jalview.io.FileFormatI;
40 import jalview.io.FileLoader;
41 import jalview.io.HtmlSvgOutput;
42 import jalview.io.IdentifyFile;
43 import jalview.schemes.AnnotationColourGradient;
44 import jalview.structure.StructureImportSettings.TFType;
45 import jalview.structure.StructureSelectionManager;
46 import jalview.util.HttpUtils;
47 import jalview.util.MessageManager;
48 import jalview.util.Platform;
49 import mc_view.PDBChain;
55 private boolean headless;
57 private ArgParser argParser;
59 private Map<String, AlignFrame> afMap;
61 private boolean commandArgsProvided = false;
63 private boolean argsWereParsed = false;
65 public Commands(ArgParser argparser, boolean headless)
67 this(Desktop.instance, argparser, headless);
70 public Commands(Desktop d, ArgParser argparser, boolean h)
72 argParser = argparser;
75 afMap = new HashMap<String, AlignFrame>();
76 if (argparser != null)
78 processArgs(argparser, headless);
82 private boolean processArgs(ArgParser argparser, boolean h)
84 argParser = argparser;
86 boolean theseArgsWereParsed = false;
88 if (argParser != null && argParser.linkedIds() != null)
90 for (String id : argParser.linkedIds())
92 ArgValuesMap avm = argParser.linkedArgs(id);
93 theseArgsWereParsed = true;
96 theseArgsWereParsed &= processUnlinked(id);
100 theseArgsWereParsed &= processLinked(id);
102 theseArgsWereParsed &= processImages(id);
105 if (avm.getBoolean(Arg.CLOSE))
107 AlignFrame af = afMap.get(id);
110 af.closeMenuItem_actionPerformed(true);
117 if (argParser.getBool(Arg.QUIT))
119 Jalview.getInstance().quit();
122 // carry on with jalview.bin.Jalview
123 argsWereParsed = theseArgsWereParsed;
124 return argsWereParsed;
127 public boolean commandArgsProvided()
129 return commandArgsProvided;
132 public boolean argsWereParsed()
134 return argsWereParsed;
137 protected boolean processUnlinked(String id)
139 return processLinked(id);
142 protected boolean processLinked(String id)
144 boolean theseArgsWereParsed = false;
145 ArgValuesMap avm = argParser.linkedArgs(id);
150 * // script to execute after all loading is completed one way or another String
151 * groovyscript = m.get(Arg.GROOVY) == null ? null :
152 * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
153 * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
154 * DataSourceType protocol = null;
156 if (avm.containsArg(Arg.OPEN) || avm.containsArg(Arg.OPENNEW))
158 commandArgsProvided = true;
161 boolean first = true;
162 boolean progressBarSet = false;
164 // Combine the OPEN and OPENNEW files into one list, along with whether it
165 // was OPEN or OPENNEW
166 List<Entry<Arg, ArgValue>> openAvList = new ArrayList<>();
167 avm.getArgValueList(Arg.OPEN).stream()
168 .forEachOrdered(av -> openAvList.add(
169 new AbstractMap.SimpleEntry<Arg, ArgValue>(Arg.OPEN,
171 avm.getArgValueList(Arg.OPENNEW).stream()
172 .forEachOrdered(av -> openAvList
173 .add(new AbstractMap.SimpleEntry<Arg, ArgValue>(
175 for (Entry<Arg, ArgValue> aav : openAvList)
177 Arg a = aav.getKey();
178 ArgValue av = aav.getValue();
179 String openFile = av.getValue();
180 if (openFile == null)
183 theseArgsWereParsed = true;
187 if (!headless && desktop != null)
189 desktop.setProgressBar(
190 MessageManager.getString(
191 "status.processing_commandline_args"),
192 progress = System.currentTimeMillis());
193 progressBarSet = true;
197 if (!Platform.isJS())
199 * ignore in JavaScript -- can't just file existence - could load it?
204 if (!HttpUtils.startsWithHttpOrHttps(openFile))
206 if (!(new File(openFile)).exists())
208 Console.warn("Can't find file '" + openFile + "'");
213 DataSourceType protocol = AppletFormatAdapter
214 .checkProtocol(openFile);
216 FileFormatI format = null;
219 format = new IdentifyFile().identify(openFile, protocol);
220 } catch (FileFormatException e1)
222 Console.error("Unknown file format for '" + openFile + "'");
226 if (af == null || "true".equals(av.getSubVal("new"))
227 || a == Arg.OPENNEW || format == FileFormat.Jalview)
230 * this approach isn't working yet // get default annotations before opening
231 * AlignFrame if (m.get(Arg.SSANNOTATION) != null) {
232 * Console.debug("##### SSANNOTATION=" + m.get(Arg.SSANNOTATION).getBoolean());
233 * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
234 * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
235 * (m.get(Arg.SSANNOTATION) != null) ? m.get(Arg.SSANNOTATION).getBoolean() :
236 * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
237 * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
238 * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
239 * StructureSelectionManager ssm = StructureSelectionManager
240 * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
241 * ssm.setAddTempFacAnnot(showTemperatureFactor);
242 * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
246 "Opening '" + openFile + "' in new alignment frame");
247 FileLoader fileLoader = new FileLoader(!headless);
249 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
253 if (avm.getBoolean(Arg.WRAP))
255 af.getCurrentView().setWrapAlignment(true);
259 if (avm.containsArg(Arg.COLOUR))
261 af.changeColour_actionPerformed(avm.getValue(Arg.COLOUR));
264 // change alignment frame title
265 if (avm.containsArg(Arg.TITLE))
266 af.setTitle(avm.getValue(Arg.TITLE));
268 /* hacky approach to hiding the annotations */
269 // show secondary structure annotations?
270 if (avm.getBoolean(Arg.SSANNOTATION))
272 // do this better (annotation types?)
273 AlignmentUtils.showOrHideSequenceAnnotations(
274 af.getCurrentView().getAlignment(),
275 Collections.singleton("Secondary Structure"), null,
279 // show temperature factor annotations?
280 if (avm.getBoolean(Arg.NOTEMPFAC))
282 // do this better (annotation types?)
283 List<String> hideThese = new ArrayList<>();
284 hideThese.add("Temperature Factor");
285 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
286 AlignmentUtils.showOrHideSequenceAnnotations(
287 af.getCurrentView().getAlignment(), hideThese, null,
292 * comment out hacky approach up to here and add this line: if
293 * (showTemperatureFactor)
296 if (avm.containsArg(Arg.TEMPFAC_LABEL))
298 AlignmentAnnotation aa = AlignmentUtils
299 .getFirstSequenceAnnotationOfType(
300 af.getCurrentView().getAlignment(),
301 AlignmentAnnotation.LINE_GRAPH);
302 String label = avm.getValue(Arg.TEMPFAC_LABEL);
310 "Could not find annotation to apply tempfac_label '"
316 // store the AlignFrame for this id
319 // is it its own structure file?
320 if (format.isStructureFile())
322 StructureSelectionManager ssm = StructureSelectionManager
323 .getStructureSelectionManager(Desktop.instance);
324 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
325 ssm.computeMapping(false, new SequenceI[] { seq }, null,
326 openFile, DataSourceType.FILE, null, null, null);
332 "Opening '" + openFile + "' in existing alignment frame");
333 af.getCurrentView().addFile(new File(openFile), format, false);
336 Console.debug("Command " + Arg.OPEN + " executed successfully!");
339 if (first) // first=true means nothing opened
343 Jalview.exit("Could not open any files in headless mode", 1);
347 Console.warn("No more files to open");
350 if (progressBarSet && desktop != null)
351 desktop.setProgressBar(null, progress);
355 // open the structure (from same PDB file or given PDBfile)
356 if (!avm.getBoolean(Arg.NOSTRUCTURE))
358 AlignFrame af = afMap.get(id);
359 if (avm.containsArg(Arg.STRUCTURE))
361 commandArgsProvided = true;
362 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
364 String val = av.getValue();
365 SubVals subVals = av.getSubVals();
366 SequenceI seq = getSpecifiedSequence(af, subVals);
369 // Could not find sequence from subId, let's assume the first
370 // sequence in the alignframe
371 AlignmentI al = af.getCurrentView().getAlignment();
372 seq = al.getSequenceAt(0);
377 Console.warn("Could not find sequence for argument "
378 + Arg.STRUCTURE.argString() + "=" + val);
379 // you probably want to continue here, not break
383 File structureFile = null;
384 if (subVals.getContent() != null
385 && subVals.getContent().length() != 0)
387 structureFile = new File(subVals.getContent());
388 Console.debug("Using structure file (from argument) '"
389 + structureFile.getAbsolutePath() + "'");
393 * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
394 * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
395 * selectedSequence, true, Desktop.instance);
397 * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
398 * SequenceI[] { selectedSequence });
401 /* THIS DOESN'T WORK */
402 else if (seq.getAllPDBEntries() != null
403 && seq.getAllPDBEntries().size() > 0)
405 structureFile = new File(
406 seq.getAllPDBEntries().elementAt(0).getFile());
407 Console.debug("Using structure file (from sequence) '"
408 + structureFile.getAbsolutePath() + "'");
411 if (structureFile == null)
413 Console.warn("Not provided structure file with '" + val + "'");
417 if (!structureFile.exists())
419 Console.warn("Structure file '"
420 + structureFile.getAbsoluteFile() + "' not found.");
424 Console.debug("Using structure file "
425 + structureFile.getAbsolutePath());
427 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
428 .associatePdbWithSeq(structureFile.getAbsolutePath(),
429 DataSourceType.FILE, seq, true, Desktop.instance);
431 // open structure view
432 AlignmentPanel ap = af.alignPanel;
435 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
436 StructureViewer.ViewerType.JMOL.toString());
439 String structureFilepath = structureFile.getAbsolutePath();
441 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
442 String paeFilepath = subVals.getWithSubstitutions(argParser, id,
444 String paeLabel = subVals.get("paelabel");
445 ArgValue paeAv = getArgAssociatedWithStructure(Arg.PAEMATRIX, avm,
446 af, structureFilepath);
447 if (paeFilepath == null && paeAv != null)
449 SubVals sv = paeAv.getSubVals();
450 File paeFile = new File(sv.getContent());
452 paeLabel = sv.get("label");
455 paeFilepath = paeFile.getCanonicalPath();
456 } catch (IOException e)
458 paeFilepath = paeFile.getAbsolutePath();
459 Console.warn("Problem with the PAE file path: '"
460 + paeFile.getPath() + "'");
464 // get TEMPFAC type from subvals or Arg.TEMPFAC
465 String tftString = subVals.get("tempfac");
466 TFType tft = avm.getBoolean(Arg.NOTEMPFAC) ? null
468 ArgValue tftAv = getArgAssociatedWithStructure(Arg.TEMPFAC, avm,
469 af, structureFilepath);
470 if (tftString == null && tftAv != null)
472 tftString = tftAv.getSubVals().getContent();
474 if (tftString != null)
476 // get kind of temperature factor annotation
479 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
480 Console.debug("Obtained Temperature Factor type of '" + tft
481 + "' for structure '" + structureFilepath + "'");
482 } catch (IllegalArgumentException e)
484 // Just an error message!
485 StringBuilder sb = new StringBuilder().append("Cannot set ")
486 .append(Arg.TEMPFAC.argString()).append(" to '")
488 .append("', ignoring. Valid values are: ");
489 Iterator<TFType> it = Arrays.stream(TFType.values())
493 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
497 Console.warn(sb.toString());
501 // TODO pass PAE label
502 StructureChooser.openStructureFileForSequence(null, null, ap, seq,
503 false, structureFilepath, tft, paeFilepath);
508 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
511 AlignFrame af = afMap.get(id);
512 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
513 .findAnnotation(PDBChain.class.getName().toString()))
515 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
516 af.alignPanel.av.getGlobalColourScheme(), 0);
517 acg.setSeqAssociated(true);
518 af.changeColour(acg);
519 Console.info("Changed colour " + acg.toString());
523 return theseArgsWereParsed;
526 protected boolean processImages(String id)
528 ArgValuesMap avm = argParser.linkedArgs(id);
529 AlignFrame af = afMap.get(id);
533 Console.warn("Did not have an alignment window for id=" + id);
537 if (avm.containsArg(Arg.IMAGE))
539 for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
541 String val = av.getValue();
542 SubVals subVal = av.getSubVals();
543 String type = "png"; // default
544 String fileName = subVal.getContent();
545 File file = new File(fileName);
546 if (subVal.has("type"))
548 type = subVal.get("type");
550 else if (fileName != null)
552 for (String ext : new String[] { "svg", "png", "html" })
554 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
560 // for moment we disable JSON export
561 Cache.setPropsAreReadOnly(true);
562 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
567 Console.debug("Outputting type '" + type + "' to " + fileName);
571 Console.debug("Outputting type '" + type + "' to " + fileName);
575 Console.debug("Outputting type '" + type + "' to " + fileName);
576 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
577 htmlSVG.exportHTML(fileName);
580 Console.warn(Arg.IMAGE.argString() + " type '" + type
581 + "' not known. Ignoring");
589 private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
593 AlignmentI al = af.getCurrentView().getAlignment();
594 if (subId.has("seqid"))
596 return al.findName(subId.get("seqid"));
598 else if (-1 < subId.getIndex()
599 && subId.getIndex() < al.getSequences().size())
601 return al.getSequenceAt(subId.getIndex());
606 // returns the first Arg value intended for the structure structFilename
607 // (in the given AlignFrame from the ArgValuesMap)
608 private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
609 AlignFrame af, String structFilename)
613 for (ArgValue av : avm.getArgValueList(arg))
615 SubVals subVals = av.getSubVals();
616 String structid = subVals.get("structid");
617 String structfile = subVals.get("structfile");
619 // let's find a structure
620 if (structfile == null && structid == null)
622 ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
624 if (likelyStructure != null)
626 SubVals sv = likelyStructure.getSubVals();
627 if (sv != null && sv.has(ArgValues.ID))
629 structid = sv.get(ArgValues.ID);
633 structfile = likelyStructure.getValue();
635 "##### Comparing closest previous structure argument '"
641 if (structfile == null && structid != null)
643 StructureSelectionManager ssm = StructureSelectionManager
644 .getStructureSelectionManager(Desktop.instance);
647 structfile = ssm.findFileForPDBId(structid);
650 if (structfile != null && structfile.equals(structFilename))