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.BioJsHTMLOutput;
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.structure.StructureImportSettings.TFType;
44 import jalview.structure.StructureSelectionManager;
45 import jalview.util.HttpUtils;
46 import jalview.util.MessageManager;
47 import jalview.util.Platform;
53 private boolean headless;
55 private ArgParser argParser;
57 private Map<String, AlignFrame> afMap;
59 private boolean commandArgsProvided = false;
61 private boolean argsWereParsed = false;
63 public Commands(ArgParser argparser, boolean headless)
65 this(Desktop.instance, argparser, headless);
68 public Commands(Desktop d, ArgParser argparser, boolean h)
70 argParser = argparser;
73 afMap = new HashMap<String, AlignFrame>();
74 if (argparser != null)
76 processArgs(argparser, headless);
80 private boolean processArgs(ArgParser argparser, boolean h)
82 argParser = argparser;
84 boolean theseArgsWereParsed = false;
86 if (argParser != null && argParser.getLinkedIds() != null)
88 for (String id : argParser.getLinkedIds())
90 ArgValuesMap avm = argParser.getLinkedArgs(id);
91 theseArgsWereParsed = true;
92 theseArgsWereParsed &= processLinked(id);
93 boolean processLinkedOkay = theseArgsWereParsed;
94 theseArgsWereParsed &= processImages(id);
95 if (processLinkedOkay)
96 theseArgsWereParsed &= processOutput(id);
99 if (avm.getBoolean(Arg.CLOSE))
101 AlignFrame af = afMap.get(id);
104 af.closeMenuItem_actionPerformed(true);
111 if (argParser.getBool(Arg.QUIT))
113 Jalview.getInstance().quit();
116 // carry on with jalview.bin.Jalview
117 argsWereParsed = theseArgsWereParsed;
118 return argsWereParsed;
121 public boolean commandArgsProvided()
123 return commandArgsProvided;
126 public boolean argsWereParsed()
128 return argsWereParsed;
131 protected boolean processUnlinked(String id)
133 return processLinked(id);
136 protected boolean processLinked(String id)
138 boolean theseArgsWereParsed = false;
139 ArgValuesMap avm = argParser.getLinkedArgs(id);
144 * // script to execute after all loading is completed one way or another String
145 * groovyscript = m.get(Arg.GROOVY) == null ? null :
146 * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
147 * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
148 * DataSourceType protocol = null;
150 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
152 commandArgsProvided = true;
155 boolean first = true;
156 boolean progressBarSet = false;
158 // Combine the APPEND and OPEN files into one list, along with whether it
159 // was APPEND or OPEN
160 List<ArgValue> openAvList = new ArrayList<>();
161 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
162 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
163 // sort avlist based on av.getArgIndex()
164 Collections.sort(openAvList);
165 for (ArgValue av : openAvList)
168 SubVals sv = av.getSubVals();
169 String openFile = av.getValue();
170 if (openFile == null)
173 theseArgsWereParsed = true;
177 if (!headless && desktop != null)
179 desktop.setProgressBar(
180 MessageManager.getString(
181 "status.processing_commandline_args"),
182 progress = System.currentTimeMillis());
183 progressBarSet = true;
187 if (!Platform.isJS())
189 * ignore in JavaScript -- can't just file existence - could load it?
194 if (!HttpUtils.startsWithHttpOrHttps(openFile))
196 if (!(new File(openFile)).exists())
198 Console.warn("Can't find file '" + openFile + "'");
203 DataSourceType protocol = AppletFormatAdapter
204 .checkProtocol(openFile);
206 FileFormatI format = null;
209 format = new IdentifyFile().identify(openFile, protocol);
210 } catch (FileFormatException e1)
212 Console.error("Unknown file format for '" + openFile + "'");
216 // When to open a new AlignFrame
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 boolean wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv,
249 null, "WRAP_ALIGNMENT", false);
250 af.getCurrentView().setWrapAlignment(wrap);
253 String colour = ArgParser.getFromSubValArgOrPref(avm, av,
254 Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
258 af.changeColour_actionPerformed(colour);
261 // change alignment frame title
262 String title = ArgParser.getFromSubValArgOrPref(avm, av,
263 Arg.TITLE, sv, null, null, null);
267 // show secondary structure annotations?
268 boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
269 Arg.SSANNOTATIONS, av.getSubVals(), null,
270 "STRUCT_FROM_PDB", true);
271 if (avm.getBoolean(Arg.SSANNOTATIONS))
273 af.setAnnotationsVisibility(showSSAnnotations, true, false);
275 AlignmentUtils.showOrHideSequenceAnnotations(
276 af.getCurrentView().getAlignment(),
277 Collections.singleton("Secondary Structure"), null,
282 // show temperature factor annotations?
283 if (avm.getBoolean(Arg.NOTEMPFAC))
285 // do this better (annotation types?)
286 List<String> hideThese = new ArrayList<>();
287 hideThese.add("Temperature Factor");
288 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
289 AlignmentUtils.showOrHideSequenceAnnotations(
290 af.getCurrentView().getAlignment(), hideThese, null,
295 * comment out hacky approach up to here and add this line: if
296 * (showTemperatureFactor)
300 if (avm.containsArg(Arg.TEMPFAC_LABEL))
302 AlignmentAnnotation aa = AlignmentUtils
303 .getFirstSequenceAnnotationOfType(
304 af.getCurrentView().getAlignment(),
305 AlignmentAnnotation.LINE_GRAPH);
306 String label = avm.getValue(Arg.TEMPFAC_LABEL);
314 "Could not find annotation to apply tempfac_label '"
321 // store the AlignFrame for this id
324 // is it its own structure file?
325 if (format.isStructureFile())
327 StructureSelectionManager ssm = StructureSelectionManager
328 .getStructureSelectionManager(Desktop.instance);
329 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
330 ssm.computeMapping(false, new SequenceI[] { seq }, null,
331 openFile, DataSourceType.FILE, null, null, null, false);
337 "Opening '" + openFile + "' in existing alignment frame");
338 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
340 : DataSourceType.FILE;
341 FileLoader fileLoader = new FileLoader(!headless);
342 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
346 Console.debug("Command " + Arg.APPEND + " executed successfully!");
349 if (first) // first=true means nothing opened
353 Jalview.exit("Could not open any files in headless mode", 1);
357 Console.warn("No more files to open");
360 if (progressBarSet && desktop != null)
361 desktop.setProgressBar(null, progress);
365 // open the structure (from same PDB file or given PDBfile)
366 if (!avm.getBoolean(Arg.NOSTRUCTURE))
368 AlignFrame af = afMap.get(id);
369 if (avm.containsArg(Arg.STRUCTURE))
371 commandArgsProvided = true;
372 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
374 String val = av.getValue();
375 SubVals subVals = av.getSubVals();
376 SequenceI seq = getSpecifiedSequence(af, subVals);
379 // Could not find sequence from subId, let's assume the first
380 // sequence in the alignframe
381 AlignmentI al = af.getCurrentView().getAlignment();
382 seq = al.getSequenceAt(0);
387 Console.warn("Could not find sequence for argument "
388 + Arg.STRUCTURE.argString() + "=" + val);
389 // you probably want to continue here, not break
393 File structureFile = null;
394 if (subVals.getContent() != null
395 && subVals.getContent().length() != 0)
397 structureFile = new File(subVals.getContent());
398 Console.debug("Using structure file (from argument) '"
399 + structureFile.getAbsolutePath() + "'");
403 * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
404 * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
405 * selectedSequence, true, Desktop.instance);
407 * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
408 * SequenceI[] { selectedSequence });
411 /* THIS DOESN'T WORK */
412 else if (seq.getAllPDBEntries() != null
413 && seq.getAllPDBEntries().size() > 0)
415 structureFile = new File(
416 seq.getAllPDBEntries().elementAt(0).getFile());
417 Console.debug("Using structure file (from sequence) '"
418 + structureFile.getAbsolutePath() + "'");
421 if (structureFile == null)
423 Console.warn("Not provided structure file with '" + val + "'");
427 if (!structureFile.exists())
429 Console.warn("Structure file '"
430 + structureFile.getAbsoluteFile() + "' not found.");
434 Console.debug("Using structure file "
435 + structureFile.getAbsolutePath());
437 // ##### Does this need to happen? Follow
438 // openStructureFileForSequence() below
440 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
441 .associatePdbWithSeq(structureFile.getAbsolutePath(),
442 DataSourceType.FILE, seq, true, Desktop.instance);
445 // open structure view
446 AlignmentPanel ap = af.alignPanel;
449 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
450 StructureViewer.ViewerType.JMOL.toString());
453 String structureFilepath = structureFile.getAbsolutePath();
455 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
456 String paeFilepath = subVals.getWithSubstitutions(argParser, id,
458 String paeLabel = subVals.get("paelabel");
459 ArgValue paeAv = getArgAssociatedWithStructure(Arg.PAEMATRIX, avm,
460 af, structureFilepath);
461 if (paeFilepath == null && paeAv != null)
463 SubVals sv = paeAv.getSubVals();
464 File paeFile = new File(sv.getContent());
466 paeLabel = sv.get("label");
469 paeFilepath = paeFile.getCanonicalPath();
470 } catch (IOException e)
472 paeFilepath = paeFile.getAbsolutePath();
473 Console.warn("Problem with the PAE file path: '"
474 + paeFile.getPath() + "'");
478 // showing annotations from structure file or not
479 boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
480 Arg.SSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
483 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
484 // reference annotations
485 String tftString = subVals.get("tempfac");
486 TFType tft = avm.getBoolean(Arg.NOTEMPFAC) ? null
488 ArgValue tftAv = getArgAssociatedWithStructure(Arg.TEMPFAC, avm,
489 af, structureFilepath);
490 if (tftString == null && tftAv != null)
492 tftString = tftAv.getSubVals().getContent();
494 if (tftString != null)
496 // get kind of temperature factor annotation
499 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
500 Console.debug("Obtained Temperature Factor type of '" + tft
501 + "' for structure '" + structureFilepath + "'");
502 } catch (IllegalArgumentException e)
504 // Just an error message!
505 StringBuilder sb = new StringBuilder().append("Cannot set ")
506 .append(Arg.TEMPFAC.argString()).append(" to '")
508 .append("', ignoring. Valid values are: ");
509 Iterator<TFType> it = Arrays.stream(TFType.values())
513 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
517 Console.warn(sb.toString());
521 String sViewer = ArgParser.getFromSubValArgOrPref(avm,
522 Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals,
523 "viewer", null, "jmol");
524 ViewerType viewerType = null;
525 if (!"none".equals(sViewer))
527 for (ViewerType v : EnumSet.allOf(ViewerType.class))
529 String name = v.name().toLowerCase(Locale.ROOT)
530 .replaceAll(" ", "");
531 if (sViewer.equals(name))
539 boolean addTempFac = tft != null
540 || Cache.getDefault("ADD_TEMPFACT_ANN", false);
542 // TODO use ssFromStructure
543 StructureChooser.openStructureFileForSequence(null, null, ap, seq,
544 false, structureFilepath, tft, paeFilepath, false,
545 ssFromStructure, false, viewerType);
551 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
554 AlignFrame af = afMap.get(id);
555 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
556 .findAnnotation(PDBChain.class.getName().toString()))
558 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
559 af.alignPanel.av.getGlobalColourScheme(), 0);
560 acg.setSeqAssociated(true);
561 af.changeColour(acg);
562 Console.info("Changed colour " + acg.toString());
567 return theseArgsWereParsed;
570 protected boolean processImages(String id)
572 ArgValuesMap avm = argParser.getLinkedArgs(id);
573 AlignFrame af = afMap.get(id);
577 Console.warn("Did not have an alignment window for id=" + id);
581 if (avm.containsArg(Arg.IMAGE))
583 for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
585 String val = av.getValue();
586 SubVals subVal = av.getSubVals();
587 String type = "png"; // default
588 String fileName = subVal.getContent();
589 File file = new File(fileName);
590 String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
591 Arg.RENDERER, subVal);
592 if (renderer == null)
594 type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
595 if (type == null && fileName != null)
597 for (String ext : new String[] { "svg", "png", "html", "eps" })
599 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
605 // for moment we disable JSON export
606 Cache.setPropsAreReadOnly(true);
607 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
613 Console.debug("Outputting type '" + type + "' to " + fileName);
614 af.createSVG(file, renderer);
618 Console.debug("Outputting type '" + type + "' to " + fileName);
623 Console.debug("Outputting type '" + type + "' to " + fileName);
624 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
625 htmlSVG.exportHTML(fileName, renderer);
631 BioJsHTMLOutput.refreshVersionInfo(
632 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
633 } catch (URISyntaxException e)
637 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
638 bjs.exportHTML(fileName);
639 Console.debug("Creating BioJS MSA Viwer HTML file: " + fileName);
643 Console.warn(Arg.IMAGE.argString() + " type '" + type
644 + "' not known. Ignoring");
652 protected boolean processOutput(String id)
654 ArgValuesMap avm = argParser.getLinkedArgs(id);
655 AlignFrame af = afMap.get(id);
659 Console.warn("Did not have an alignment window for id=" + id);
663 if (avm.containsArg(Arg.OUTPUT))
665 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
667 String val = av.getValue();
668 SubVals subVal = av.getSubVals();
669 String type = null; // default
670 String fileName = subVal.getContent();
671 File file = new File(fileName);
677 private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
681 AlignmentI al = af.getCurrentView().getAlignment();
682 if (subId.has("seqid"))
684 return al.findName(subId.get("seqid"));
686 else if (-1 < subId.getIndex()
687 && subId.getIndex() < al.getSequences().size())
689 return al.getSequenceAt(subId.getIndex());
694 // returns the first Arg value intended for the structure structFilename
695 // (in the given AlignFrame from the ArgValuesMap)
696 private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
697 AlignFrame af, String structFilename)
701 for (ArgValue av : avm.getArgValueList(arg))
703 SubVals subVals = av.getSubVals();
704 String structid = subVals.get("structid");
705 String structfile = subVals.get("structfile");
707 // let's find a structure
708 if (structfile == null && structid == null)
710 ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
712 if (likelyStructure != null)
714 SubVals sv = likelyStructure.getSubVals();
715 if (sv != null && sv.has(ArgValues.ID))
717 structid = sv.get(ArgValues.ID);
721 structfile = likelyStructure.getValue();
726 if (structfile == null && structid != null)
728 StructureSelectionManager ssm = StructureSelectionManager
729 .getStructureSelectionManager(Desktop.instance);
732 structfile = ssm.findFileForPDBId(structid);
735 if (structfile != null && structfile.equals(structFilename))