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 // When to open a new AlignFrame
218 if (af == null || "true".equals(av.getSubVal("new"))
219 || a == Arg.OPEN || format == FileFormat.Jalview)
222 * this approach isn't working yet // get default annotations before opening
223 * AlignFrame if (m.get(Arg.SSANNOTATIONS) != null) {
224 * Console.debug("##### SSANNOTATIONS=" + m.get(Arg.SSANNOTATIONS).getBoolean());
225 * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
226 * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
227 * (m.get(Arg.SSANNOTATIONS) != null) ? m.get(Arg.SSANNOTATIONS).getBoolean() :
228 * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
229 * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
230 * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
231 * StructureSelectionManager ssm = StructureSelectionManager
232 * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
233 * ssm.setAddTempFacAnnot(showTemperatureFactor);
234 * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
238 "Opening '" + openFile + "' in new alignment frame");
239 FileLoader fileLoader = new FileLoader(!headless);
241 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
243 boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
244 Arg.ANNOTATIONS, av.getSubVals(), null,
245 "SHOW_ANNOTATIONS", true);
246 af.setAnnotationsVisibility(showAnnotations, false, true);
249 if (avm.getBoolean(Arg.WRAP))
251 af.getCurrentView().setWrapAlignment(true);
255 if (avm.containsArg(Arg.COLOUR))
257 af.changeColour_actionPerformed(avm.getValue(Arg.COLOUR));
260 // change alignment frame title
261 if (avm.containsArg(Arg.TITLE))
262 af.setTitle(avm.getValue(Arg.TITLE));
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.linkedArgs(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 if (subVal.has("type"))
589 type = subVal.get("type");
591 else if (fileName != null)
593 for (String ext : new String[] { "svg", "png", "html" })
595 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
601 // for moment we disable JSON export
602 Cache.setPropsAreReadOnly(true);
603 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
608 Console.debug("Outputting type '" + type + "' to " + fileName);
612 Console.debug("Outputting type '" + type + "' to " + fileName);
616 Console.debug("Outputting type '" + type + "' to " + fileName);
617 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
618 htmlSVG.exportHTML(fileName);
621 Console.warn(Arg.IMAGE.argString() + " type '" + type
622 + "' not known. Ignoring");
630 private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
634 AlignmentI al = af.getCurrentView().getAlignment();
635 if (subId.has("seqid"))
637 return al.findName(subId.get("seqid"));
639 else if (-1 < subId.getIndex()
640 && subId.getIndex() < al.getSequences().size())
642 return al.getSequenceAt(subId.getIndex());
647 // returns the first Arg value intended for the structure structFilename
648 // (in the given AlignFrame from the ArgValuesMap)
649 private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
650 AlignFrame af, String structFilename)
654 for (ArgValue av : avm.getArgValueList(arg))
656 SubVals subVals = av.getSubVals();
657 String structid = subVals.get("structid");
658 String structfile = subVals.get("structfile");
660 // let's find a structure
661 if (structfile == null && structid == null)
663 ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
665 if (likelyStructure != null)
667 SubVals sv = likelyStructure.getSubVals();
668 if (sv != null && sv.has(ArgValues.ID))
670 structid = sv.get(ArgValues.ID);
674 structfile = likelyStructure.getValue();
676 "##### Comparing closest previous structure argument '"
682 if (structfile == null && structid != null)
684 StructureSelectionManager ssm = StructureSelectionManager
685 .getStructureSelectionManager(Desktop.instance);
688 structfile = ssm.findFileForPDBId(structid);
691 if (structfile != null && structfile.equals(structFilename))