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.getInstance().exit(
183 "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 openFile = av.getValue();
240 if (openFile == null)
243 theseArgsWereParsed = true;
247 if (!headless && desktop != null)
249 SwingUtilities.invokeLater(new Runnable()
254 desktop.setProgressBar(
255 MessageManager.getString(
256 "status.processing_commandline_args"),
261 progressBarSet = true;
265 if (!Platform.isJS())
267 * ignore in JavaScript -- can't just file existence - could load it?
272 if (!HttpUtils.startsWithHttpOrHttps(openFile))
274 if (!(new File(openFile)).exists())
276 addError("Can't find file '" + openFile + "'");
283 DataSourceType protocol = AppletFormatAdapter
284 .checkProtocol(openFile);
286 FileFormatI format = null;
289 format = new IdentifyFile().identify(openFile, protocol);
290 } catch (FileFormatException e1)
292 addError("Unknown file format for '" + openFile + "'");
298 // When to open a new AlignFrame
299 if (af == null || "true".equals(av.getSubVal("new"))
300 || a == Arg.OPEN || format == FileFormat.Jalview)
304 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
309 "Opening '" + openFile + "' in new alignment frame");
310 FileLoader fileLoader = new FileLoader(!headless);
311 boolean xception = false;
314 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
316 } catch (Throwable thr)
319 addError("Couldn't open '" + openFile + "' as " + format + " "
320 + thr.getLocalizedMessage()
321 + " (Enable debug for full stack trace)");
323 Console.debug("Exception when opening '" + openFile + "'", thr);
326 if (af == null && !xception)
328 addInfo("Ignoring '" + openFile
329 + "' - no alignment data found.");
335 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
336 null, "DEFAULT_COLOUR_PROT", "");
337 this.colourAlignFrame(af, colour);
339 // Change alignment frame title
340 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
345 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
349 String featuresfile = avm.getValueFromSubValOrArg(av,
351 if (featuresfile != null)
353 af.parseFeaturesFile(featuresfile,
354 AppletFormatAdapter.checkProtocol(featuresfile));
355 Jalview.testoutput(argParser, Arg.FEATURES,
356 "examples/testdata/plantfdx.features", featuresfile);
359 // Add annotations from file
360 String annotationsfile = avm.getValueFromSubValOrArg(av,
361 Arg.ANNOTATIONS, sv);
362 if (annotationsfile != null)
364 af.loadJalviewDataFile(annotationsfile, null, null, null);
365 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
366 "examples/testdata/plantfdx.annotations",
370 // Set or clear the sortbytree flag
371 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
375 af.getViewport().setSortByTree(true);
376 Jalview.testoutput(argParser, Arg.SORTBYTREE);
379 // Load tree from file
380 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
381 if (treefile != null)
385 NewickFile nf = new NewickFile(treefile,
386 AppletFormatAdapter.checkProtocol(treefile));
387 af.getViewport().setCurrentTree(
388 af.showNewickTree(nf, treefile).getTree());
389 Jalview.testoutput(argParser, Arg.TREE,
390 "examples/testdata/uniref50_test_tree", treefile);
391 } catch (IOException e)
393 addError("Couldn't add tree " + treefile, e);
398 // Show secondary structure annotations?
399 showSSAnnotations = avm.getFromSubValArgOrPref(
400 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
401 "STRUCT_FROM_PDB", true);
402 // Show sequence annotations?
403 showAnnotations = avm.getFromSubValArgOrPref(Arg.SHOWANNOTATIONS,
404 av.getSubVals(), null, "SHOW_ANNOTATIONS", true);
405 // hide the Temperature Factor row?
406 hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
408 // showSSAnnotations, showAnnotations, hideTFrows used after opening
411 // wrap alignment? do this last for formatting reasons
412 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
413 "WRAP_ALIGNMENT", false);
414 // af.setWrapFormat(wrap) is applied after structures are opened for
415 // annotation reasons
417 // store the AlignFrame for this id
420 // is it its own structure file?
421 if (format.isStructureFile())
423 StructureSelectionManager ssm = StructureSelectionManager
424 .getStructureSelectionManager(Desktop.instance);
425 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
426 ssm.computeMapping(false, new SequenceI[] { seq }, null,
427 openFile, DataSourceType.FILE, null, null, null, false);
433 "Opening '" + openFile + "' in existing alignment frame");
435 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
437 : DataSourceType.FILE;
439 FileLoader fileLoader = new FileLoader(!headless);
440 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
444 Console.debug("Command " + Arg.APPEND + " executed successfully!");
447 if (first) // first=true means nothing opened
451 Jalview.exit("Could not open any files in headless mode",
456 Console.info("No more files to open");
459 if (progressBarSet && desktop != null)
460 desktop.setProgressBar(null, progress);
464 // open the structure (from same PDB file or given PDBfile)
465 if (!avm.getBoolean(Arg.NOSTRUCTURE))
471 if (avm.containsArg(Arg.STRUCTURE))
473 commandArgsProvided = true;
474 for (ArgValue structureAv : avm.getArgValueList(Arg.STRUCTURE))
476 argParser.setStructureFilename(null);
477 String val = structureAv.getValue();
478 SubVals subVals = structureAv.getSubVals();
479 int argIndex = structureAv.getArgIndex();
480 SequenceI seq = getSpecifiedSequence(af, avm, structureAv);
483 // Could not find sequence from subId, let's assume the first
484 // sequence in the alignframe
485 AlignmentI al = af.getCurrentView().getAlignment();
486 seq = al.getSequenceAt(0);
491 addWarn("Could not find sequence for argument "
492 + Arg.STRUCTURE.argString() + "=" + val);
495 String structureFilename = null;
496 File structureFile = null;
497 if (subVals.getContent() != null
498 && subVals.getContent().length() != 0)
500 structureFilename = subVals.getContent();
501 Console.debug("Using structure file (from argument) '"
502 + structureFilename + "'");
503 structureFile = new File(structureFilename);
505 /* THIS DOESN'T WORK */
506 else if (seq.getAllPDBEntries() != null
507 && seq.getAllPDBEntries().size() > 0)
509 structureFile = new File(
510 seq.getAllPDBEntries().elementAt(0).getFile());
511 if (structureFile != null)
513 Console.debug("Using structure file (from sequence) '"
514 + structureFile.getAbsolutePath() + "'");
516 structureFilename = structureFile.getAbsolutePath();
519 if (structureFilename == null || structureFile == null)
521 addWarn("Not provided structure file with '" + val + "'");
525 if (!structureFile.exists())
527 addWarn("Structure file '" + structureFile.getAbsoluteFile()
532 Console.debug("Using structure file "
533 + structureFile.getAbsolutePath());
535 argParser.setStructureFilename(structureFilename);
537 // open structure view
538 AlignmentPanel ap = af.alignPanel;
541 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
542 StructureViewer.ViewerType.JMOL.toString());
545 String structureFilepath = structureFile.getAbsolutePath();
547 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
548 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
549 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER,
550 structureAv, subVals, null, null, null);
551 if (paeFilepath != null)
553 File paeFile = new File(paeFilepath);
557 paeFilepath = paeFile.getCanonicalPath();
558 } catch (IOException e)
560 paeFilepath = paeFile.getAbsolutePath();
561 addWarn("Problem with the PAE file path: '"
562 + paeFile.getPath() + "'");
566 // showing annotations from structure file or not
567 boolean ssFromStructure = avm.getFromSubValArgOrPref(
568 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
571 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
572 // reference annotations
573 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
574 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER,
575 structureAv, subVals, null, null, null);
576 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
577 subVals, null, "ADD_TEMPFACT_ANN", false, true);
578 TFType tft = notempfac ? null : TFType.DEFAULT;
579 if (tftString != null && !notempfac)
581 // get kind of temperature factor annotation
584 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
585 Console.debug("Obtained Temperature Factor type of '" + tft
586 + "' for structure '" + structureFilepath + "'");
587 } catch (IllegalArgumentException e)
589 // Just an error message!
590 StringBuilder sb = new StringBuilder().append("Cannot set ")
591 .append(Arg.TEMPFAC.argString()).append(" to '")
593 .append("', ignoring. Valid values are: ");
594 Iterator<TFType> it = Arrays.stream(TFType.values())
598 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
602 addWarn(sb.toString());
606 String sViewerName = avm.getFromSubValArgOrPref(
607 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER,
608 structureAv, subVals, null, null, "jmol");
609 ViewerType viewerType = ViewerType.getFromString(sViewerName);
611 // TODO use ssFromStructure
612 StructureViewer structureViewer = StructureChooser
613 .openStructureFileForSequence(null, null, ap, seq, false,
614 structureFilepath, tft, paeFilepath, false,
615 ssFromStructure, false, viewerType);
617 if (structureViewer == null)
619 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
621 addError("Failed to import and open structure view for file '"
622 + structureFile + "'.");
629 while (structureViewer.isBusy() && tries > 0)
632 if (structureViewer.isBusy())
636 "Waiting for viewer for " + structureFilepath);
639 if (tries == 0 && structureViewer.isBusy())
641 addWarn("Gave up waiting for structure viewer to load file '"
643 + "'. Something may have gone wrong.");
645 } catch (Exception x)
647 addError("Exception whilst waiting for structure viewer "
648 + structureFilepath, x);
652 // add StructureViewer to svMap list
655 svMap = new HashMap<>();
657 if (svMap.get(id) == null)
659 svMap.put(id, new ArrayList<>());
661 svMap.get(id).add(structureViewer);
664 "Successfully opened viewer for " + structureFilepath);
666 if (avm.containsArg(Arg.STRUCTUREIMAGE))
668 for (ArgValue structureImageArgValue : avm
669 .getArgValueListFromSubValOrArg(structureAv,
670 Arg.STRUCTUREIMAGE, subVals))
672 String structureImageFilename = argParser.makeSubstitutions(
673 structureImageArgValue.getValue(), id, true);
674 if (structureViewer != null && structureImageFilename != null)
676 SubVals structureImageSubVals = null;
677 structureImageSubVals = structureImageArgValue.getSubVals();
678 File structureImageFile = new File(structureImageFilename);
679 String width = avm.getValueFromSubValOrArg(
680 structureImageArgValue, Arg.WIDTH,
681 structureImageSubVals);
682 String height = avm.getValueFromSubValOrArg(
683 structureImageArgValue, Arg.HEIGHT,
684 structureImageSubVals);
685 String scale = avm.getValueFromSubValOrArg(
686 structureImageArgValue, Arg.SCALE,
687 structureImageSubVals);
688 String renderer = avm.getValueFromSubValOrArg(
689 structureImageArgValue, Arg.TEXTRENDERER,
690 structureImageSubVals);
691 String typeS = avm.getValueFromSubValOrArg(
692 structureImageArgValue, Arg.TYPE,
693 structureImageSubVals);
694 if (typeS == null || typeS.length() == 0)
696 typeS = FileUtils.getExtension(structureImageFile);
701 imageType = Enum.valueOf(TYPE.class,
702 typeS.toUpperCase(Locale.ROOT));
703 } catch (IllegalArgumentException e)
705 addWarn("Do not know image format '" + typeS
707 imageType = TYPE.PNG;
709 BitmapImageSizing userBis = ImageMaker
710 .parseScaleWidthHeightStrings(scale, width, height);
713 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
714 if (viewerType != ViewerType.JMOL)
716 addWarn("Cannot export image for structure viewer "
717 + viewerType.name() + " yet");
722 // Apply the temporary colourscheme to the linked alignment
723 // TODO: enhance for multiple linked alignments.
725 String imageColour = avm.getValueFromSubValOrArg(
726 structureImageArgValue, Arg.IMAGECOLOUR,
727 structureImageSubVals);
728 ColourSchemeI originalColourScheme = this
729 .getColourScheme(af);
730 this.colourAlignFrame(af, imageColour);
733 // custom image background colour
735 String bgcolourstring = avm.getValueFromSubValOrArg(
736 structureImageArgValue, Arg.BGCOLOUR,
737 structureImageSubVals);
738 Color bgcolour = null;
739 if (bgcolourstring != null && bgcolourstring.length() > 0)
741 bgcolour = ColorUtils.parseColourString(bgcolourstring);
742 if (bgcolour == null)
745 "Background colour string '" + bgcolourstring
746 + "' not recognised -- using default");
750 JalviewStructureDisplayI sview = structureViewer
751 .getJalviewStructureDisplay();
753 File sessionToRestore = null;
755 List<StructureCommandI> extraCommands = new ArrayList<>();
757 if (extraCommands.size() > 0 || bgcolour != null)
761 sessionToRestore = sview.saveSession();
762 } catch (Throwable t)
765 "Unable to save temporary session file before custom structure view export operation.");
772 if (bgcolour != null)
774 sview.getBinding().setBackgroundColour(bgcolour);
777 sview.getBinding().executeCommands(extraCommands, false,
778 "Executing Custom Commands");
780 // and export the view as an image
781 boolean success = this.checksBeforeWritingToFile(avm,
782 subVals, false, structureImageFilename,
783 "structure image", isError);
789 Console.debug("Rendering image to " + structureImageFile);
791 // TODO - extend StructureViewer / Binding with makePDBImage so
792 // we can do this with every viewer
797 // We don't expect class cast exception
798 AppJmol jmol = (AppJmol) sview;
799 jmol.makePDBImage(structureImageFile, imageType, renderer,
801 Console.info("Exported structure image to "
802 + structureImageFile);
804 // RESTORE SESSION AFTER EXPORT IF NEED BE
805 if (sessionToRestore != null)
808 "Restoring session from " + sessionToRestore);
810 sview.getBinding().restoreSession(
811 sessionToRestore.getAbsolutePath());
814 } catch (ImageOutputException ioexec)
817 "Unexpected error when restoring structure viewer session after custom view operations.");
824 this.colourAlignFrame(af, originalColourScheme);
825 } catch (Exception t)
828 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
835 argParser.setStructureFilename(null);
844 // many of jalview's format/layout methods are only thread safe on the
845 // swingworker thread.
846 // all these methods should be on the alignViewController so it can
847 // coordinate such details
850 showOrHideAnnotations(af, showSSAnnotations, showAnnotations,
858 final boolean _showSSAnnotations = showSSAnnotations;
859 final boolean _showAnnotations = showAnnotations;
860 final boolean _hideTFrows = hideTFrows;
861 SwingUtilities.invokeAndWait(() -> {
862 showOrHideAnnotations(_af, _showSSAnnotations, _showAnnotations,
867 } catch (Exception x)
870 "Unexpected exception adjusting annotation row visibility.",
883 af.setWrapFormat(wrap, true);
888 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
891 AlignFrame af = afMap.get(id);
892 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
893 .findAnnotation(PDBChain.class.getName().toString()))
895 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
896 af.alignPanel.av.getGlobalColourScheme(), 0);
897 acg.setSeqAssociated(true);
898 af.changeColour(acg);
899 Console.info("Changed colour " + acg.toString());
904 return theseArgsWereParsed && !isError;
907 private static void showOrHideAnnotations(AlignFrame af,
908 boolean showSSAnnotations, boolean showAnnotations,
911 af.setAnnotationsVisibility(true, showSSAnnotations, showAnnotations);
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();