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.IOException;
26 import java.net.URISyntaxException;
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Collections;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
33 import java.util.Locale;
36 import javax.swing.SwingUtilities;
38 import jalview.analysis.AlignmentUtils;
39 import jalview.api.structures.JalviewStructureDisplayI;
40 import jalview.bin.Jalview.ExitCode;
41 import jalview.bin.argparser.Arg;
42 import jalview.bin.argparser.ArgParser;
43 import jalview.bin.argparser.ArgValue;
44 import jalview.bin.argparser.ArgValuesMap;
45 import jalview.bin.argparser.SubVals;
46 import jalview.datamodel.AlignmentI;
47 import jalview.datamodel.SequenceI;
48 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
49 import jalview.gui.AlignFrame;
50 import jalview.gui.AlignmentPanel;
51 import jalview.gui.AppJmol;
52 import jalview.gui.Desktop;
53 import jalview.gui.Preferences;
54 import jalview.gui.StructureChooser;
55 import jalview.gui.StructureViewer;
56 import jalview.gui.StructureViewer.ViewerType;
57 import jalview.io.AppletFormatAdapter;
58 import jalview.io.BackupFiles;
59 import jalview.io.BioJsHTMLOutput;
60 import jalview.io.DataSourceType;
61 import jalview.io.FileFormat;
62 import jalview.io.FileFormatException;
63 import jalview.io.FileFormatI;
64 import jalview.io.FileFormats;
65 import jalview.io.FileLoader;
66 import jalview.io.HtmlSvgOutput;
67 import jalview.io.IdentifyFile;
68 import jalview.io.NewickFile;
69 import jalview.io.exceptions.ImageOutputException;
70 import jalview.schemes.ColourSchemeI;
71 import jalview.schemes.ColourSchemeProperty;
72 import jalview.structure.StructureCommandI;
73 import jalview.structure.StructureImportSettings.TFType;
74 import jalview.structure.StructureSelectionManager;
75 import jalview.util.ColorUtils;
76 import jalview.util.FileUtils;
77 import jalview.util.HttpUtils;
78 import jalview.util.ImageMaker;
79 import jalview.util.ImageMaker.TYPE;
80 import jalview.util.MessageManager;
81 import jalview.util.Platform;
82 import jalview.util.StringUtils;
83 import jalview.util.imagemaker.BitmapImageSizing;
89 private boolean headless;
91 private ArgParser argParser;
93 private Map<String, AlignFrame> afMap;
95 private Map<String, List<StructureViewer>> svMap;
97 private boolean commandArgsProvided = false;
99 private boolean argsWereParsed = false;
101 private List<String> errors = new ArrayList<>();
103 public Commands(ArgParser argparser, boolean headless)
105 this(Desktop.instance, argparser, headless);
108 public Commands(Desktop d, ArgParser argparser, boolean h)
110 argParser = argparser;
113 afMap = new HashMap<>();
116 protected boolean processArgs()
118 if (argParser == null)
123 boolean theseArgsWereParsed = false;
125 if (argParser != null && argParser.getLinkedIds() != null)
127 for (String id : argParser.getLinkedIds())
129 ArgValuesMap avm = argParser.getLinkedArgs(id);
130 theseArgsWereParsed = true;
131 boolean processLinkedOkay = processLinked(id);
132 theseArgsWereParsed &= processLinkedOkay;
134 processGroovyScript(id);
136 // wait around until alignFrame isn't busy
137 AlignFrame af = afMap.get(id);
138 while (af != null && af.getViewport().isCalcInProgress())
143 } catch (Exception q)
149 theseArgsWereParsed &= processImages(id);
151 if (processLinkedOkay)
153 theseArgsWereParsed &= processOutput(id);
157 if (avm.getBoolean(Arg.CLOSE))
162 af.closeMenuItem_actionPerformed(true);
170 // report errors - if any
171 String errorsRaised = errorsToString();
172 if (errorsRaised.trim().length() > 0)
175 "The following errors and warnings occurred whilst processing files:\n"
178 // gui errors reported in Jalview
180 if (argParser.getBoolean(Arg.QUIT))
182 Jalview.exit("Exiting due to " + Arg.QUIT.argString() + " argument.",
186 // carry on with jalview.bin.Jalview
187 argsWereParsed = theseArgsWereParsed;
188 return argsWereParsed;
191 public boolean commandArgsProvided()
193 return commandArgsProvided;
196 public boolean argsWereParsed()
198 return argsWereParsed;
201 protected boolean processLinked(String id)
203 boolean theseArgsWereParsed = false;
204 ArgValuesMap avm = argParser.getLinkedArgs(id);
210 Boolean isError = Boolean.valueOf(false);
212 // set wrap, showSSAnnotations, showAnnotations and hideTFrows scope here so
213 // it can be applied after structures are opened
214 boolean wrap = false;
215 boolean showSSAnnotations = false;
216 boolean showAnnotations = false;
217 boolean hideTFrows = false;
218 AlignFrame af = null;
220 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
222 commandArgsProvided = true;
223 final long progress = System.currentTimeMillis();
225 boolean first = true;
226 boolean progressBarSet = false;
227 // Combine the APPEND and OPEN files into one list, along with whether it
228 // was APPEND or OPEN
229 List<ArgValue> openAvList = new ArrayList<>();
230 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
231 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
232 // sort avlist based on av.getArgIndex()
233 Collections.sort(openAvList);
234 for (ArgValue av : openAvList)
237 SubVals sv = av.getSubVals();
238 String openFile = av.getValue();
239 if (openFile == null)
242 theseArgsWereParsed = true;
246 if (!headless && desktop != null)
248 SwingUtilities.invokeLater(new Runnable()
253 desktop.setProgressBar(
254 MessageManager.getString(
255 "status.processing_commandline_args"),
260 progressBarSet = true;
264 if (!Platform.isJS())
266 * ignore in JavaScript -- can't just file existence - could load it?
271 if (!HttpUtils.startsWithHttpOrHttps(openFile))
273 if (!(new File(openFile)).exists())
275 addError("Can't find file '" + openFile + "'");
282 DataSourceType protocol = AppletFormatAdapter
283 .checkProtocol(openFile);
285 FileFormatI format = null;
288 format = new IdentifyFile().identify(openFile, protocol);
289 } catch (FileFormatException e1)
291 addError("Unknown file format for '" + openFile + "'");
297 // When to open a new AlignFrame
298 if (af == null || "true".equals(av.getSubVal("new"))
299 || a == Arg.OPEN || format == FileFormat.Jalview)
303 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
308 "Opening '" + openFile + "' in new alignment frame");
309 FileLoader fileLoader = new FileLoader(!headless);
310 boolean xception = false;
313 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
315 } catch (Throwable thr)
318 addError("Couldn't open '" + openFile + "' as " + format + " "
319 + thr.getLocalizedMessage()
320 + " (Enable debug for full stack trace)");
322 Console.debug("Exception when opening '" + openFile + "'", thr);
325 if (af == null && !xception)
327 addInfo("Ignoring '" + openFile
328 + "' - no alignment data found.");
334 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
335 null, "DEFAULT_COLOUR_PROT", "");
336 this.colourAlignFrame(af, colour);
338 // Change alignment frame title
339 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
344 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
348 String featuresfile = avm.getValueFromSubValOrArg(av,
350 if (featuresfile != null)
352 af.parseFeaturesFile(featuresfile,
353 AppletFormatAdapter.checkProtocol(featuresfile));
354 Jalview.testoutput(argParser, Arg.FEATURES,
355 "examples/testdata/plantfdx.features", featuresfile);
358 // Add annotations from file
359 String annotationsfile = avm.getValueFromSubValOrArg(av,
360 Arg.ANNOTATIONS, sv);
361 if (annotationsfile != null)
363 af.loadJalviewDataFile(annotationsfile, null, null, null);
364 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
365 "examples/testdata/plantfdx.annotations",
369 // Set or clear the sortbytree flag
370 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
374 af.getViewport().setSortByTree(true);
375 Jalview.testoutput(argParser, Arg.SORTBYTREE);
378 // Load tree from file
379 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
380 if (treefile != null)
384 NewickFile nf = new NewickFile(treefile,
385 AppletFormatAdapter.checkProtocol(treefile));
386 af.getViewport().setCurrentTree(
387 af.showNewickTree(nf, treefile).getTree());
388 Jalview.testoutput(argParser, Arg.TREE,
389 "examples/testdata/uniref50_test_tree", treefile);
390 } catch (IOException e)
392 addError("Couldn't add tree " + treefile, e);
397 // Show secondary structure annotations?
398 showSSAnnotations = avm.getFromSubValArgOrPref(
399 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
400 "STRUCT_FROM_PDB", true);
401 // Show sequence annotations?
402 showAnnotations = avm.getFromSubValArgOrPref(Arg.SHOWANNOTATIONS,
403 av.getSubVals(), null, "SHOW_ANNOTATIONS", true);
404 // hide the Temperature Factor row?
405 hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
407 // showSSAnnotations, showAnnotations, hideTFrows used after opening
410 // wrap alignment? do this last for formatting reasons
411 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
412 "WRAP_ALIGNMENT", false);
413 // af.setWrapFormat(wrap) is applied after structures are opened for
414 // annotation reasons
416 // store the AlignFrame for this id
419 // is it its own structure file?
420 if (format.isStructureFile())
422 StructureSelectionManager ssm = StructureSelectionManager
423 .getStructureSelectionManager(Desktop.instance);
424 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
425 ssm.computeMapping(false, new SequenceI[] { seq }, null,
426 openFile, DataSourceType.FILE, null, null, null, false);
432 "Opening '" + openFile + "' in existing alignment frame");
434 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
436 : DataSourceType.FILE;
438 FileLoader fileLoader = new FileLoader(!headless);
439 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
443 Console.debug("Command " + Arg.APPEND + " executed successfully!");
446 if (first) // first=true means nothing opened
450 Jalview.exit("Could not open any files in headless mode",
455 Console.info("No more files to open");
458 if (progressBarSet && desktop != null)
459 desktop.setProgressBar(null, progress);
463 // open the structure (from same PDB file or given PDBfile)
464 if (!avm.getBoolean(Arg.NOSTRUCTURE))
470 if (avm.containsArg(Arg.STRUCTURE))
472 commandArgsProvided = true;
473 for (ArgValue structureAv : avm.getArgValueList(Arg.STRUCTURE))
475 argParser.setStructureFilename(null);
476 String val = structureAv.getValue();
477 SubVals subVals = structureAv.getSubVals();
478 int argIndex = structureAv.getArgIndex();
479 SequenceI seq = getSpecifiedSequence(af, avm, structureAv);
482 // Could not find sequence from subId, let's assume the first
483 // sequence in the alignframe
484 AlignmentI al = af.getCurrentView().getAlignment();
485 seq = al.getSequenceAt(0);
490 addWarn("Could not find sequence for argument "
491 + Arg.STRUCTURE.argString() + "=" + val);
494 String structureFilename = null;
495 File structureFile = null;
496 if (subVals.getContent() != null
497 && subVals.getContent().length() != 0)
499 structureFilename = subVals.getContent();
500 Console.debug("Using structure file (from argument) '"
501 + structureFilename + "'");
502 structureFile = new File(structureFilename);
504 /* THIS DOESN'T WORK */
505 else if (seq.getAllPDBEntries() != null
506 && seq.getAllPDBEntries().size() > 0)
508 structureFile = new File(
509 seq.getAllPDBEntries().elementAt(0).getFile());
510 if (structureFile != null)
512 Console.debug("Using structure file (from sequence) '"
513 + structureFile.getAbsolutePath() + "'");
515 structureFilename = structureFile.getAbsolutePath();
518 if (structureFilename == null || structureFile == null)
520 addWarn("Not provided structure file with '" + val + "'");
524 if (!structureFile.exists())
526 addWarn("Structure file '" + structureFile.getAbsoluteFile()
531 Console.debug("Using structure file "
532 + structureFile.getAbsolutePath());
534 argParser.setStructureFilename(structureFilename);
536 // open structure view
537 AlignmentPanel ap = af.alignPanel;
540 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
541 StructureViewer.ViewerType.JMOL.toString());
544 String structureFilepath = structureFile.getAbsolutePath();
546 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
547 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
548 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER,
549 structureAv, subVals, null, null, null);
550 if (paeFilepath != null)
552 File paeFile = new File(paeFilepath);
556 paeFilepath = paeFile.getCanonicalPath();
557 } catch (IOException e)
559 paeFilepath = paeFile.getAbsolutePath();
560 addWarn("Problem with the PAE file path: '"
561 + paeFile.getPath() + "'");
565 // showing annotations from structure file or not
566 boolean ssFromStructure = avm.getFromSubValArgOrPref(
567 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
570 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
571 // reference annotations
572 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
573 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER,
574 structureAv, subVals, null, null, null);
575 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
576 subVals, null, "ADD_TEMPFACT_ANN", false, true);
577 TFType tft = notempfac ? null : TFType.DEFAULT;
578 if (tftString != null && !notempfac)
580 // get kind of temperature factor annotation
583 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
584 Console.debug("Obtained Temperature Factor type of '" + tft
585 + "' for structure '" + structureFilepath + "'");
586 } catch (IllegalArgumentException e)
588 // Just an error message!
589 StringBuilder sb = new StringBuilder().append("Cannot set ")
590 .append(Arg.TEMPFAC.argString()).append(" to '")
592 .append("', ignoring. Valid values are: ");
593 Iterator<TFType> it = Arrays.stream(TFType.values())
597 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
601 addWarn(sb.toString());
605 String sViewerName = avm.getFromSubValArgOrPref(
606 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER,
607 structureAv, subVals, null, null, "jmol");
608 ViewerType viewerType = ViewerType.getFromString(sViewerName);
610 // TODO use ssFromStructure
611 StructureViewer structureViewer = StructureChooser
612 .openStructureFileForSequence(null, null, ap, seq, false,
613 structureFilepath, tft, paeFilepath, false,
614 ssFromStructure, false, viewerType);
616 if (structureViewer == null)
618 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
620 addError("Failed to import and open structure view for file '"
621 + structureFile + "'.");
628 while (structureViewer.isBusy() && tries > 0)
631 if (structureViewer.isBusy())
635 "Waiting for viewer for " + structureFilepath);
638 if (tries == 0 && structureViewer.isBusy())
640 addWarn("Gave up waiting for structure viewer to load file '"
642 + "'. Something may have gone wrong.");
644 } catch (Exception x)
646 addError("Exception whilst waiting for structure viewer "
647 + structureFilepath, x);
651 // add StructureViewer to svMap list
654 svMap = new HashMap<>();
656 if (svMap.get(id) == null)
658 svMap.put(id, new ArrayList<>());
660 svMap.get(id).add(structureViewer);
663 "Successfully opened viewer for " + structureFilepath);
665 if (avm.containsArg(Arg.STRUCTUREIMAGE))
667 for (ArgValue structureImageArgValue : avm
668 .getArgValueListFromSubValOrArg(structureAv,
669 Arg.STRUCTUREIMAGE, subVals))
671 String structureImageFilename = argParser.makeSubstitutions(
672 structureImageArgValue.getValue(), id, true);
673 if (structureViewer != null && structureImageFilename != null)
675 SubVals structureImageSubVals = null;
676 structureImageSubVals = structureImageArgValue.getSubVals();
677 File structureImageFile = new File(structureImageFilename);
678 String width = avm.getValueFromSubValOrArg(
679 structureImageArgValue, Arg.WIDTH,
680 structureImageSubVals);
681 String height = avm.getValueFromSubValOrArg(
682 structureImageArgValue, Arg.HEIGHT,
683 structureImageSubVals);
684 String scale = avm.getValueFromSubValOrArg(
685 structureImageArgValue, Arg.SCALE,
686 structureImageSubVals);
687 String renderer = avm.getValueFromSubValOrArg(
688 structureImageArgValue, Arg.TEXTRENDERER,
689 structureImageSubVals);
690 String typeS = avm.getValueFromSubValOrArg(
691 structureImageArgValue, Arg.TYPE,
692 structureImageSubVals);
693 if (typeS == null || typeS.length() == 0)
695 typeS = FileUtils.getExtension(structureImageFile);
700 imageType = Enum.valueOf(TYPE.class,
701 typeS.toUpperCase(Locale.ROOT));
702 } catch (IllegalArgumentException e)
704 addWarn("Do not know image format '" + typeS
706 imageType = TYPE.PNG;
708 BitmapImageSizing userBis = ImageMaker
709 .parseScaleWidthHeightStrings(scale, width, height);
712 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
713 if (viewerType != ViewerType.JMOL)
715 addWarn("Cannot export image for structure viewer "
716 + viewerType.name() + " yet");
721 // Apply the temporary colourscheme to the linked alignment
722 // TODO: enhance for multiple linked alignments.
724 String imageColour = avm.getValueFromSubValOrArg(
725 structureImageArgValue, Arg.IMAGECOLOUR,
726 structureImageSubVals);
727 ColourSchemeI originalColourScheme = this
728 .getColourScheme(af);
729 this.colourAlignFrame(af, imageColour);
732 // custom image background colour
734 String bgcolourstring = avm.getValueFromSubValOrArg(
735 structureImageArgValue, Arg.BGCOLOUR,
736 structureImageSubVals);
737 Color bgcolour = null;
738 if (bgcolourstring != null && bgcolourstring.length() > 0)
740 bgcolour = ColorUtils.parseColourString(bgcolourstring);
741 if (bgcolour == null)
744 "Background colour string '" + bgcolourstring
745 + "' not recognised -- using default");
749 JalviewStructureDisplayI sview = structureViewer
750 .getJalviewStructureDisplay();
752 File sessionToRestore = null;
754 List<StructureCommandI> extraCommands = new ArrayList<>();
756 if (extraCommands.size() > 0 || bgcolour != null)
760 sessionToRestore = sview.saveSession();
761 } catch (Throwable t)
764 "Unable to save temporary session file before custom structure view export operation.");
771 if (bgcolour != null)
773 sview.getBinding().setBackgroundColour(bgcolour);
776 sview.getBinding().executeCommands(extraCommands, false,
777 "Executing Custom Commands");
779 // and export the view as an image
780 boolean success = this.checksBeforeWritingToFile(avm,
781 subVals, false, structureImageFilename,
782 "structure image", isError);
788 Console.debug("Rendering image to " + structureImageFile);
790 // TODO - extend StructureViewer / Binding with makePDBImage so
791 // we can do this with every viewer
796 // We don't expect class cast exception
797 AppJmol jmol = (AppJmol) sview;
798 jmol.makePDBImage(structureImageFile, imageType, renderer,
800 Console.info("Exported structure image to "
801 + structureImageFile);
803 // RESTORE SESSION AFTER EXPORT IF NEED BE
804 if (sessionToRestore != null)
807 "Restoring session from " + sessionToRestore);
809 sview.getBinding().restoreSession(
810 sessionToRestore.getAbsolutePath());
813 } catch (ImageOutputException ioexec)
816 "Unexpected error when restoring structure viewer session after custom view operations.");
823 this.colourAlignFrame(af, originalColourScheme);
824 } catch (Exception t)
827 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
834 argParser.setStructureFilename(null);
843 // many of jalview's format/layout methods are only thread safe on the
844 // swingworker thread.
845 // all these methods should be on the alignViewController so it can
846 // coordinate such details
849 showOrHideAnnotations(af, showSSAnnotations, showAnnotations,
857 final boolean _showSSAnnotations = showSSAnnotations;
858 final boolean _showAnnotations = showAnnotations;
859 final boolean _hideTFrows = hideTFrows;
860 SwingUtilities.invokeAndWait(() -> {
861 showOrHideAnnotations(_af, _showSSAnnotations, _showAnnotations,
866 } catch (Exception x)
869 "Unexpected exception adjusting annotation row visibility.",
882 af.setWrapFormat(wrap, true);
887 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
890 AlignFrame af = afMap.get(id);
891 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
892 .findAnnotation(PDBChain.class.getName().toString()))
894 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
895 af.alignPanel.av.getGlobalColourScheme(), 0);
896 acg.setSeqAssociated(true);
897 af.changeColour(acg);
898 Console.info("Changed colour " + acg.toString());
903 return theseArgsWereParsed && !isError;
906 private static void showOrHideAnnotations(AlignFrame af,
907 boolean showSSAnnotations, boolean showAnnotations,
910 af.setAnnotationsVisibility(showSSAnnotations, true, false);
911 af.setAnnotationsVisibility(showAnnotations, false, true);
913 // show temperature factor annotations?
916 // do this better (annotation types?)
917 List<String> hideThese = new ArrayList<>();
918 hideThese.add("Temperature Factor");
919 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
920 AlignmentUtils.showOrHideSequenceAnnotations(
921 af.getCurrentView().getAlignment(), hideThese, null, false,
926 protected void processGroovyScript(String id)
928 ArgValuesMap avm = argParser.getLinkedArgs(id);
929 AlignFrame af = afMap.get(id);
931 if (avm != null && !avm.containsArg(Arg.GROOVY))
939 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
942 if (avm.containsArg(Arg.GROOVY))
944 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
946 String groovyscript = groovyAv.getValue();
947 if (groovyscript != null)
949 // Execute the groovy script after we've done all the rendering stuff
950 // and before any images or figures are generated.
951 Console.info("Executing script " + groovyscript);
952 Jalview.getInstance().executeGroovyScript(groovyscript, af);
958 protected boolean processImages(String id)
960 ArgValuesMap avm = argParser.getLinkedArgs(id);
961 AlignFrame af = afMap.get(id);
963 if (avm != null && !avm.containsArg(Arg.IMAGE))
971 addWarn("Do not have an alignment window to create image from (id="
972 + id + "). Not proceeding.");
976 Boolean isError = Boolean.valueOf(false);
977 if (avm.containsArg(Arg.IMAGE))
979 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
981 String val = imageAv.getValue();
982 SubVals imageSubVals = imageAv.getSubVals();
983 String fileName = imageSubVals.getContent();
984 File file = new File(fileName);
985 String name = af.getName();
986 String renderer = avm.getValueFromSubValOrArg(imageAv,
987 Arg.TEXTRENDERER, imageSubVals);
988 if (renderer == null)
990 String type = "png"; // default
992 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
994 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
996 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
998 BitmapImageSizing userBis = ImageMaker
999 .parseScaleWidthHeightStrings(scale, width, height);
1001 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
1002 if (type == null && fileName != null)
1004 for (String ext : new String[] { "svg", "png", "html", "eps" })
1006 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1012 // for moment we disable JSON export
1013 Cache.setPropsAreReadOnly(true);
1014 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
1016 String imageColour = avm.getValueFromSubValOrArg(imageAv,
1017 Arg.IMAGECOLOUR, imageSubVals);
1018 ColourSchemeI originalColourScheme = this.getColourScheme(af);
1019 this.colourAlignFrame(af, imageColour);
1021 Console.info("Writing " + file);
1023 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
1024 false, fileName, "image", isError);
1036 Console.debug("Outputting type '" + type + "' to " + fileName);
1037 af.createSVG(file, renderer);
1041 Console.debug("Outputting type '" + type + "' to " + fileName);
1042 af.createPNG(file, null, userBis);
1046 Console.debug("Outputting type '" + type + "' to " + fileName);
1047 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1048 htmlSVG.exportHTML(fileName, renderer);
1053 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1056 BioJsHTMLOutput.refreshVersionInfo(
1057 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1058 } catch (URISyntaxException e)
1060 e.printStackTrace();
1062 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1063 bjs.exportHTML(fileName);
1067 Console.debug("Outputting EPS file: " + fileName);
1068 af.createEPS(file, renderer);
1072 Console.debug("Outputting ImageMap file: " + fileName);
1073 af.createImageMap(file, name);
1077 addWarn(Arg.IMAGE.argString() + " type '" + type
1078 + "' not known. Ignoring");
1081 } catch (Exception ioex)
1083 addError("Unexpected error during export to '" + fileName + "'",
1088 this.colourAlignFrame(af, originalColourScheme);
1094 protected boolean processOutput(String id)
1096 ArgValuesMap avm = argParser.getLinkedArgs(id);
1097 AlignFrame af = afMap.get(id);
1099 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1107 addWarn("Do not have an alignment window (id=" + id
1108 + "). Not proceeding.");
1112 Boolean isError = Boolean.valueOf(false);
1114 if (avm.containsArg(Arg.OUTPUT))
1116 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1118 String val = av.getValue();
1119 SubVals subVals = av.getSubVals();
1120 String fileName = subVals.getContent();
1121 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1122 File file = new File(fileName);
1124 String name = af.getName();
1125 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1127 FileFormats ffs = FileFormats.getInstance();
1128 List<String> validFormats = ffs.getWritableFormats(false);
1130 FileFormatI ff = null;
1131 if (format == null && fileName != null)
1133 FORMAT: for (String fname : validFormats)
1135 FileFormatI tff = ffs.forName(fname);
1136 String[] extensions = tff.getExtensions().split(",");
1137 for (String ext : extensions)
1139 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1142 format = ff.getName();
1148 if (ff == null && format != null)
1150 ff = ffs.forName(format);
1156 ff = FileFormat.Fasta;
1160 StringBuilder validSB = new StringBuilder();
1161 for (String f : validFormats)
1163 if (validSB.length() > 0)
1164 validSB.append(", ");
1166 FileFormatI tff = ffs.forName(f);
1167 validSB.append(" (");
1168 validSB.append(tff.getExtensions());
1169 validSB.append(")");
1172 addError("No valid format specified for "
1173 + Arg.OUTPUT.argString() + ". Valid formats are "
1174 + validSB.toString() + ".");
1179 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1180 fileName, ff.getName(), isError);
1186 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1187 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1188 !Platform.isHeadless());
1190 Console.info("Writing " + fileName);
1192 af.saveAlignment(fileName, ff, stdout, backups);
1193 if (af.isSaveAlignmentSuccessful())
1195 Console.debug("Written alignment '" + name + "' in "
1196 + ff.getName() + " format to '" + file + "'");
1200 addError("Error writing file '" + file + "' in " + ff.getName()
1211 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1214 SubVals subVals = av.getSubVals();
1215 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1216 SequenceI seq = null;
1217 if (subVals == null && idAv == null)
1219 if (af == null || af.getCurrentView() == null)
1223 AlignmentI al = af.getCurrentView().getAlignment();
1228 if (subVals != null)
1230 if (subVals.has(Arg.SEQID.getName()))
1232 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1234 else if (-1 < subVals.getIndex()
1235 && subVals.getIndex() < al.getSequences().size())
1237 seq = al.getSequenceAt(subVals.getIndex());
1240 if (seq == null && idAv != null)
1242 seq = al.findName(idAv.getValue());
1247 public AlignFrame[] getAlignFrames()
1249 AlignFrame[] afs = null;
1252 afs = (AlignFrame[]) afMap.values().toArray();
1258 public List<StructureViewer> getStructureViewers()
1260 List<StructureViewer> svs = null;
1263 for (List<StructureViewer> svList : svMap.values())
1267 svs = new ArrayList<>();
1275 private void colourAlignFrame(AlignFrame af, String colour)
1277 // use string "none" to remove colour scheme
1278 if (colour != null && "" != colour)
1280 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1281 af.getViewport(), af.getViewport().getAlignment(), colour);
1282 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1284 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1288 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1289 colourAlignFrame(af, cs);
1294 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1296 // Note that cs == null removes colour scheme from af
1297 af.changeColour(cs);
1300 private ColourSchemeI getColourScheme(AlignFrame af)
1302 return af.getViewport().getGlobalColourScheme();
1305 private void addInfo(String errorMessage)
1307 Console.info(errorMessage);
1308 errors.add(errorMessage);
1311 private void addWarn(String errorMessage)
1313 Console.warn(errorMessage);
1314 errors.add(errorMessage);
1317 private void addError(String errorMessage)
1319 addError(errorMessage, null);
1322 private void addError(String errorMessage, Exception e)
1324 Console.error(errorMessage, e);
1325 errors.add(errorMessage);
1328 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1329 SubVals subVal, boolean includeBackups, String filename,
1330 String adjective, Boolean isError)
1332 File file = new File(filename);
1334 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1335 null, "OVERWRITE_OUTPUT", false);
1336 boolean stdout = false;
1337 boolean backups = false;
1340 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1341 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1342 // otherwise if headless assume false, if not headless use the user
1343 // preference with default true.
1344 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1345 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1346 !Platform.isHeadless());
1349 if (file.exists() && !(overwrite || backups || stdout))
1351 addWarn("Won't overwrite file '" + filename + "' without "
1352 + Arg.OVERWRITE.argString()
1353 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1358 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1359 "MKDIRS_OUTPUT", false);
1361 if (!FileUtils.checkParentDir(file, mkdirs))
1363 addError("Directory '"
1364 + FileUtils.getParentDir(file).getAbsolutePath()
1365 + "' does not exist for " + adjective + " file '" + filename
1367 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1375 public List<String> getErrors()
1380 public String errorsToString()
1382 StringBuilder sb = new StringBuilder();
1383 for (String error : errors)
1385 if (sb.length() > 0)
1387 sb.append("- " + error);
1389 return sb.toString();