4 import java.io.IOException;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.Collections;
8 import java.util.EnumSet;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Locale;
15 import jalview.analysis.AlignmentUtils;
16 import jalview.bin.argparser.Arg;
17 import jalview.bin.argparser.ArgParser;
18 import jalview.bin.argparser.ArgParser.Position;
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.AlignmentI;
24 import jalview.datamodel.SequenceI;
25 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
26 import jalview.gui.AlignFrame;
27 import jalview.gui.AlignmentPanel;
28 import jalview.gui.Desktop;
29 import jalview.gui.Preferences;
30 import jalview.gui.StructureChooser;
31 import jalview.gui.StructureViewer;
32 import jalview.gui.StructureViewer.ViewerType;
33 import jalview.io.AppletFormatAdapter;
34 import jalview.io.DataSourceType;
35 import jalview.io.FileFormat;
36 import jalview.io.FileFormatException;
37 import jalview.io.FileFormatI;
38 import jalview.io.FileLoader;
39 import jalview.io.HtmlSvgOutput;
40 import jalview.io.IdentifyFile;
41 import jalview.structure.StructureImportSettings.TFType;
42 import jalview.structure.StructureSelectionManager;
43 import jalview.util.HttpUtils;
44 import jalview.util.MessageManager;
45 import jalview.util.Platform;
51 private boolean headless;
53 private ArgParser argParser;
55 private Map<String, AlignFrame> afMap;
57 private boolean commandArgsProvided = false;
59 private boolean argsWereParsed = false;
61 public Commands(ArgParser argparser, boolean headless)
63 this(Desktop.instance, argparser, headless);
66 public Commands(Desktop d, ArgParser argparser, boolean h)
68 argParser = argparser;
71 afMap = new HashMap<String, AlignFrame>();
72 if (argparser != null)
74 processArgs(argparser, headless);
78 private boolean processArgs(ArgParser argparser, boolean h)
80 argParser = argparser;
82 boolean theseArgsWereParsed = false;
84 if (argParser != null && argParser.linkedIds() != null)
86 for (String id : argParser.linkedIds())
88 ArgValuesMap avm = argParser.linkedArgs(id);
89 theseArgsWereParsed = true;
92 theseArgsWereParsed &= processUnlinked(id);
96 theseArgsWereParsed &= processLinked(id);
98 theseArgsWereParsed &= processImages(id);
101 if (avm.getBoolean(Arg.CLOSE))
103 AlignFrame af = afMap.get(id);
106 af.closeMenuItem_actionPerformed(true);
113 if (argParser.getBool(Arg.QUIT))
115 Jalview.getInstance().quit();
118 // carry on with jalview.bin.Jalview
119 argsWereParsed = theseArgsWereParsed;
120 return argsWereParsed;
123 public boolean commandArgsProvided()
125 return commandArgsProvided;
128 public boolean argsWereParsed()
130 return argsWereParsed;
133 protected boolean processUnlinked(String id)
135 return processLinked(id);
138 protected boolean processLinked(String id)
140 boolean theseArgsWereParsed = false;
141 ArgValuesMap avm = argParser.linkedArgs(id);
146 * // script to execute after all loading is completed one way or another String
147 * groovyscript = m.get(Arg.GROOVY) == null ? null :
148 * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
149 * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
150 * DataSourceType protocol = null;
152 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
154 commandArgsProvided = true;
157 boolean first = true;
158 boolean progressBarSet = false;
160 // Combine the APPEND and OPEN files into one list, along with whether it
161 // was APPEND or OPEN
162 List<ArgValue> openAvList = new ArrayList<>();
163 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
164 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
165 // sort avlist based on av.getArgIndex()
166 Collections.sort(openAvList);
167 for (ArgValue av : openAvList)
170 String openFile = av.getValue();
171 if (openFile == null)
174 theseArgsWereParsed = true;
178 if (!headless && desktop != null)
180 desktop.setProgressBar(
181 MessageManager.getString(
182 "status.processing_commandline_args"),
183 progress = System.currentTimeMillis());
184 progressBarSet = true;
188 if (!Platform.isJS())
190 * ignore in JavaScript -- can't just file existence - could load it?
195 if (!HttpUtils.startsWithHttpOrHttps(openFile))
197 if (!(new File(openFile)).exists())
199 Console.warn("Can't find file '" + openFile + "'");
204 DataSourceType protocol = AppletFormatAdapter
205 .checkProtocol(openFile);
207 FileFormatI format = null;
210 format = new IdentifyFile().identify(openFile, protocol);
211 } catch (FileFormatException e1)
213 Console.error("Unknown file format for '" + openFile + "'");
217 if (af == null || "true".equals(av.getSubVal("new"))
218 || a == Arg.OPEN || format == FileFormat.Jalview)
221 * this approach isn't working yet // get default annotations before opening
222 * AlignFrame if (m.get(Arg.SSANNOTATIONS) != null) {
223 * Console.debug("##### SSANNOTATIONS=" + m.get(Arg.SSANNOTATIONS).getBoolean());
224 * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
225 * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
226 * (m.get(Arg.SSANNOTATIONS) != null) ? m.get(Arg.SSANNOTATIONS).getBoolean() :
227 * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
228 * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
229 * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
230 * StructureSelectionManager ssm = StructureSelectionManager
231 * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
232 * ssm.setAddTempFacAnnot(showTemperatureFactor);
233 * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
237 "Opening '" + openFile + "' in new alignment frame");
238 FileLoader fileLoader = new FileLoader(!headless);
240 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
242 boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
243 Arg.ANNOTATIONS, av.getSubVals(), null,
244 "SHOW_ANNOTATIONS", true);
245 af.setAnnotationsVisibility(showAnnotations, false, true);
248 if (avm.getBoolean(Arg.WRAP))
250 af.getCurrentView().setWrapAlignment(true);
254 if (avm.containsArg(Arg.COLOUR))
256 af.changeColour_actionPerformed(avm.getValue(Arg.COLOUR));
259 // change alignment frame title
260 if (avm.containsArg(Arg.TITLE))
261 af.setTitle(avm.getValue(Arg.TITLE));
263 // show secondary structure annotations?
264 boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
265 Arg.SSANNOTATIONS, av.getSubVals(), null,
266 "STRUCT_FROM_PDB", true);
267 if (avm.getBoolean(Arg.SSANNOTATIONS))
269 af.setAnnotationsVisibility(showSSAnnotations, true, false);
271 AlignmentUtils.showOrHideSequenceAnnotations(
272 af.getCurrentView().getAlignment(),
273 Collections.singleton("Secondary Structure"), null,
278 // show temperature factor annotations?
279 if (avm.getBoolean(Arg.NOTEMPFAC))
281 // do this better (annotation types?)
282 List<String> hideThese = new ArrayList<>();
283 hideThese.add("Temperature Factor");
284 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
285 AlignmentUtils.showOrHideSequenceAnnotations(
286 af.getCurrentView().getAlignment(), hideThese, null,
291 * comment out hacky approach up to here and add this line: if
292 * (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 '"
317 // store the AlignFrame for this id
320 // is it its own structure file?
321 if (format.isStructureFile())
323 StructureSelectionManager ssm = StructureSelectionManager
324 .getStructureSelectionManager(Desktop.instance);
325 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
326 ssm.computeMapping(false, new SequenceI[] { seq }, null,
327 openFile, DataSourceType.FILE, null, null, null, false);
333 "Opening '" + openFile + "' in existing alignment frame");
334 af.getCurrentView().addFile(new File(openFile), format, false);
337 Console.debug("Command " + Arg.APPEND + " executed successfully!");
340 if (first) // first=true means nothing opened
344 Jalview.exit("Could not open any files in headless mode", 1);
348 Console.warn("No more files to open");
351 if (progressBarSet && desktop != null)
352 desktop.setProgressBar(null, progress);
356 // open the structure (from same PDB file or given PDBfile)
357 if (!avm.getBoolean(Arg.NOSTRUCTURE))
359 AlignFrame af = afMap.get(id);
360 if (avm.containsArg(Arg.STRUCTURE))
362 commandArgsProvided = true;
363 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
365 String val = av.getValue();
366 SubVals subVals = av.getSubVals();
367 SequenceI seq = getSpecifiedSequence(af, subVals);
370 // Could not find sequence from subId, let's assume the first
371 // sequence in the alignframe
372 AlignmentI al = af.getCurrentView().getAlignment();
373 seq = al.getSequenceAt(0);
378 Console.warn("Could not find sequence for argument "
379 + Arg.STRUCTURE.argString() + "=" + val);
380 // you probably want to continue here, not break
384 File structureFile = null;
385 if (subVals.getContent() != null
386 && subVals.getContent().length() != 0)
388 structureFile = new File(subVals.getContent());
389 Console.debug("Using structure file (from argument) '"
390 + structureFile.getAbsolutePath() + "'");
394 * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
395 * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
396 * selectedSequence, true, Desktop.instance);
398 * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
399 * SequenceI[] { selectedSequence });
402 /* THIS DOESN'T WORK */
403 else if (seq.getAllPDBEntries() != null
404 && seq.getAllPDBEntries().size() > 0)
406 structureFile = new File(
407 seq.getAllPDBEntries().elementAt(0).getFile());
408 Console.debug("Using structure file (from sequence) '"
409 + structureFile.getAbsolutePath() + "'");
412 if (structureFile == null)
414 Console.warn("Not provided structure file with '" + val + "'");
418 if (!structureFile.exists())
420 Console.warn("Structure file '"
421 + structureFile.getAbsoluteFile() + "' not found.");
425 Console.debug("Using structure file "
426 + structureFile.getAbsolutePath());
428 // ##### Does this need to happen? Follow
429 // openStructureFileForSequence() below
431 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
432 .associatePdbWithSeq(structureFile.getAbsolutePath(),
433 DataSourceType.FILE, seq, true, Desktop.instance);
436 // open structure view
437 AlignmentPanel ap = af.alignPanel;
440 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
441 StructureViewer.ViewerType.JMOL.toString());
444 String structureFilepath = structureFile.getAbsolutePath();
446 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
447 String paeFilepath = subVals.getWithSubstitutions(argParser, id,
449 String paeLabel = subVals.get("paelabel");
450 ArgValue paeAv = getArgAssociatedWithStructure(Arg.PAEMATRIX, avm,
451 af, structureFilepath);
452 if (paeFilepath == null && paeAv != null)
454 SubVals sv = paeAv.getSubVals();
455 File paeFile = new File(sv.getContent());
457 paeLabel = sv.get("label");
460 paeFilepath = paeFile.getCanonicalPath();
461 } catch (IOException e)
463 paeFilepath = paeFile.getAbsolutePath();
464 Console.warn("Problem with the PAE file path: '"
465 + paeFile.getPath() + "'");
469 // showing annotations from structure file or not
470 boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
471 Arg.SSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
474 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
475 // reference annotations
476 String tftString = subVals.get("tempfac");
477 TFType tft = avm.getBoolean(Arg.NOTEMPFAC) ? null
479 ArgValue tftAv = getArgAssociatedWithStructure(Arg.TEMPFAC, avm,
480 af, structureFilepath);
481 if (tftString == null && tftAv != null)
483 tftString = tftAv.getSubVals().getContent();
485 if (tftString != null)
487 // get kind of temperature factor annotation
490 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
491 Console.debug("Obtained Temperature Factor type of '" + tft
492 + "' for structure '" + structureFilepath + "'");
493 } catch (IllegalArgumentException e)
495 // Just an error message!
496 StringBuilder sb = new StringBuilder().append("Cannot set ")
497 .append(Arg.TEMPFAC.argString()).append(" to '")
499 .append("', ignoring. Valid values are: ");
500 Iterator<TFType> it = Arrays.stream(TFType.values())
504 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
508 Console.warn(sb.toString());
512 String sViewer = ArgParser.getFromSubValArgOrPref(avm,
513 Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals,
514 "viewer", null, "jmol");
515 ViewerType viewerType = null;
516 if (!"none".equals(sViewer))
518 for (ViewerType v : EnumSet.allOf(ViewerType.class))
520 String name = v.name().toLowerCase(Locale.ROOT)
521 .replaceAll(" ", "");
522 if (sViewer.equals(name))
530 boolean addTempFac = tft != null
531 || Cache.getDefault("ADD_TEMPFACT_ANN", false);
533 // TODO use ssFromStructure
534 StructureChooser.openStructureFileForSequence(null, null, ap, seq,
535 false, structureFilepath, tft, paeFilepath, false,
536 ssFromStructure, false, viewerType);
542 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
545 AlignFrame af = afMap.get(id);
546 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
547 .findAnnotation(PDBChain.class.getName().toString()))
549 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
550 af.alignPanel.av.getGlobalColourScheme(), 0);
551 acg.setSeqAssociated(true);
552 af.changeColour(acg);
553 Console.info("Changed colour " + acg.toString());
558 return theseArgsWereParsed;
561 protected boolean processImages(String id)
563 ArgValuesMap avm = argParser.linkedArgs(id);
564 AlignFrame af = afMap.get(id);
568 Console.warn("Did not have an alignment window for id=" + id);
572 if (avm.containsArg(Arg.IMAGE))
574 for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
576 String val = av.getValue();
577 SubVals subVal = av.getSubVals();
578 String type = "png"; // default
579 String fileName = subVal.getContent();
580 File file = new File(fileName);
581 if (subVal.has("type"))
583 type = subVal.get("type");
585 else if (fileName != null)
587 for (String ext : new String[] { "svg", "png", "html" })
589 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
595 // for moment we disable JSON export
596 Cache.setPropsAreReadOnly(true);
597 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
602 Console.debug("Outputting type '" + type + "' to " + fileName);
606 Console.debug("Outputting type '" + type + "' to " + fileName);
610 Console.debug("Outputting type '" + type + "' to " + fileName);
611 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
612 htmlSVG.exportHTML(fileName);
615 Console.warn(Arg.IMAGE.argString() + " type '" + type
616 + "' not known. Ignoring");
624 private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
628 AlignmentI al = af.getCurrentView().getAlignment();
629 if (subId.has("seqid"))
631 return al.findName(subId.get("seqid"));
633 else if (-1 < subId.getIndex()
634 && subId.getIndex() < al.getSequences().size())
636 return al.getSequenceAt(subId.getIndex());
641 // returns the first Arg value intended for the structure structFilename
642 // (in the given AlignFrame from the ArgValuesMap)
643 private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
644 AlignFrame af, String structFilename)
648 for (ArgValue av : avm.getArgValueList(arg))
650 SubVals subVals = av.getSubVals();
651 String structid = subVals.get("structid");
652 String structfile = subVals.get("structfile");
654 // let's find a structure
655 if (structfile == null && structid == null)
657 ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
659 if (likelyStructure != null)
661 SubVals sv = likelyStructure.getSubVals();
662 if (sv != null && sv.has(ArgValues.ID))
664 structid = sv.get(ArgValues.ID);
668 structfile = likelyStructure.getValue();
670 "##### Comparing closest previous structure argument '"
676 if (structfile == null && structid != null)
678 StructureSelectionManager ssm = StructureSelectionManager
679 .getStructureSelectionManager(Desktop.instance);
682 structfile = ssm.findFileForPDBId(structid);
685 if (structfile != null && structfile.equals(structFilename))