4 import java.io.IOException;
5 import java.net.URISyntaxException;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.EnumSet;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Locale;
16 import jalview.analysis.AlignmentUtils;
17 import jalview.bin.argparser.Arg;
18 import jalview.bin.argparser.ArgParser;
19 import jalview.bin.argparser.ArgParser.Position;
20 import jalview.bin.argparser.ArgValue;
21 import jalview.bin.argparser.ArgValues;
22 import jalview.bin.argparser.ArgValuesMap;
23 import jalview.bin.argparser.SubVals;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.SequenceI;
26 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
27 import jalview.gui.AlignFrame;
28 import jalview.gui.AlignmentPanel;
29 import jalview.gui.Desktop;
30 import jalview.gui.Preferences;
31 import jalview.gui.StructureChooser;
32 import jalview.gui.StructureViewer;
33 import jalview.gui.StructureViewer.ViewerType;
34 import jalview.io.AppletFormatAdapter;
35 import jalview.io.BackupFiles;
36 import jalview.io.BioJsHTMLOutput;
37 import jalview.io.DataSourceType;
38 import jalview.io.FileFormat;
39 import jalview.io.FileFormatException;
40 import jalview.io.FileFormatI;
41 import jalview.io.FileFormats;
42 import jalview.io.FileLoader;
43 import jalview.io.HtmlSvgOutput;
44 import jalview.io.IdentifyFile;
45 import jalview.structure.StructureImportSettings.TFType;
46 import jalview.structure.StructureSelectionManager;
47 import jalview.util.HttpUtils;
48 import jalview.util.MessageManager;
49 import jalview.util.Platform;
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.getLinkedIds() != null)
90 for (String id : argParser.getLinkedIds())
92 ArgValuesMap avm = argParser.getLinkedArgs(id);
93 theseArgsWereParsed = true;
94 theseArgsWereParsed &= processLinked(id);
95 boolean processLinkedOkay = theseArgsWereParsed;
96 theseArgsWereParsed &= processImages(id);
97 if (processLinkedOkay)
98 theseArgsWereParsed &= processOutput(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.getLinkedArgs(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, av,
256 Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
260 af.changeColour_actionPerformed(colour);
263 // change alignment frame title
264 String title = ArgParser.getFromSubValArgOrPref(avm, av,
265 Arg.TITLE, 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.getLinkedArgs(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 fileName = subVal.getContent();
590 File file = new File(fileName);
591 String name = af.getName();
592 String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
593 Arg.RENDERER, subVal);
594 if (renderer == null)
596 String type = "png"; // default
597 type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
598 if (type == null && fileName != null)
600 for (String ext : new String[] { "svg", "png", "html", "eps" })
602 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
608 // for moment we disable JSON export
609 Cache.setPropsAreReadOnly(true);
610 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
616 Console.debug("Outputting type '" + type + "' to " + fileName);
617 af.createSVG(file, renderer);
621 Console.debug("Outputting type '" + type + "' to " + fileName);
626 Console.debug("Outputting type '" + type + "' to " + fileName);
627 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
628 htmlSVG.exportHTML(fileName, renderer);
634 BioJsHTMLOutput.refreshVersionInfo(
635 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
636 } catch (URISyntaxException e)
640 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
641 bjs.exportHTML(fileName);
642 Console.debug("Creating BioJS MSA Viwer HTML file: " + fileName);
646 af.createEPS(file, name);
647 Console.debug("Creating EPS file: " + fileName);
651 af.createImageMap(file, name);
652 Console.debug("Creating ImageMap file: " + fileName);
656 Console.warn(Arg.IMAGE.argString() + " type '" + type
657 + "' not known. Ignoring");
665 protected boolean processOutput(String id)
667 ArgValuesMap avm = argParser.getLinkedArgs(id);
668 AlignFrame af = afMap.get(id);
672 Console.warn("Did not have an alignment window for id=" + id);
676 if (avm.containsArg(Arg.OUTPUT))
678 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
680 String val = av.getValue();
681 SubVals subVals = av.getSubVals();
682 String fileName = subVals.getContent();
683 File file = new File(fileName);
684 boolean overwrite = ArgParser.getFromSubValArgOrPref(avm,
685 Arg.OVERWRITE, subVals, null, "OVERWRITE_OUTPUT", false);
686 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
687 // otherwise if headless assume false, if not headless use the user
688 // preference with default true.
689 boolean backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS,
691 Platform.isHeadless() ? null : BackupFiles.ENABLED,
692 !Platform.isHeadless());
694 // if backups is not true then --overwrite must be specified
695 if (file.exists() && !(overwrite || backups))
697 Console.error("Won't overwrite file '" + fileName + "' without "
698 + Arg.OVERWRITE.argString() + " or "
699 + Arg.BACKUPS.argString() + " set");
703 String name = af.getName();
704 String format = ArgParser.getValueFromSubValOrArg(avm, av,
705 Arg.FORMAT, subVals);
706 FileFormats ffs = FileFormats.getInstance();
707 List<String> validFormats = ffs.getWritableFormats(false);
709 FileFormatI ff = null;
710 if (format == null && fileName != null)
712 FORMAT: for (String fname : validFormats)
714 FileFormatI tff = ffs.forName(fname);
715 String[] extensions = tff.getExtensions().split(",");
716 for (String ext : extensions)
718 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
721 format = ff.getName();
727 if (ff == null && format != null)
729 ff = ffs.forName(format);
733 StringBuilder validSB = new StringBuilder();
734 for (String f : validFormats)
736 if (validSB.length() > 0)
737 validSB.append(", ");
739 FileFormatI tff = ffs.forName(f);
740 validSB.append(" (");
741 validSB.append(tff.getExtensions());
745 Jalview.exit("No valid format specified for "
746 + Arg.OUTPUT.argString() + ". Valid formats are "
747 + validSB.toString() + ".", 1);
748 // this return really shouldn't happen
752 String savedBackupsPreference = Cache
753 .getDefault(BackupFiles.ENABLED, null);
754 Console.debug("Setting backups to " + backups);
755 Cache.applicationProperties.put(BackupFiles.ENABLED,
756 Boolean.toString(backups));
757 af.saveAlignment(fileName, ff);
758 Console.debug("Returning backups to " + savedBackupsPreference);
759 if (savedBackupsPreference != null)
760 Cache.applicationProperties.put(BackupFiles.ENABLED,
761 savedBackupsPreference);
762 if (af.isSaveAlignmentSuccessful())
764 Console.debug("Written alignment '" + name + "' in "
765 + ff.getName() + " format to " + file);
769 Console.warn("Error writing file " + file + " in " + ff.getName()
778 private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
782 AlignmentI al = af.getCurrentView().getAlignment();
783 if (subId.has("seqid"))
785 return al.findName(subId.get("seqid"));
787 else if (-1 < subId.getIndex()
788 && subId.getIndex() < al.getSequences().size())
790 return al.getSequenceAt(subId.getIndex());
795 // returns the first Arg value intended for the structure structFilename
796 // (in the given AlignFrame from the ArgValuesMap)
797 private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
798 AlignFrame af, String structFilename)
802 for (ArgValue av : avm.getArgValueList(arg))
804 SubVals subVals = av.getSubVals();
805 String structid = subVals.get("structid");
806 String structfile = subVals.get("structfile");
808 // let's find a structure
809 if (structfile == null && structid == null)
811 ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
813 if (likelyStructure != null)
815 SubVals sv = likelyStructure.getSubVals();
816 if (sv != null && sv.has(ArgValues.ID))
818 structid = sv.get(ArgValues.ID);
822 structfile = likelyStructure.getValue();
827 if (structfile == null && structid != null)
829 StructureSelectionManager ssm = StructureSelectionManager
830 .getStructureSelectionManager(Desktop.instance);
833 structfile = ssm.findFileForPDBId(structid);
836 if (structfile != null && structfile.equals(structFilename))