2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import java.awt.Color;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.net.URISyntaxException;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collections;
31 import java.util.HashMap;
32 import java.util.Iterator;
33 import java.util.List;
34 import java.util.Locale;
37 import javax.swing.SwingUtilities;
39 import jalview.analysis.AlignmentUtils;
40 import jalview.api.structures.JalviewStructureDisplayI;
41 import jalview.bin.Jalview.ExitCode;
42 import jalview.bin.argparser.Arg;
43 import jalview.bin.argparser.ArgParser;
44 import jalview.bin.argparser.ArgValue;
45 import jalview.bin.argparser.ArgValuesMap;
46 import jalview.bin.argparser.SubVals;
47 import jalview.datamodel.AlignmentI;
48 import jalview.datamodel.SequenceI;
49 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
50 import jalview.gui.AlignFrame;
51 import jalview.gui.AlignmentPanel;
52 import jalview.gui.AppJmol;
53 import jalview.gui.Desktop;
54 import jalview.gui.Preferences;
55 import jalview.gui.StructureChooser;
56 import jalview.gui.StructureViewer;
57 import jalview.gui.StructureViewer.ViewerType;
58 import jalview.io.AppletFormatAdapter;
59 import jalview.io.BackupFiles;
60 import jalview.io.BioJsHTMLOutput;
61 import jalview.io.DataSourceType;
62 import jalview.io.FileFormat;
63 import jalview.io.FileFormatException;
64 import jalview.io.FileFormatI;
65 import jalview.io.FileFormats;
66 import jalview.io.FileLoader;
67 import jalview.io.HtmlSvgOutput;
68 import jalview.io.IdentifyFile;
69 import jalview.io.NewickFile;
70 import jalview.io.exceptions.ImageOutputException;
71 import jalview.schemes.ColourSchemeI;
72 import jalview.schemes.ColourSchemeProperty;
73 import jalview.structure.StructureCommandI;
74 import jalview.structure.StructureImportSettings.TFType;
75 import jalview.structure.StructureSelectionManager;
76 import jalview.util.ColorUtils;
77 import jalview.util.FileUtils;
78 import jalview.util.HttpUtils;
79 import jalview.util.ImageMaker;
80 import jalview.util.ImageMaker.TYPE;
81 import jalview.util.MessageManager;
82 import jalview.util.Platform;
83 import jalview.util.StringUtils;
84 import jalview.util.imagemaker.BitmapImageSizing;
90 private boolean headless;
92 private ArgParser argParser;
94 private Map<String, AlignFrame> afMap;
96 private Map<String, List<StructureViewer>> svMap;
98 private boolean commandArgsProvided = false;
100 private boolean argsWereParsed = false;
102 private List<String> errors = new ArrayList<>();
104 public Commands(ArgParser argparser, boolean headless)
106 this(Desktop.instance, argparser, headless);
109 public Commands(Desktop d, ArgParser argparser, boolean h)
111 argParser = argparser;
114 afMap = new HashMap<>();
117 protected boolean processArgs()
119 if (argParser == null)
124 boolean theseArgsWereParsed = false;
126 if (argParser != null && argParser.getLinkedIds() != null)
128 for (String id : argParser.getLinkedIds())
130 ArgValuesMap avm = argParser.getLinkedArgs(id);
131 theseArgsWereParsed = true;
132 boolean processLinkedOkay = processLinked(id);
133 theseArgsWereParsed &= processLinkedOkay;
135 processGroovyScript(id);
137 // wait around until alignFrame isn't busy
138 AlignFrame af = afMap.get(id);
139 while (af != null && af.getViewport().isCalcInProgress())
144 } catch (Exception q)
150 theseArgsWereParsed &= processImages(id);
152 if (processLinkedOkay)
154 theseArgsWereParsed &= processOutput(id);
158 if (avm.getBoolean(Arg.CLOSE))
163 af.closeMenuItem_actionPerformed(true);
171 // report errors - if any
172 String errorsRaised = errorsToString();
173 if (errorsRaised.trim().length() > 0)
176 "The following errors and warnings occurred whilst processing files:\n"
179 // gui errors reported in Jalview
181 if (argParser.getBoolean(Arg.QUIT))
183 Jalview.exit("Exiting due to " + Arg.QUIT.argString() + " argument.",
187 // carry on with jalview.bin.Jalview
188 argsWereParsed = theseArgsWereParsed;
189 return argsWereParsed;
192 public boolean commandArgsProvided()
194 return commandArgsProvided;
197 public boolean argsWereParsed()
199 return argsWereParsed;
202 protected boolean processLinked(String id)
204 boolean theseArgsWereParsed = false;
205 ArgValuesMap avm = argParser.getLinkedArgs(id);
211 Boolean isError = Boolean.valueOf(false);
213 // set wrap, showSSAnnotations, showAnnotations and hideTFrows scope here so
214 // it can be applied after structures are opened
215 boolean wrap = false;
216 boolean showSSAnnotations = false;
217 boolean showAnnotations = false;
218 boolean hideTFrows = false;
219 AlignFrame af = null;
221 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
223 commandArgsProvided = true;
224 final long progress = System.currentTimeMillis();
226 boolean first = true;
227 boolean progressBarSet = false;
228 // Combine the APPEND and OPEN files into one list, along with whether it
229 // was APPEND or OPEN
230 List<ArgValue> openAvList = new ArrayList<>();
231 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
232 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
233 // sort avlist based on av.getArgIndex()
234 Collections.sort(openAvList);
235 for (ArgValue av : openAvList)
238 SubVals sv = av.getSubVals();
239 String openFile0 = av.getValue();
240 String openFile = HttpUtils.equivalentJalviewUrl(openFile0);
241 if (openFile == null)
244 theseArgsWereParsed = true;
248 if (!headless && desktop != null)
250 SwingUtilities.invokeLater(new Runnable()
255 desktop.setProgressBar(
256 MessageManager.getString(
257 "status.processing_commandline_args"),
262 progressBarSet = true;
266 if (!Platform.isJS())
268 * ignore in JavaScript -- can't just file existence - could load it?
273 if (!HttpUtils.isPlausibleUri(openFile))
275 if (!(new File(openFile)).exists())
277 addError("Can't find file '" + openFile + "'");
284 DataSourceType protocol = AppletFormatAdapter
285 .checkProtocol(openFile);
287 FileFormatI format = null;
290 format = new IdentifyFile().identify(openFile, protocol);
291 } catch (FileNotFoundException e0)
293 addError((protocol == DataSourceType.URL ? "File at URL" : "File")
294 + " '" + openFile + "' not found");
297 } catch (FileFormatException e1)
299 addError("Unknown file format for '" + openFile + "'");
305 // When to open a new AlignFrame
306 if (af == null || "true".equals(av.getSubVal("new"))
307 || a == Arg.OPEN || format == FileFormat.Jalview)
311 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
316 "Opening '" + openFile + "' in new alignment frame");
317 FileLoader fileLoader = new FileLoader(!headless);
318 boolean xception = false;
321 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
323 if (!openFile.equals(openFile0))
325 af.setTitle(openFile0);
327 } catch (Throwable thr)
330 addError("Couldn't open '" + openFile + "' as " + format + " "
331 + thr.getLocalizedMessage()
332 + " (Enable debug for full stack trace)");
334 Console.debug("Exception when opening '" + openFile + "'", thr);
337 if (af == null && !xception)
339 addInfo("Ignoring '" + openFile
340 + "' - no alignment data found.");
346 String colour = null;
347 if (avm.containsArg(Arg.COLOUR)
348 || !(format == FileFormat.Jalview))
350 colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv, null,
351 "DEFAULT_COLOUR_PROT", null);
355 this.colourAlignFrame(af, colour);
358 // Change alignment frame title
359 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
364 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
368 String featuresfile = avm.getValueFromSubValOrArg(av,
370 if (featuresfile != null)
372 af.parseFeaturesFile(featuresfile,
373 AppletFormatAdapter.checkProtocol(featuresfile));
374 Jalview.testoutput(argParser, Arg.FEATURES,
375 "examples/testdata/plantfdx.features", featuresfile);
378 // Add annotations from file
379 String annotationsfile = avm.getValueFromSubValOrArg(av,
380 Arg.ANNOTATIONS, sv);
381 if (annotationsfile != null)
383 af.loadJalviewDataFile(annotationsfile, null, null, null);
384 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
385 "examples/testdata/plantfdx.annotations",
389 // Set or clear the sortbytree flag
390 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
394 af.getViewport().setSortByTree(true);
395 Jalview.testoutput(argParser, Arg.SORTBYTREE);
398 // Load tree from file
399 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
400 if (treefile != null)
404 NewickFile nf = new NewickFile(treefile,
405 AppletFormatAdapter.checkProtocol(treefile));
406 af.getViewport().setCurrentTree(
407 af.showNewickTree(nf, treefile).getTree());
408 Jalview.testoutput(argParser, Arg.TREE,
409 "examples/testdata/uniref50_test_tree", treefile);
410 } catch (IOException e)
412 addError("Couldn't add tree " + treefile, e);
417 // Show secondary structure annotations?
418 showSSAnnotations = avm.getFromSubValArgOrPref(
419 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
420 "STRUCT_FROM_PDB", true);
421 // Show sequence annotations?
422 showAnnotations = avm.getFromSubValArgOrPref(Arg.SHOWANNOTATIONS,
423 av.getSubVals(), null, "SHOW_ANNOTATIONS", true);
424 // hide the Temperature Factor row?
425 hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
427 // showSSAnnotations, showAnnotations, hideTFrows used after opening
430 // wrap alignment? do this last for formatting reasons
431 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
432 "WRAP_ALIGNMENT", false);
433 // af.setWrapFormat(wrap) is applied after structures are opened for
434 // annotation reasons
436 // store the AlignFrame for this id
439 // is it its own structure file?
440 if (format.isStructureFile())
442 StructureSelectionManager ssm = StructureSelectionManager
443 .getStructureSelectionManager(Desktop.instance);
444 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
445 ssm.computeMapping(false, new SequenceI[] { seq }, null,
446 openFile, DataSourceType.FILE, null, null, null, false);
452 "Opening '" + openFile + "' in existing alignment frame");
454 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
456 : DataSourceType.FILE;
458 FileLoader fileLoader = new FileLoader(!headless);
459 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
463 Console.debug("Command " + Arg.APPEND + " executed successfully!");
466 if (first) // first=true means nothing opened
470 Jalview.exit("Could not open any files in headless mode",
475 Console.info("No more files to open");
478 if (progressBarSet && desktop != null)
479 desktop.setProgressBar(null, progress);
483 // open the structure (from same PDB file or given PDBfile)
484 if (!avm.getBoolean(Arg.NOSTRUCTURE))
490 if (avm.containsArg(Arg.STRUCTURE))
492 commandArgsProvided = true;
493 for (ArgValue structureAv : avm.getArgValueList(Arg.STRUCTURE))
495 argParser.setStructureFilename(null);
496 String val = structureAv.getValue();
497 SubVals subVals = structureAv.getSubVals();
498 int argIndex = structureAv.getArgIndex();
499 SequenceI seq = getSpecifiedSequence(af, avm, structureAv);
502 // Could not find sequence from subId, let's assume the first
503 // sequence in the alignframe
504 AlignmentI al = af.getCurrentView().getAlignment();
505 seq = al.getSequenceAt(0);
510 addWarn("Could not find sequence for argument "
511 + Arg.STRUCTURE.argString() + "=" + val);
514 String structureFilename = null;
515 File structureFile = null;
516 if (subVals.getContent() != null
517 && subVals.getContent().length() != 0)
519 structureFilename = subVals.getContent();
520 Console.debug("Using structure file (from argument) '"
521 + structureFilename + "'");
522 structureFile = new File(structureFilename);
524 /* THIS DOESN'T WORK */
525 else if (seq.getAllPDBEntries() != null
526 && seq.getAllPDBEntries().size() > 0)
528 structureFile = new File(
529 seq.getAllPDBEntries().elementAt(0).getFile());
530 if (structureFile != null)
532 Console.debug("Using structure file (from sequence) '"
533 + structureFile.getAbsolutePath() + "'");
535 structureFilename = structureFile.getAbsolutePath();
538 if (structureFilename == null || structureFile == null)
540 addWarn("Not provided structure file with '" + val + "'");
544 if (!structureFile.exists())
546 addWarn("Structure file '" + structureFile.getAbsoluteFile()
551 Console.debug("Using structure file "
552 + structureFile.getAbsolutePath());
554 argParser.setStructureFilename(structureFilename);
556 // open structure view
557 AlignmentPanel ap = af.alignPanel;
560 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
561 StructureViewer.ViewerType.JMOL.toString());
564 String structureFilepath = structureFile.getAbsolutePath();
566 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
567 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
568 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER,
569 structureAv, subVals, null, null, null);
570 if (paeFilepath != null)
572 File paeFile = new File(paeFilepath);
576 paeFilepath = paeFile.getCanonicalPath();
577 } catch (IOException e)
579 paeFilepath = paeFile.getAbsolutePath();
580 addWarn("Problem with the PAE file path: '"
581 + paeFile.getPath() + "'");
585 // showing annotations from structure file or not
586 boolean ssFromStructure = avm.getFromSubValArgOrPref(
587 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
590 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
591 // reference annotations
592 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
593 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER,
594 structureAv, subVals, null, null, null);
595 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
596 subVals, null, "ADD_TEMPFACT_ANN", false, true);
597 TFType tft = notempfac ? null : TFType.DEFAULT;
598 if (tftString != null && !notempfac)
600 // get kind of temperature factor annotation
603 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
604 Console.debug("Obtained Temperature Factor type of '" + tft
605 + "' for structure '" + structureFilepath + "'");
606 } catch (IllegalArgumentException e)
608 // Just an error message!
609 StringBuilder sb = new StringBuilder().append("Cannot set ")
610 .append(Arg.TEMPFAC.argString()).append(" to '")
612 .append("', ignoring. Valid values are: ");
613 Iterator<TFType> it = Arrays.stream(TFType.values())
617 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
621 addWarn(sb.toString());
625 String sViewerName = avm.getFromSubValArgOrPref(
626 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER,
627 structureAv, subVals, null, null, "jmol");
628 ViewerType viewerType = ViewerType.getFromString(sViewerName);
630 // TODO use ssFromStructure
631 StructureViewer structureViewer = StructureChooser
632 .openStructureFileForSequence(null, null, ap, seq, false,
633 structureFilepath, tft, paeFilepath, false,
634 ssFromStructure, false, viewerType);
636 if (structureViewer == null)
638 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
640 addError("Failed to import and open structure view for file '"
641 + structureFile + "'.");
648 while (structureViewer.isBusy() && tries > 0)
651 if (structureViewer.isBusy())
655 "Waiting for viewer for " + structureFilepath);
658 if (tries == 0 && structureViewer.isBusy())
660 addWarn("Gave up waiting for structure viewer to load file '"
662 + "'. Something may have gone wrong.");
664 } catch (Exception x)
666 addError("Exception whilst waiting for structure viewer "
667 + structureFilepath, x);
671 // add StructureViewer to svMap list
674 svMap = new HashMap<>();
676 if (svMap.get(id) == null)
678 svMap.put(id, new ArrayList<>());
680 svMap.get(id).add(structureViewer);
683 "Successfully opened viewer for " + structureFilepath);
685 if (avm.containsArg(Arg.STRUCTUREIMAGE))
687 for (ArgValue structureImageArgValue : avm
688 .getArgValueListFromSubValOrArg(structureAv,
689 Arg.STRUCTUREIMAGE, subVals))
691 String structureImageFilename = argParser.makeSubstitutions(
692 structureImageArgValue.getValue(), id, true);
693 if (structureViewer != null && structureImageFilename != null)
695 SubVals structureImageSubVals = null;
696 structureImageSubVals = structureImageArgValue.getSubVals();
697 File structureImageFile = new File(structureImageFilename);
698 String width = avm.getValueFromSubValOrArg(
699 structureImageArgValue, Arg.WIDTH,
700 structureImageSubVals);
701 String height = avm.getValueFromSubValOrArg(
702 structureImageArgValue, Arg.HEIGHT,
703 structureImageSubVals);
704 String scale = avm.getValueFromSubValOrArg(
705 structureImageArgValue, Arg.SCALE,
706 structureImageSubVals);
707 String renderer = avm.getValueFromSubValOrArg(
708 structureImageArgValue, Arg.TEXTRENDERER,
709 structureImageSubVals);
710 String typeS = avm.getValueFromSubValOrArg(
711 structureImageArgValue, Arg.TYPE,
712 structureImageSubVals);
713 if (typeS == null || typeS.length() == 0)
715 typeS = FileUtils.getExtension(structureImageFile);
720 imageType = Enum.valueOf(TYPE.class,
721 typeS.toUpperCase(Locale.ROOT));
722 } catch (IllegalArgumentException e)
724 addWarn("Do not know image format '" + typeS
726 imageType = TYPE.PNG;
728 BitmapImageSizing userBis = ImageMaker
729 .parseScaleWidthHeightStrings(scale, width, height);
732 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
733 if (viewerType != ViewerType.JMOL)
735 addWarn("Cannot export image for structure viewer "
736 + viewerType.name() + " yet");
741 // Apply the temporary colourscheme to the linked alignment
742 // TODO: enhance for multiple linked alignments.
744 String imageColour = avm.getValueFromSubValOrArg(
745 structureImageArgValue, Arg.IMAGECOLOUR,
746 structureImageSubVals);
747 ColourSchemeI originalColourScheme = this
748 .getColourScheme(af);
749 this.colourAlignFrame(af, imageColour);
752 // custom image background colour
754 String bgcolourstring = avm.getValueFromSubValOrArg(
755 structureImageArgValue, Arg.BGCOLOUR,
756 structureImageSubVals);
757 Color bgcolour = null;
758 if (bgcolourstring != null && bgcolourstring.length() > 0)
760 bgcolour = ColorUtils.parseColourString(bgcolourstring);
761 if (bgcolour == null)
764 "Background colour string '" + bgcolourstring
765 + "' not recognised -- using default");
769 JalviewStructureDisplayI sview = structureViewer
770 .getJalviewStructureDisplay();
772 File sessionToRestore = null;
774 List<StructureCommandI> extraCommands = new ArrayList<>();
776 if (extraCommands.size() > 0 || bgcolour != null)
780 sessionToRestore = sview.saveSession();
781 } catch (Throwable t)
784 "Unable to save temporary session file before custom structure view export operation.");
791 if (bgcolour != null)
793 sview.getBinding().setBackgroundColour(bgcolour);
796 sview.getBinding().executeCommands(extraCommands, false,
797 "Executing Custom Commands");
799 // and export the view as an image
800 boolean success = this.checksBeforeWritingToFile(avm,
801 subVals, false, structureImageFilename,
802 "structure image", isError);
808 Console.debug("Rendering image to " + structureImageFile);
810 // TODO - extend StructureViewer / Binding with makePDBImage so
811 // we can do this with every viewer
816 // We don't expect class cast exception
817 AppJmol jmol = (AppJmol) sview;
818 jmol.makePDBImage(structureImageFile, imageType, renderer,
820 Console.info("Exported structure image to "
821 + structureImageFile);
823 // RESTORE SESSION AFTER EXPORT IF NEED BE
824 if (sessionToRestore != null)
827 "Restoring session from " + sessionToRestore);
829 sview.getBinding().restoreSession(
830 sessionToRestore.getAbsolutePath());
833 } catch (ImageOutputException ioexec)
836 "Unexpected error when restoring structure viewer session after custom view operations.");
843 this.colourAlignFrame(af, originalColourScheme);
844 } catch (Exception t)
847 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
854 argParser.setStructureFilename(null);
863 // many of jalview's format/layout methods are only thread safe on the
864 // swingworker thread.
865 // all these methods should be on the alignViewController so it can
866 // coordinate such details
869 showOrHideAnnotations(af, showSSAnnotations, showAnnotations,
877 final boolean _showSSAnnotations = showSSAnnotations;
878 final boolean _showAnnotations = showAnnotations;
879 final boolean _hideTFrows = hideTFrows;
880 SwingUtilities.invokeAndWait(() -> {
881 showOrHideAnnotations(_af, _showSSAnnotations, _showAnnotations,
886 } catch (Exception x)
889 "Unexpected exception adjusting annotation row visibility.",
902 af.setWrapFormat(wrap, true);
907 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
910 AlignFrame af = afMap.get(id);
911 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
912 .findAnnotation(PDBChain.class.getName().toString()))
914 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
915 af.alignPanel.av.getGlobalColourScheme(), 0);
916 acg.setSeqAssociated(true);
917 af.changeColour(acg);
918 Console.info("Changed colour " + acg.toString());
923 return theseArgsWereParsed && !isError;
926 private static void showOrHideAnnotations(AlignFrame af,
927 boolean showSSAnnotations, boolean showAnnotations,
930 af.setAnnotationsVisibility(showSSAnnotations, true, false);
931 af.setAnnotationsVisibility(showAnnotations, false, true);
933 // show temperature factor annotations?
936 // do this better (annotation types?)
937 List<String> hideThese = new ArrayList<>();
938 hideThese.add("Temperature Factor");
939 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
940 AlignmentUtils.showOrHideSequenceAnnotations(
941 af.getCurrentView().getAlignment(), hideThese, null, false,
946 protected void processGroovyScript(String id)
948 ArgValuesMap avm = argParser.getLinkedArgs(id);
949 AlignFrame af = afMap.get(id);
951 if (avm != null && !avm.containsArg(Arg.GROOVY))
959 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
962 if (avm.containsArg(Arg.GROOVY))
964 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
966 String groovyscript = groovyAv.getValue();
967 if (groovyscript != null)
969 // Execute the groovy script after we've done all the rendering stuff
970 // and before any images or figures are generated.
971 Console.info("Executing script " + groovyscript);
972 Jalview.getInstance().executeGroovyScript(groovyscript, af);
978 protected boolean processImages(String id)
980 ArgValuesMap avm = argParser.getLinkedArgs(id);
981 AlignFrame af = afMap.get(id);
983 if (avm != null && !avm.containsArg(Arg.IMAGE))
991 addWarn("Do not have an alignment window to create image from (id="
992 + id + "). Not proceeding.");
996 Boolean isError = Boolean.valueOf(false);
997 if (avm.containsArg(Arg.IMAGE))
999 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
1001 String val = imageAv.getValue();
1002 SubVals imageSubVals = imageAv.getSubVals();
1003 String fileName = imageSubVals.getContent();
1004 File file = new File(fileName);
1005 String name = af.getName();
1006 String renderer = avm.getValueFromSubValOrArg(imageAv,
1007 Arg.TEXTRENDERER, imageSubVals);
1008 if (renderer == null)
1010 String type = "png"; // default
1012 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
1014 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
1016 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
1018 BitmapImageSizing userBis = ImageMaker
1019 .parseScaleWidthHeightStrings(scale, width, height);
1021 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
1022 if (type == null && fileName != null)
1024 for (String ext : new String[] { "svg", "png", "html", "eps" })
1026 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1032 // for moment we disable JSON export
1033 Cache.setPropsAreReadOnly(true);
1034 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
1036 String imageColour = avm.getValueFromSubValOrArg(imageAv,
1037 Arg.IMAGECOLOUR, imageSubVals);
1038 ColourSchemeI originalColourScheme = this.getColourScheme(af);
1039 this.colourAlignFrame(af, imageColour);
1041 Console.info("Writing " + file);
1043 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
1044 false, fileName, "image", isError);
1056 Console.debug("Outputting type '" + type + "' to " + fileName);
1057 af.createSVG(file, renderer);
1061 Console.debug("Outputting type '" + type + "' to " + fileName);
1062 af.createPNG(file, null, userBis);
1066 Console.debug("Outputting type '" + type + "' to " + fileName);
1067 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1068 htmlSVG.exportHTML(fileName, renderer);
1073 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1076 BioJsHTMLOutput.refreshVersionInfo(
1077 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1078 } catch (URISyntaxException e)
1080 e.printStackTrace();
1082 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1083 bjs.exportHTML(fileName);
1087 Console.debug("Outputting EPS file: " + fileName);
1088 af.createEPS(file, renderer);
1092 Console.debug("Outputting ImageMap file: " + fileName);
1093 af.createImageMap(file, name);
1097 addWarn(Arg.IMAGE.argString() + " type '" + type
1098 + "' not known. Ignoring");
1101 } catch (Exception ioex)
1103 addError("Unexpected error during export to '" + fileName + "'",
1108 this.colourAlignFrame(af, originalColourScheme);
1114 protected boolean processOutput(String id)
1116 ArgValuesMap avm = argParser.getLinkedArgs(id);
1117 AlignFrame af = afMap.get(id);
1119 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1127 addWarn("Do not have an alignment window (id=" + id
1128 + "). Not proceeding.");
1132 Boolean isError = Boolean.valueOf(false);
1134 if (avm.containsArg(Arg.OUTPUT))
1136 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1138 String val = av.getValue();
1139 SubVals subVals = av.getSubVals();
1140 String fileName = subVals.getContent();
1141 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1142 File file = new File(fileName);
1144 String name = af.getName();
1145 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1147 FileFormats ffs = FileFormats.getInstance();
1148 List<String> validFormats = ffs.getWritableFormats(false);
1150 FileFormatI ff = null;
1151 if (format == null && fileName != null)
1153 FORMAT: for (String fname : validFormats)
1155 FileFormatI tff = ffs.forName(fname);
1156 String[] extensions = tff.getExtensions().split(",");
1157 for (String ext : extensions)
1159 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1162 format = ff.getName();
1168 if (ff == null && format != null)
1170 ff = ffs.forName(format);
1176 ff = FileFormat.Fasta;
1180 StringBuilder validSB = new StringBuilder();
1181 for (String f : validFormats)
1183 if (validSB.length() > 0)
1184 validSB.append(", ");
1186 FileFormatI tff = ffs.forName(f);
1187 validSB.append(" (");
1188 validSB.append(tff.getExtensions());
1189 validSB.append(")");
1192 addError("No valid format specified for "
1193 + Arg.OUTPUT.argString() + ". Valid formats are "
1194 + validSB.toString() + ".");
1199 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1200 fileName, ff.getName(), isError);
1206 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1207 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1208 !Platform.isHeadless());
1210 Console.info("Writing " + fileName);
1212 af.saveAlignment(fileName, ff, stdout, backups);
1213 if (af.isSaveAlignmentSuccessful())
1215 Console.debug("Written alignment '" + name + "' in "
1216 + ff.getName() + " format to '" + file + "'");
1220 addError("Error writing file '" + file + "' in " + ff.getName()
1231 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1234 SubVals subVals = av.getSubVals();
1235 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1236 SequenceI seq = null;
1237 if (subVals == null && idAv == null)
1239 if (af == null || af.getCurrentView() == null)
1243 AlignmentI al = af.getCurrentView().getAlignment();
1248 if (subVals != null)
1250 if (subVals.has(Arg.SEQID.getName()))
1252 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1254 else if (-1 < subVals.getIndex()
1255 && subVals.getIndex() < al.getSequences().size())
1257 seq = al.getSequenceAt(subVals.getIndex());
1260 if (seq == null && idAv != null)
1262 seq = al.findName(idAv.getValue());
1267 public AlignFrame[] getAlignFrames()
1269 AlignFrame[] afs = null;
1272 afs = (AlignFrame[]) afMap.values().toArray();
1278 public List<StructureViewer> getStructureViewers()
1280 List<StructureViewer> svs = null;
1283 for (List<StructureViewer> svList : svMap.values())
1287 svs = new ArrayList<>();
1295 private void colourAlignFrame(AlignFrame af, String colour)
1297 // use string "none" to remove colour scheme
1298 if (colour != null && "" != colour)
1300 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1301 af.getViewport(), af.getViewport().getAlignment(), colour);
1302 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1304 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1308 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1309 colourAlignFrame(af, cs);
1314 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1318 SwingUtilities.invokeAndWait(new Runnable()
1323 // Note that cs == null removes colour scheme from af
1324 af.changeColour(cs);
1327 } catch (Exception x)
1329 Console.trace("Interrupted whilst waiting for colorAlignFrame action",
1335 private ColourSchemeI getColourScheme(AlignFrame af)
1337 return af.getViewport().getGlobalColourScheme();
1340 private void addInfo(String errorMessage)
1342 Console.info(errorMessage);
1343 errors.add(errorMessage);
1346 private void addWarn(String errorMessage)
1348 Console.warn(errorMessage);
1349 errors.add(errorMessage);
1352 private void addError(String errorMessage)
1354 addError(errorMessage, null);
1357 private void addError(String errorMessage, Exception e)
1359 Console.error(errorMessage, e);
1360 errors.add(errorMessage);
1363 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1364 SubVals subVal, boolean includeBackups, String filename,
1365 String adjective, Boolean isError)
1367 File file = new File(filename);
1369 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1370 null, "OVERWRITE_OUTPUT", false);
1371 boolean stdout = false;
1372 boolean backups = false;
1375 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1376 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1377 // otherwise if headless assume false, if not headless use the user
1378 // preference with default true.
1379 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1380 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1381 !Platform.isHeadless());
1384 if (file.exists() && !(overwrite || backups || stdout))
1386 addWarn("Won't overwrite file '" + filename + "' without "
1387 + Arg.OVERWRITE.argString()
1388 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1393 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1394 "MKDIRS_OUTPUT", false);
1396 if (!FileUtils.checkParentDir(file, mkdirs))
1398 addError("Directory '"
1399 + FileUtils.getParentDir(file).getAbsolutePath()
1400 + "' does not exist for " + adjective + " file '" + filename
1402 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1410 public List<String> getErrors()
1415 public String errorsToString()
1417 StringBuilder sb = new StringBuilder();
1418 for (String error : errors)
1420 if (sb.length() > 0)
1422 sb.append("- " + error);
1424 return sb.toString();