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 SubVals sv = av.getSubVals();
171 String openFile = av.getValue();
172 if (openFile == null)
175 theseArgsWereParsed = true;
179 if (!headless && desktop != null)
181 desktop.setProgressBar(
182 MessageManager.getString(
183 "status.processing_commandline_args"),
184 progress = System.currentTimeMillis());
185 progressBarSet = true;
189 if (!Platform.isJS())
191 * ignore in JavaScript -- can't just file existence - could load it?
196 if (!HttpUtils.startsWithHttpOrHttps(openFile))
198 if (!(new File(openFile)).exists())
200 Console.warn("Can't find file '" + openFile + "'");
205 DataSourceType protocol = AppletFormatAdapter
206 .checkProtocol(openFile);
208 FileFormatI format = null;
211 format = new IdentifyFile().identify(openFile, protocol);
212 } catch (FileFormatException e1)
214 Console.error("Unknown file format for '" + openFile + "'");
218 // When to open a new AlignFrame
219 if (af == null || "true".equals(av.getSubVal("new"))
220 || a == Arg.OPEN || format == FileFormat.Jalview)
223 * this approach isn't working yet // get default annotations before opening
224 * AlignFrame if (m.get(Arg.SSANNOTATIONS) != null) {
225 * Console.debug("##### SSANNOTATIONS=" + m.get(Arg.SSANNOTATIONS).getBoolean());
226 * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
227 * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
228 * (m.get(Arg.SSANNOTATIONS) != null) ? m.get(Arg.SSANNOTATIONS).getBoolean() :
229 * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
230 * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
231 * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
232 * StructureSelectionManager ssm = StructureSelectionManager
233 * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
234 * ssm.setAddTempFacAnnot(showTemperatureFactor);
235 * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
239 "Opening '" + openFile + "' in new alignment frame");
240 FileLoader fileLoader = new FileLoader(!headless);
242 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
244 boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
245 Arg.ANNOTATIONS, av.getSubVals(), null,
246 "SHOW_ANNOTATIONS", true);
247 af.setAnnotationsVisibility(showAnnotations, false, true);
250 boolean wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv,
251 null, "WRAP_ALIGNMENT", false);
252 af.getCurrentView().setWrapAlignment(wrap);
255 String colour = ArgParser.getFromSubValArgOrPref(avm, Arg.COLOUR,
256 sv, null, "DEFAULT_COLOUR_PROT", "");
260 af.changeColour_actionPerformed(colour);
263 // change alignment frame title
264 String title = ArgParser.getFromSubValArgOrPref(avm, Arg.TITLE,
265 sv, null, null, null);
269 // show secondary structure annotations?
270 boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
271 Arg.SSANNOTATIONS, av.getSubVals(), null,
272 "STRUCT_FROM_PDB", true);
273 if (avm.getBoolean(Arg.SSANNOTATIONS))
275 af.setAnnotationsVisibility(showSSAnnotations, true, false);
277 AlignmentUtils.showOrHideSequenceAnnotations(
278 af.getCurrentView().getAlignment(),
279 Collections.singleton("Secondary Structure"), null,
284 // show temperature factor annotations?
285 if (avm.getBoolean(Arg.NOTEMPFAC))
287 // do this better (annotation types?)
288 List<String> hideThese = new ArrayList<>();
289 hideThese.add("Temperature Factor");
290 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
291 AlignmentUtils.showOrHideSequenceAnnotations(
292 af.getCurrentView().getAlignment(), hideThese, null,
297 * comment out hacky approach up to here and add this line: if
298 * (showTemperatureFactor)
302 if (avm.containsArg(Arg.TEMPFAC_LABEL))
304 AlignmentAnnotation aa = AlignmentUtils
305 .getFirstSequenceAnnotationOfType(
306 af.getCurrentView().getAlignment(),
307 AlignmentAnnotation.LINE_GRAPH);
308 String label = avm.getValue(Arg.TEMPFAC_LABEL);
316 "Could not find annotation to apply tempfac_label '"
323 // store the AlignFrame for this id
326 // is it its own structure file?
327 if (format.isStructureFile())
329 StructureSelectionManager ssm = StructureSelectionManager
330 .getStructureSelectionManager(Desktop.instance);
331 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
332 ssm.computeMapping(false, new SequenceI[] { seq }, null,
333 openFile, DataSourceType.FILE, null, null, null, false);
339 "Opening '" + openFile + "' in existing alignment frame");
340 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
342 : DataSourceType.FILE;
343 FileLoader fileLoader = new FileLoader(!headless);
344 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
348 Console.debug("Command " + Arg.APPEND + " executed successfully!");
351 if (first) // first=true means nothing opened
355 Jalview.exit("Could not open any files in headless mode", 1);
359 Console.warn("No more files to open");
362 if (progressBarSet && desktop != null)
363 desktop.setProgressBar(null, progress);
367 // open the structure (from same PDB file or given PDBfile)
368 if (!avm.getBoolean(Arg.NOSTRUCTURE))
370 AlignFrame af = afMap.get(id);
371 if (avm.containsArg(Arg.STRUCTURE))
373 commandArgsProvided = true;
374 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
376 String val = av.getValue();
377 SubVals subVals = av.getSubVals();
378 SequenceI seq = getSpecifiedSequence(af, subVals);
381 // Could not find sequence from subId, let's assume the first
382 // sequence in the alignframe
383 AlignmentI al = af.getCurrentView().getAlignment();
384 seq = al.getSequenceAt(0);
389 Console.warn("Could not find sequence for argument "
390 + Arg.STRUCTURE.argString() + "=" + val);
391 // you probably want to continue here, not break
395 File structureFile = null;
396 if (subVals.getContent() != null
397 && subVals.getContent().length() != 0)
399 structureFile = new File(subVals.getContent());
400 Console.debug("Using structure file (from argument) '"
401 + structureFile.getAbsolutePath() + "'");
405 * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
406 * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
407 * selectedSequence, true, Desktop.instance);
409 * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
410 * SequenceI[] { selectedSequence });
413 /* THIS DOESN'T WORK */
414 else if (seq.getAllPDBEntries() != null
415 && seq.getAllPDBEntries().size() > 0)
417 structureFile = new File(
418 seq.getAllPDBEntries().elementAt(0).getFile());
419 Console.debug("Using structure file (from sequence) '"
420 + structureFile.getAbsolutePath() + "'");
423 if (structureFile == null)
425 Console.warn("Not provided structure file with '" + val + "'");
429 if (!structureFile.exists())
431 Console.warn("Structure file '"
432 + structureFile.getAbsoluteFile() + "' not found.");
436 Console.debug("Using structure file "
437 + structureFile.getAbsolutePath());
439 // ##### Does this need to happen? Follow
440 // openStructureFileForSequence() below
442 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
443 .associatePdbWithSeq(structureFile.getAbsolutePath(),
444 DataSourceType.FILE, seq, true, Desktop.instance);
447 // open structure view
448 AlignmentPanel ap = af.alignPanel;
451 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
452 StructureViewer.ViewerType.JMOL.toString());
455 String structureFilepath = structureFile.getAbsolutePath();
457 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
458 String paeFilepath = subVals.getWithSubstitutions(argParser, id,
460 String paeLabel = subVals.get("paelabel");
461 ArgValue paeAv = getArgAssociatedWithStructure(Arg.PAEMATRIX, avm,
462 af, structureFilepath);
463 if (paeFilepath == null && paeAv != null)
465 SubVals sv = paeAv.getSubVals();
466 File paeFile = new File(sv.getContent());
468 paeLabel = sv.get("label");
471 paeFilepath = paeFile.getCanonicalPath();
472 } catch (IOException e)
474 paeFilepath = paeFile.getAbsolutePath();
475 Console.warn("Problem with the PAE file path: '"
476 + paeFile.getPath() + "'");
480 // showing annotations from structure file or not
481 boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
482 Arg.SSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
485 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
486 // reference annotations
487 String tftString = subVals.get("tempfac");
488 TFType tft = avm.getBoolean(Arg.NOTEMPFAC) ? null
490 ArgValue tftAv = getArgAssociatedWithStructure(Arg.TEMPFAC, avm,
491 af, structureFilepath);
492 if (tftString == null && tftAv != null)
494 tftString = tftAv.getSubVals().getContent();
496 if (tftString != null)
498 // get kind of temperature factor annotation
501 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
502 Console.debug("Obtained Temperature Factor type of '" + tft
503 + "' for structure '" + structureFilepath + "'");
504 } catch (IllegalArgumentException e)
506 // Just an error message!
507 StringBuilder sb = new StringBuilder().append("Cannot set ")
508 .append(Arg.TEMPFAC.argString()).append(" to '")
510 .append("', ignoring. Valid values are: ");
511 Iterator<TFType> it = Arrays.stream(TFType.values())
515 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
519 Console.warn(sb.toString());
523 String sViewer = ArgParser.getFromSubValArgOrPref(avm,
524 Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals,
525 "viewer", null, "jmol");
526 ViewerType viewerType = null;
527 if (!"none".equals(sViewer))
529 for (ViewerType v : EnumSet.allOf(ViewerType.class))
531 String name = v.name().toLowerCase(Locale.ROOT)
532 .replaceAll(" ", "");
533 if (sViewer.equals(name))
541 boolean addTempFac = tft != null
542 || Cache.getDefault("ADD_TEMPFACT_ANN", false);
544 // TODO use ssFromStructure
545 StructureChooser.openStructureFileForSequence(null, null, ap, seq,
546 false, structureFilepath, tft, paeFilepath, false,
547 ssFromStructure, false, viewerType);
553 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
556 AlignFrame af = afMap.get(id);
557 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
558 .findAnnotation(PDBChain.class.getName().toString()))
560 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
561 af.alignPanel.av.getGlobalColourScheme(), 0);
562 acg.setSeqAssociated(true);
563 af.changeColour(acg);
564 Console.info("Changed colour " + acg.toString());
569 return theseArgsWereParsed;
572 protected boolean processImages(String id)
574 ArgValuesMap avm = argParser.linkedArgs(id);
575 AlignFrame af = afMap.get(id);
579 Console.warn("Did not have an alignment window for id=" + id);
583 if (avm.containsArg(Arg.IMAGE))
585 for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
587 String val = av.getValue();
588 SubVals subVal = av.getSubVals();
589 String type = "png"; // default
590 String fileName = subVal.getContent();
591 File file = new File(fileName);
592 if (subVal.has("type"))
594 type = subVal.get("type");
596 else if (fileName != null)
598 for (String ext : new String[] { "svg", "png", "html" })
600 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
606 // for moment we disable JSON export
607 Cache.setPropsAreReadOnly(true);
608 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
613 Console.debug("Outputting type '" + type + "' to " + fileName);
617 Console.debug("Outputting type '" + type + "' to " + fileName);
621 Console.debug("Outputting type '" + type + "' to " + fileName);
622 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
623 htmlSVG.exportHTML(fileName);
626 Console.warn(Arg.IMAGE.argString() + " type '" + type
627 + "' not known. Ignoring");
635 private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
639 AlignmentI al = af.getCurrentView().getAlignment();
640 if (subId.has("seqid"))
642 return al.findName(subId.get("seqid"));
644 else if (-1 < subId.getIndex()
645 && subId.getIndex() < al.getSequences().size())
647 return al.getSequenceAt(subId.getIndex());
652 // returns the first Arg value intended for the structure structFilename
653 // (in the given AlignFrame from the ArgValuesMap)
654 private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
655 AlignFrame af, String structFilename)
659 for (ArgValue av : avm.getArgValueList(arg))
661 SubVals subVals = av.getSubVals();
662 String structid = subVals.get("structid");
663 String structfile = subVals.get("structfile");
665 // let's find a structure
666 if (structfile == null && structid == null)
668 ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
670 if (likelyStructure != null)
672 SubVals sv = likelyStructure.getSubVals();
673 if (sv != null && sv.has(ArgValues.ID))
675 structid = sv.get(ArgValues.ID);
679 structfile = likelyStructure.getValue();
681 "##### Comparing closest previous structure argument '"
687 if (structfile == null && structid != null)
689 StructureSelectionManager ssm = StructureSelectionManager
690 .getStructureSelectionManager(Desktop.instance);
693 structfile = ssm.findFileForPDBId(structid);
696 if (structfile != null && structfile.equals(structFilename))