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 = null;
335 if (avm.containsArg(Arg.COLOUR)
336 || !(format == FileFormat.Jalview))
338 colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv, null,
339 "DEFAULT_COLOUR_PROT", null);
343 this.colourAlignFrame(af, colour);
346 // Change alignment frame title
347 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
352 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
356 String featuresfile = avm.getValueFromSubValOrArg(av,
358 if (featuresfile != null)
360 af.parseFeaturesFile(featuresfile,
361 AppletFormatAdapter.checkProtocol(featuresfile));
362 Jalview.testoutput(argParser, Arg.FEATURES,
363 "examples/testdata/plantfdx.features", featuresfile);
366 // Add annotations from file
367 String annotationsfile = avm.getValueFromSubValOrArg(av,
368 Arg.ANNOTATIONS, sv);
369 if (annotationsfile != null)
371 af.loadJalviewDataFile(annotationsfile, null, null, null);
372 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
373 "examples/testdata/plantfdx.annotations",
377 // Set or clear the sortbytree flag
378 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
382 af.getViewport().setSortByTree(true);
383 Jalview.testoutput(argParser, Arg.SORTBYTREE);
386 // Load tree from file
387 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
388 if (treefile != null)
392 NewickFile nf = new NewickFile(treefile,
393 AppletFormatAdapter.checkProtocol(treefile));
394 af.getViewport().setCurrentTree(
395 af.showNewickTree(nf, treefile).getTree());
396 Jalview.testoutput(argParser, Arg.TREE,
397 "examples/testdata/uniref50_test_tree", treefile);
398 } catch (IOException e)
400 addError("Couldn't add tree " + treefile, e);
405 // Show secondary structure annotations?
406 showSSAnnotations = avm.getFromSubValArgOrPref(
407 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
408 "STRUCT_FROM_PDB", true);
409 // Show sequence annotations?
410 showAnnotations = avm.getFromSubValArgOrPref(Arg.SHOWANNOTATIONS,
411 av.getSubVals(), null, "SHOW_ANNOTATIONS", true);
412 // hide the Temperature Factor row?
413 hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
415 // showSSAnnotations, showAnnotations, hideTFrows used after opening
418 // wrap alignment? do this last for formatting reasons
419 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
420 "WRAP_ALIGNMENT", false);
421 // af.setWrapFormat(wrap) is applied after structures are opened for
422 // annotation reasons
424 // store the AlignFrame for this id
427 // is it its own structure file?
428 if (format.isStructureFile())
430 StructureSelectionManager ssm = StructureSelectionManager
431 .getStructureSelectionManager(Desktop.instance);
432 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
433 ssm.computeMapping(false, new SequenceI[] { seq }, null,
434 openFile, DataSourceType.FILE, null, null, null, false);
440 "Opening '" + openFile + "' in existing alignment frame");
442 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
444 : DataSourceType.FILE;
446 FileLoader fileLoader = new FileLoader(!headless);
447 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
451 Console.debug("Command " + Arg.APPEND + " executed successfully!");
454 if (first) // first=true means nothing opened
458 Jalview.exit("Could not open any files in headless mode",
463 Console.info("No more files to open");
466 if (progressBarSet && desktop != null)
467 desktop.setProgressBar(null, progress);
471 // open the structure (from same PDB file or given PDBfile)
472 if (!avm.getBoolean(Arg.NOSTRUCTURE))
478 if (avm.containsArg(Arg.STRUCTURE))
480 commandArgsProvided = true;
481 for (ArgValue structureAv : avm.getArgValueList(Arg.STRUCTURE))
483 argParser.setStructureFilename(null);
484 String val = structureAv.getValue();
485 SubVals subVals = structureAv.getSubVals();
486 int argIndex = structureAv.getArgIndex();
487 SequenceI seq = getSpecifiedSequence(af, avm, structureAv);
490 // Could not find sequence from subId, let's assume the first
491 // sequence in the alignframe
492 AlignmentI al = af.getCurrentView().getAlignment();
493 seq = al.getSequenceAt(0);
498 addWarn("Could not find sequence for argument "
499 + Arg.STRUCTURE.argString() + "=" + val);
502 String structureFilename = null;
503 File structureFile = null;
504 if (subVals.getContent() != null
505 && subVals.getContent().length() != 0)
507 structureFilename = subVals.getContent();
508 Console.debug("Using structure file (from argument) '"
509 + structureFilename + "'");
510 structureFile = new File(structureFilename);
512 /* THIS DOESN'T WORK */
513 else if (seq.getAllPDBEntries() != null
514 && seq.getAllPDBEntries().size() > 0)
516 structureFile = new File(
517 seq.getAllPDBEntries().elementAt(0).getFile());
518 if (structureFile != null)
520 Console.debug("Using structure file (from sequence) '"
521 + structureFile.getAbsolutePath() + "'");
523 structureFilename = structureFile.getAbsolutePath();
526 if (structureFilename == null || structureFile == null)
528 addWarn("Not provided structure file with '" + val + "'");
532 if (!structureFile.exists())
534 addWarn("Structure file '" + structureFile.getAbsoluteFile()
539 Console.debug("Using structure file "
540 + structureFile.getAbsolutePath());
542 argParser.setStructureFilename(structureFilename);
544 // open structure view
545 AlignmentPanel ap = af.alignPanel;
548 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
549 StructureViewer.ViewerType.JMOL.toString());
552 String structureFilepath = structureFile.getAbsolutePath();
554 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
555 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
556 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER,
557 structureAv, subVals, null, null, null);
558 if (paeFilepath != null)
560 File paeFile = new File(paeFilepath);
564 paeFilepath = paeFile.getCanonicalPath();
565 } catch (IOException e)
567 paeFilepath = paeFile.getAbsolutePath();
568 addWarn("Problem with the PAE file path: '"
569 + paeFile.getPath() + "'");
573 // showing annotations from structure file or not
574 boolean ssFromStructure = avm.getFromSubValArgOrPref(
575 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
578 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
579 // reference annotations
580 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
581 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER,
582 structureAv, subVals, null, null, null);
583 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
584 subVals, null, "ADD_TEMPFACT_ANN", false, true);
585 TFType tft = notempfac ? null : TFType.DEFAULT;
586 if (tftString != null && !notempfac)
588 // get kind of temperature factor annotation
591 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
592 Console.debug("Obtained Temperature Factor type of '" + tft
593 + "' for structure '" + structureFilepath + "'");
594 } catch (IllegalArgumentException e)
596 // Just an error message!
597 StringBuilder sb = new StringBuilder().append("Cannot set ")
598 .append(Arg.TEMPFAC.argString()).append(" to '")
600 .append("', ignoring. Valid values are: ");
601 Iterator<TFType> it = Arrays.stream(TFType.values())
605 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
609 addWarn(sb.toString());
613 String sViewerName = avm.getFromSubValArgOrPref(
614 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER,
615 structureAv, subVals, null, null, "jmol");
616 ViewerType viewerType = ViewerType.getFromString(sViewerName);
618 // TODO use ssFromStructure
619 StructureViewer structureViewer = StructureChooser
620 .openStructureFileForSequence(null, null, ap, seq, false,
621 structureFilepath, tft, paeFilepath, false,
622 ssFromStructure, false, viewerType);
624 if (structureViewer == null)
626 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
628 addError("Failed to import and open structure view for file '"
629 + structureFile + "'.");
636 while (structureViewer.isBusy() && tries > 0)
639 if (structureViewer.isBusy())
643 "Waiting for viewer for " + structureFilepath);
646 if (tries == 0 && structureViewer.isBusy())
648 addWarn("Gave up waiting for structure viewer to load file '"
650 + "'. Something may have gone wrong.");
652 } catch (Exception x)
654 addError("Exception whilst waiting for structure viewer "
655 + structureFilepath, x);
659 // add StructureViewer to svMap list
662 svMap = new HashMap<>();
664 if (svMap.get(id) == null)
666 svMap.put(id, new ArrayList<>());
668 svMap.get(id).add(structureViewer);
671 "Successfully opened viewer for " + structureFilepath);
673 if (avm.containsArg(Arg.STRUCTUREIMAGE))
675 for (ArgValue structureImageArgValue : avm
676 .getArgValueListFromSubValOrArg(structureAv,
677 Arg.STRUCTUREIMAGE, subVals))
679 String structureImageFilename = argParser.makeSubstitutions(
680 structureImageArgValue.getValue(), id, true);
681 if (structureViewer != null && structureImageFilename != null)
683 SubVals structureImageSubVals = null;
684 structureImageSubVals = structureImageArgValue.getSubVals();
685 File structureImageFile = new File(structureImageFilename);
686 String width = avm.getValueFromSubValOrArg(
687 structureImageArgValue, Arg.WIDTH,
688 structureImageSubVals);
689 String height = avm.getValueFromSubValOrArg(
690 structureImageArgValue, Arg.HEIGHT,
691 structureImageSubVals);
692 String scale = avm.getValueFromSubValOrArg(
693 structureImageArgValue, Arg.SCALE,
694 structureImageSubVals);
695 String renderer = avm.getValueFromSubValOrArg(
696 structureImageArgValue, Arg.TEXTRENDERER,
697 structureImageSubVals);
698 String typeS = avm.getValueFromSubValOrArg(
699 structureImageArgValue, Arg.TYPE,
700 structureImageSubVals);
701 if (typeS == null || typeS.length() == 0)
703 typeS = FileUtils.getExtension(structureImageFile);
708 imageType = Enum.valueOf(TYPE.class,
709 typeS.toUpperCase(Locale.ROOT));
710 } catch (IllegalArgumentException e)
712 addWarn("Do not know image format '" + typeS
714 imageType = TYPE.PNG;
716 BitmapImageSizing userBis = ImageMaker
717 .parseScaleWidthHeightStrings(scale, width, height);
720 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
721 if (viewerType != ViewerType.JMOL)
723 addWarn("Cannot export image for structure viewer "
724 + viewerType.name() + " yet");
729 // Apply the temporary colourscheme to the linked alignment
730 // TODO: enhance for multiple linked alignments.
732 String imageColour = avm.getValueFromSubValOrArg(
733 structureImageArgValue, Arg.IMAGECOLOUR,
734 structureImageSubVals);
735 ColourSchemeI originalColourScheme = this
736 .getColourScheme(af);
737 this.colourAlignFrame(af, imageColour);
740 // custom image background colour
742 String bgcolourstring = avm.getValueFromSubValOrArg(
743 structureImageArgValue, Arg.BGCOLOUR,
744 structureImageSubVals);
745 Color bgcolour = null;
746 if (bgcolourstring != null && bgcolourstring.length() > 0)
748 bgcolour = ColorUtils.parseColourString(bgcolourstring);
749 if (bgcolour == null)
752 "Background colour string '" + bgcolourstring
753 + "' not recognised -- using default");
757 JalviewStructureDisplayI sview = structureViewer
758 .getJalviewStructureDisplay();
760 File sessionToRestore = null;
762 List<StructureCommandI> extraCommands = new ArrayList<>();
764 if (extraCommands.size() > 0 || bgcolour != null)
768 sessionToRestore = sview.saveSession();
769 } catch (Throwable t)
772 "Unable to save temporary session file before custom structure view export operation.");
779 if (bgcolour != null)
781 sview.getBinding().setBackgroundColour(bgcolour);
784 sview.getBinding().executeCommands(extraCommands, false,
785 "Executing Custom Commands");
787 // and export the view as an image
788 boolean success = this.checksBeforeWritingToFile(avm,
789 subVals, false, structureImageFilename,
790 "structure image", isError);
796 Console.debug("Rendering image to " + structureImageFile);
798 // TODO - extend StructureViewer / Binding with makePDBImage so
799 // we can do this with every viewer
804 // We don't expect class cast exception
805 AppJmol jmol = (AppJmol) sview;
806 jmol.makePDBImage(structureImageFile, imageType, renderer,
808 Console.info("Exported structure image to "
809 + structureImageFile);
811 // RESTORE SESSION AFTER EXPORT IF NEED BE
812 if (sessionToRestore != null)
815 "Restoring session from " + sessionToRestore);
817 sview.getBinding().restoreSession(
818 sessionToRestore.getAbsolutePath());
821 } catch (ImageOutputException ioexec)
824 "Unexpected error when restoring structure viewer session after custom view operations.");
831 this.colourAlignFrame(af, originalColourScheme);
832 } catch (Exception t)
835 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
842 argParser.setStructureFilename(null);
851 // many of jalview's format/layout methods are only thread safe on the
852 // swingworker thread.
853 // all these methods should be on the alignViewController so it can
854 // coordinate such details
857 showOrHideAnnotations(af, showSSAnnotations, showAnnotations,
865 final boolean _showSSAnnotations = showSSAnnotations;
866 final boolean _showAnnotations = showAnnotations;
867 final boolean _hideTFrows = hideTFrows;
868 SwingUtilities.invokeAndWait(() -> {
869 showOrHideAnnotations(_af, _showSSAnnotations, _showAnnotations,
874 } catch (Exception x)
877 "Unexpected exception adjusting annotation row visibility.",
890 af.setWrapFormat(wrap, true);
895 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
898 AlignFrame af = afMap.get(id);
899 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
900 .findAnnotation(PDBChain.class.getName().toString()))
902 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
903 af.alignPanel.av.getGlobalColourScheme(), 0);
904 acg.setSeqAssociated(true);
905 af.changeColour(acg);
906 Console.info("Changed colour " + acg.toString());
911 return theseArgsWereParsed && !isError;
914 private static void showOrHideAnnotations(AlignFrame af,
915 boolean showSSAnnotations, boolean showAnnotations,
918 af.setAnnotationsVisibility(showSSAnnotations, true, false);
919 af.setAnnotationsVisibility(showAnnotations, false, true);
921 // show temperature factor annotations?
924 // do this better (annotation types?)
925 List<String> hideThese = new ArrayList<>();
926 hideThese.add("Temperature Factor");
927 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
928 AlignmentUtils.showOrHideSequenceAnnotations(
929 af.getCurrentView().getAlignment(), hideThese, null, false,
934 protected void processGroovyScript(String id)
936 ArgValuesMap avm = argParser.getLinkedArgs(id);
937 AlignFrame af = afMap.get(id);
939 if (avm != null && !avm.containsArg(Arg.GROOVY))
947 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
950 if (avm.containsArg(Arg.GROOVY))
952 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
954 String groovyscript = groovyAv.getValue();
955 if (groovyscript != null)
957 // Execute the groovy script after we've done all the rendering stuff
958 // and before any images or figures are generated.
959 Console.info("Executing script " + groovyscript);
960 Jalview.getInstance().executeGroovyScript(groovyscript, af);
966 protected boolean processImages(String id)
968 ArgValuesMap avm = argParser.getLinkedArgs(id);
969 AlignFrame af = afMap.get(id);
971 if (avm != null && !avm.containsArg(Arg.IMAGE))
979 addWarn("Do not have an alignment window to create image from (id="
980 + id + "). Not proceeding.");
984 Boolean isError = Boolean.valueOf(false);
985 if (avm.containsArg(Arg.IMAGE))
987 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
989 String val = imageAv.getValue();
990 SubVals imageSubVals = imageAv.getSubVals();
991 String fileName = imageSubVals.getContent();
992 File file = new File(fileName);
993 String name = af.getName();
994 String renderer = avm.getValueFromSubValOrArg(imageAv,
995 Arg.TEXTRENDERER, imageSubVals);
996 if (renderer == null)
998 String type = "png"; // default
1000 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
1002 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
1004 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
1006 BitmapImageSizing userBis = ImageMaker
1007 .parseScaleWidthHeightStrings(scale, width, height);
1009 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
1010 if (type == null && fileName != null)
1012 for (String ext : new String[] { "svg", "png", "html", "eps" })
1014 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1020 // for moment we disable JSON export
1021 Cache.setPropsAreReadOnly(true);
1022 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
1024 String imageColour = avm.getValueFromSubValOrArg(imageAv,
1025 Arg.IMAGECOLOUR, imageSubVals);
1026 ColourSchemeI originalColourScheme = this.getColourScheme(af);
1027 this.colourAlignFrame(af, imageColour);
1029 Console.info("Writing " + file);
1031 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
1032 false, fileName, "image", isError);
1044 Console.debug("Outputting type '" + type + "' to " + fileName);
1045 af.createSVG(file, renderer);
1049 Console.debug("Outputting type '" + type + "' to " + fileName);
1050 af.createPNG(file, null, userBis);
1054 Console.debug("Outputting type '" + type + "' to " + fileName);
1055 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1056 htmlSVG.exportHTML(fileName, renderer);
1061 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1064 BioJsHTMLOutput.refreshVersionInfo(
1065 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1066 } catch (URISyntaxException e)
1068 e.printStackTrace();
1070 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1071 bjs.exportHTML(fileName);
1075 Console.debug("Outputting EPS file: " + fileName);
1076 af.createEPS(file, renderer);
1080 Console.debug("Outputting ImageMap file: " + fileName);
1081 af.createImageMap(file, name);
1085 addWarn(Arg.IMAGE.argString() + " type '" + type
1086 + "' not known. Ignoring");
1089 } catch (Exception ioex)
1091 addError("Unexpected error during export to '" + fileName + "'",
1096 this.colourAlignFrame(af, originalColourScheme);
1102 protected boolean processOutput(String id)
1104 ArgValuesMap avm = argParser.getLinkedArgs(id);
1105 AlignFrame af = afMap.get(id);
1107 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1115 addWarn("Do not have an alignment window (id=" + id
1116 + "). Not proceeding.");
1120 Boolean isError = Boolean.valueOf(false);
1122 if (avm.containsArg(Arg.OUTPUT))
1124 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1126 String val = av.getValue();
1127 SubVals subVals = av.getSubVals();
1128 String fileName = subVals.getContent();
1129 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1130 File file = new File(fileName);
1132 String name = af.getName();
1133 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1135 FileFormats ffs = FileFormats.getInstance();
1136 List<String> validFormats = ffs.getWritableFormats(false);
1138 FileFormatI ff = null;
1139 if (format == null && fileName != null)
1141 FORMAT: for (String fname : validFormats)
1143 FileFormatI tff = ffs.forName(fname);
1144 String[] extensions = tff.getExtensions().split(",");
1145 for (String ext : extensions)
1147 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1150 format = ff.getName();
1156 if (ff == null && format != null)
1158 ff = ffs.forName(format);
1164 ff = FileFormat.Fasta;
1168 StringBuilder validSB = new StringBuilder();
1169 for (String f : validFormats)
1171 if (validSB.length() > 0)
1172 validSB.append(", ");
1174 FileFormatI tff = ffs.forName(f);
1175 validSB.append(" (");
1176 validSB.append(tff.getExtensions());
1177 validSB.append(")");
1180 addError("No valid format specified for "
1181 + Arg.OUTPUT.argString() + ". Valid formats are "
1182 + validSB.toString() + ".");
1187 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1188 fileName, ff.getName(), isError);
1194 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1195 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1196 !Platform.isHeadless());
1198 Console.info("Writing " + fileName);
1200 af.saveAlignment(fileName, ff, stdout, backups);
1201 if (af.isSaveAlignmentSuccessful())
1203 Console.debug("Written alignment '" + name + "' in "
1204 + ff.getName() + " format to '" + file + "'");
1208 addError("Error writing file '" + file + "' in " + ff.getName()
1219 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1222 SubVals subVals = av.getSubVals();
1223 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1224 SequenceI seq = null;
1225 if (subVals == null && idAv == null)
1227 if (af == null || af.getCurrentView() == null)
1231 AlignmentI al = af.getCurrentView().getAlignment();
1236 if (subVals != null)
1238 if (subVals.has(Arg.SEQID.getName()))
1240 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1242 else if (-1 < subVals.getIndex()
1243 && subVals.getIndex() < al.getSequences().size())
1245 seq = al.getSequenceAt(subVals.getIndex());
1248 if (seq == null && idAv != null)
1250 seq = al.findName(idAv.getValue());
1255 public AlignFrame[] getAlignFrames()
1257 AlignFrame[] afs = null;
1260 afs = (AlignFrame[]) afMap.values().toArray();
1266 public List<StructureViewer> getStructureViewers()
1268 List<StructureViewer> svs = null;
1271 for (List<StructureViewer> svList : svMap.values())
1275 svs = new ArrayList<>();
1283 private void colourAlignFrame(AlignFrame af, String colour)
1285 // use string "none" to remove colour scheme
1286 if (colour != null && "" != colour)
1288 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1289 af.getViewport(), af.getViewport().getAlignment(), colour);
1290 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1292 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1296 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1297 colourAlignFrame(af, cs);
1302 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1305 SwingUtilities.invokeAndWait(new Runnable()
1310 // Note that cs == null removes colour scheme from af
1311 af.changeColour(cs);
1313 }); } catch (Exception x) {
1314 Console.trace("Interrupted whilst waiting for colorAlignFrame action",x);
1319 private ColourSchemeI getColourScheme(AlignFrame af)
1321 return af.getViewport().getGlobalColourScheme();
1324 private void addInfo(String errorMessage)
1326 Console.info(errorMessage);
1327 errors.add(errorMessage);
1330 private void addWarn(String errorMessage)
1332 Console.warn(errorMessage);
1333 errors.add(errorMessage);
1336 private void addError(String errorMessage)
1338 addError(errorMessage, null);
1341 private void addError(String errorMessage, Exception e)
1343 Console.error(errorMessage, e);
1344 errors.add(errorMessage);
1347 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1348 SubVals subVal, boolean includeBackups, String filename,
1349 String adjective, Boolean isError)
1351 File file = new File(filename);
1353 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1354 null, "OVERWRITE_OUTPUT", false);
1355 boolean stdout = false;
1356 boolean backups = false;
1359 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1360 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1361 // otherwise if headless assume false, if not headless use the user
1362 // preference with default true.
1363 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1364 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1365 !Platform.isHeadless());
1368 if (file.exists() && !(overwrite || backups || stdout))
1370 addWarn("Won't overwrite file '" + filename + "' without "
1371 + Arg.OVERWRITE.argString()
1372 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1377 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1378 "MKDIRS_OUTPUT", false);
1380 if (!FileUtils.checkParentDir(file, mkdirs))
1382 addError("Directory '"
1383 + FileUtils.getParentDir(file).getAbsolutePath()
1384 + "' does not exist for " + adjective + " file '" + filename
1386 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1394 public List<String> getErrors()
1399 public String errorsToString()
1401 StringBuilder sb = new StringBuilder();
1402 for (String error : errors)
1404 if (sb.length() > 0)
1406 sb.append("- " + error);
1408 return sb.toString();