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 theseArgsWereParsed &= processImages(id);
96 if (avm.getBoolean(Arg.CLOSE))
98 AlignFrame af = afMap.get(id);
101 af.closeMenuItem_actionPerformed(true);
108 if (argParser.getBool(Arg.QUIT))
110 Jalview.getInstance().quit();
113 // carry on with jalview.bin.Jalview
114 argsWereParsed = theseArgsWereParsed;
115 return argsWereParsed;
118 public boolean commandArgsProvided()
120 return commandArgsProvided;
123 public boolean argsWereParsed()
125 return argsWereParsed;
128 protected boolean processUnlinked(String id)
130 return processLinked(id);
133 protected boolean processLinked(String id)
135 boolean theseArgsWereParsed = false;
136 ArgValuesMap avm = argParser.getLinkedArgs(id);
141 * // script to execute after all loading is completed one way or another String
142 * groovyscript = m.get(Arg.GROOVY) == null ? null :
143 * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
144 * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
145 * DataSourceType protocol = null;
147 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
149 commandArgsProvided = true;
152 boolean first = true;
153 boolean progressBarSet = false;
155 // Combine the APPEND and OPEN files into one list, along with whether it
156 // was APPEND or OPEN
157 List<ArgValue> openAvList = new ArrayList<>();
158 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
159 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
160 // sort avlist based on av.getArgIndex()
161 Collections.sort(openAvList);
162 for (ArgValue av : openAvList)
165 SubVals sv = av.getSubVals();
166 String openFile = av.getValue();
167 if (openFile == null)
170 theseArgsWereParsed = true;
174 if (!headless && desktop != null)
176 desktop.setProgressBar(
177 MessageManager.getString(
178 "status.processing_commandline_args"),
179 progress = System.currentTimeMillis());
180 progressBarSet = true;
184 if (!Platform.isJS())
186 * ignore in JavaScript -- can't just file existence - could load it?
191 if (!HttpUtils.startsWithHttpOrHttps(openFile))
193 if (!(new File(openFile)).exists())
195 Console.warn("Can't find file '" + openFile + "'");
200 DataSourceType protocol = AppletFormatAdapter
201 .checkProtocol(openFile);
203 FileFormatI format = null;
206 format = new IdentifyFile().identify(openFile, protocol);
207 } catch (FileFormatException e1)
209 Console.error("Unknown file format for '" + openFile + "'");
213 // When to open a new AlignFrame
214 if (af == null || "true".equals(av.getSubVal("new"))
215 || a == Arg.OPEN || format == FileFormat.Jalview)
218 * this approach isn't working yet // get default annotations before opening
219 * AlignFrame if (m.get(Arg.SSANNOTATIONS) != null) {
220 * Console.debug("##### SSANNOTATIONS=" + m.get(Arg.SSANNOTATIONS).getBoolean());
221 * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
222 * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
223 * (m.get(Arg.SSANNOTATIONS) != null) ? m.get(Arg.SSANNOTATIONS).getBoolean() :
224 * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
225 * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
226 * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
227 * StructureSelectionManager ssm = StructureSelectionManager
228 * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
229 * ssm.setAddTempFacAnnot(showTemperatureFactor);
230 * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
234 "Opening '" + openFile + "' in new alignment frame");
235 FileLoader fileLoader = new FileLoader(!headless);
237 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
239 boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
240 Arg.ANNOTATIONS, av.getSubVals(), null,
241 "SHOW_ANNOTATIONS", true);
242 af.setAnnotationsVisibility(showAnnotations, false, true);
245 boolean wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv,
246 null, "WRAP_ALIGNMENT", false);
247 af.getCurrentView().setWrapAlignment(wrap);
250 String colour = ArgParser.getFromSubValArgOrPref(avm, av,
251 Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
255 af.changeColour_actionPerformed(colour);
258 // change alignment frame title
259 String title = ArgParser.getFromSubValArgOrPref(avm, av,
260 Arg.TITLE, sv, null, null, null);
264 // show secondary structure annotations?
265 boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
266 Arg.SSANNOTATIONS, av.getSubVals(), null,
267 "STRUCT_FROM_PDB", true);
268 if (avm.getBoolean(Arg.SSANNOTATIONS))
270 af.setAnnotationsVisibility(showSSAnnotations, true, false);
272 AlignmentUtils.showOrHideSequenceAnnotations(
273 af.getCurrentView().getAlignment(),
274 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)
297 if (avm.containsArg(Arg.TEMPFAC_LABEL))
299 AlignmentAnnotation aa = AlignmentUtils
300 .getFirstSequenceAnnotationOfType(
301 af.getCurrentView().getAlignment(),
302 AlignmentAnnotation.LINE_GRAPH);
303 String label = avm.getValue(Arg.TEMPFAC_LABEL);
311 "Could not find annotation to apply tempfac_label '"
318 // store the AlignFrame for this id
321 // is it its own structure file?
322 if (format.isStructureFile())
324 StructureSelectionManager ssm = StructureSelectionManager
325 .getStructureSelectionManager(Desktop.instance);
326 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
327 ssm.computeMapping(false, new SequenceI[] { seq }, null,
328 openFile, DataSourceType.FILE, null, null, null, false);
334 "Opening '" + openFile + "' in existing alignment frame");
335 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
337 : DataSourceType.FILE;
338 FileLoader fileLoader = new FileLoader(!headless);
339 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
343 Console.debug("Command " + Arg.APPEND + " executed successfully!");
346 if (first) // first=true means nothing opened
350 Jalview.exit("Could not open any files in headless mode", 1);
354 Console.warn("No more files to open");
357 if (progressBarSet && desktop != null)
358 desktop.setProgressBar(null, progress);
362 // open the structure (from same PDB file or given PDBfile)
363 if (!avm.getBoolean(Arg.NOSTRUCTURE))
365 AlignFrame af = afMap.get(id);
366 if (avm.containsArg(Arg.STRUCTURE))
368 commandArgsProvided = true;
369 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
371 String val = av.getValue();
372 SubVals subVals = av.getSubVals();
373 SequenceI seq = getSpecifiedSequence(af, subVals);
376 // Could not find sequence from subId, let's assume the first
377 // sequence in the alignframe
378 AlignmentI al = af.getCurrentView().getAlignment();
379 seq = al.getSequenceAt(0);
384 Console.warn("Could not find sequence for argument "
385 + Arg.STRUCTURE.argString() + "=" + val);
386 // you probably want to continue here, not break
390 File structureFile = null;
391 if (subVals.getContent() != null
392 && subVals.getContent().length() != 0)
394 structureFile = new File(subVals.getContent());
395 Console.debug("Using structure file (from argument) '"
396 + structureFile.getAbsolutePath() + "'");
400 * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
401 * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
402 * selectedSequence, true, Desktop.instance);
404 * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
405 * SequenceI[] { selectedSequence });
408 /* THIS DOESN'T WORK */
409 else if (seq.getAllPDBEntries() != null
410 && seq.getAllPDBEntries().size() > 0)
412 structureFile = new File(
413 seq.getAllPDBEntries().elementAt(0).getFile());
414 Console.debug("Using structure file (from sequence) '"
415 + structureFile.getAbsolutePath() + "'");
418 if (structureFile == null)
420 Console.warn("Not provided structure file with '" + val + "'");
424 if (!structureFile.exists())
426 Console.warn("Structure file '"
427 + structureFile.getAbsoluteFile() + "' not found.");
431 Console.debug("Using structure file "
432 + structureFile.getAbsolutePath());
434 // ##### Does this need to happen? Follow
435 // openStructureFileForSequence() below
437 PDBEntry fileEntry = new AssociatePdbFileWithSeq()
438 .associatePdbWithSeq(structureFile.getAbsolutePath(),
439 DataSourceType.FILE, seq, true, Desktop.instance);
442 // open structure view
443 AlignmentPanel ap = af.alignPanel;
446 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
447 StructureViewer.ViewerType.JMOL.toString());
450 String structureFilepath = structureFile.getAbsolutePath();
452 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
453 String paeFilepath = subVals.getWithSubstitutions(argParser, id,
455 String paeLabel = subVals.get("paelabel");
456 ArgValue paeAv = getArgAssociatedWithStructure(Arg.PAEMATRIX, avm,
457 af, structureFilepath);
458 if (paeFilepath == null && paeAv != null)
460 SubVals sv = paeAv.getSubVals();
461 File paeFile = new File(sv.getContent());
463 paeLabel = sv.get("label");
466 paeFilepath = paeFile.getCanonicalPath();
467 } catch (IOException e)
469 paeFilepath = paeFile.getAbsolutePath();
470 Console.warn("Problem with the PAE file path: '"
471 + paeFile.getPath() + "'");
475 // showing annotations from structure file or not
476 boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
477 Arg.SSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
480 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
481 // reference annotations
482 String tftString = subVals.get("tempfac");
483 TFType tft = avm.getBoolean(Arg.NOTEMPFAC) ? null
485 ArgValue tftAv = getArgAssociatedWithStructure(Arg.TEMPFAC, avm,
486 af, structureFilepath);
487 if (tftString == null && tftAv != null)
489 tftString = tftAv.getSubVals().getContent();
491 if (tftString != null)
493 // get kind of temperature factor annotation
496 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
497 Console.debug("Obtained Temperature Factor type of '" + tft
498 + "' for structure '" + structureFilepath + "'");
499 } catch (IllegalArgumentException e)
501 // Just an error message!
502 StringBuilder sb = new StringBuilder().append("Cannot set ")
503 .append(Arg.TEMPFAC.argString()).append(" to '")
505 .append("', ignoring. Valid values are: ");
506 Iterator<TFType> it = Arrays.stream(TFType.values())
510 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
514 Console.warn(sb.toString());
518 String sViewer = ArgParser.getFromSubValArgOrPref(avm,
519 Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals,
520 "viewer", null, "jmol");
521 ViewerType viewerType = null;
522 if (!"none".equals(sViewer))
524 for (ViewerType v : EnumSet.allOf(ViewerType.class))
526 String name = v.name().toLowerCase(Locale.ROOT)
527 .replaceAll(" ", "");
528 if (sViewer.equals(name))
536 boolean addTempFac = tft != null
537 || Cache.getDefault("ADD_TEMPFACT_ANN", false);
539 // TODO use ssFromStructure
540 StructureChooser.openStructureFileForSequence(null, null, ap, seq,
541 false, structureFilepath, tft, paeFilepath, false,
542 ssFromStructure, false, viewerType);
548 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
551 AlignFrame af = afMap.get(id);
552 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
553 .findAnnotation(PDBChain.class.getName().toString()))
555 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
556 af.alignPanel.av.getGlobalColourScheme(), 0);
557 acg.setSeqAssociated(true);
558 af.changeColour(acg);
559 Console.info("Changed colour " + acg.toString());
564 return theseArgsWereParsed;
567 protected boolean processImages(String id)
569 ArgValuesMap avm = argParser.getLinkedArgs(id);
570 AlignFrame af = afMap.get(id);
574 Console.warn("Did not have an alignment window for id=" + id);
578 if (avm.containsArg(Arg.IMAGE))
580 for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
582 String val = av.getValue();
583 SubVals subVal = av.getSubVals();
584 String type = "png"; // default
585 String fileName = subVal.getContent();
586 File file = new File(fileName);
587 String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
588 Arg.RENDERER, subVal);
589 if (renderer == null)
591 type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
592 if (type == null && fileName != null)
594 for (String ext : new String[] { "svg", "png", "html", "eps" })
596 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
602 // for moment we disable JSON export
603 Cache.setPropsAreReadOnly(true);
604 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
610 Console.debug("Outputting type '" + type + "' to " + fileName);
611 af.createSVG(file, renderer);
615 Console.debug("Outputting type '" + type + "' to " + fileName);
620 Console.debug("Outputting type '" + type + "' to " + fileName);
621 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
622 htmlSVG.exportHTML(fileName, renderer);
628 BioJsHTMLOutput.refreshVersionInfo(
629 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
630 } catch (URISyntaxException e)
634 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
635 bjs.exportHTML(fileName);
636 Console.debug("Creating BioJS MSA Viwer HTML file: " + fileName);
640 Console.warn(Arg.IMAGE.argString() + " type '" + type
641 + "' not known. Ignoring");
649 private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
653 AlignmentI al = af.getCurrentView().getAlignment();
654 if (subId.has("seqid"))
656 return al.findName(subId.get("seqid"));
658 else if (-1 < subId.getIndex()
659 && subId.getIndex() < al.getSequences().size())
661 return al.getSequenceAt(subId.getIndex());
666 // returns the first Arg value intended for the structure structFilename
667 // (in the given AlignFrame from the ArgValuesMap)
668 private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
669 AlignFrame af, String structFilename)
673 for (ArgValue av : avm.getArgValueList(arg))
675 SubVals subVals = av.getSubVals();
676 String structid = subVals.get("structid");
677 String structfile = subVals.get("structfile");
679 // let's find a structure
680 if (structfile == null && structid == null)
682 ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
684 if (likelyStructure != null)
686 SubVals sv = likelyStructure.getSubVals();
687 if (sv != null && sv.has(ArgValues.ID))
689 structid = sv.get(ArgValues.ID);
693 structfile = likelyStructure.getValue();
698 if (structfile == null && structid != null)
700 StructureSelectionManager ssm = StructureSelectionManager
701 .getStructureSelectionManager(Desktop.instance);
704 structfile = ssm.findFileForPDBId(structid);
707 if (structfile != null && structfile.equals(structFilename))