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.IdUtils;
79 import jalview.util.IdUtils.IdType;
80 import jalview.util.ImageMaker;
81 import jalview.util.ImageMaker.TYPE;
82 import jalview.util.MessageManager;
83 import jalview.util.Platform;
84 import jalview.util.StringUtils;
85 import jalview.util.imagemaker.BitmapImageSizing;
91 private boolean headless;
93 private ArgParser argParser;
95 private Map<String, AlignFrame> afMap;
97 private Map<String, List<StructureViewer>> svMap;
99 private boolean commandArgsProvided = false;
101 private boolean argsWereParsed = false;
103 private List<String> errors = new ArrayList<>();
105 public Commands(ArgParser argparser, boolean headless)
107 this(Desktop.instance, argparser, headless);
110 public Commands(Desktop d, ArgParser argparser, boolean h)
112 argParser = argparser;
115 afMap = new HashMap<>();
118 protected boolean processArgs()
120 if (argParser == null)
125 boolean theseArgsWereParsed = false;
127 if (argParser != null && argParser.getLinkedIds() != null)
129 for (String id : argParser.getLinkedIds())
131 ArgValuesMap avm = argParser.getLinkedArgs(id);
132 theseArgsWereParsed = true;
133 boolean processLinkedOkay = processLinked(id);
134 theseArgsWereParsed &= processLinkedOkay;
136 processGroovyScript(id);
138 // wait around until alignFrame isn't busy
139 AlignFrame af = afMap.get(id);
140 while (af != null && af.getViewport().isCalcInProgress())
145 } catch (Exception q)
151 theseArgsWereParsed &= processImages(id);
153 if (processLinkedOkay)
155 theseArgsWereParsed &= processOutput(id);
159 if (avm.getBoolean(Arg.CLOSE))
164 af.closeMenuItem_actionPerformed(true);
172 // report errors - if any
173 String errorsRaised = errorsToString();
174 if (errorsRaised.trim().length() > 0)
177 "The following errors and warnings occurred whilst processing files:\n"
180 // gui errors reported in Jalview
182 if (argParser.getBoolean(Arg.QUIT))
184 Jalview.getInstance().exit(
185 "Exiting due to " + Arg.QUIT.argString() + " argument.",
189 // carry on with jalview.bin.Jalview
190 argsWereParsed = theseArgsWereParsed;
191 return argsWereParsed;
194 public boolean commandArgsProvided()
196 return commandArgsProvided;
199 public boolean argsWereParsed()
201 return argsWereParsed;
204 protected boolean processLinked(String id)
206 boolean theseArgsWereParsed = false;
207 ArgValuesMap avm = argParser.getLinkedArgs(id);
213 Boolean isError = Boolean.valueOf(false);
215 // set wrap scope here so it can be applied after structures are opened
216 boolean wrap = false;
218 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
220 commandArgsProvided = true;
221 final long progress = IdUtils.newId(IdType.PROGRESS);
223 boolean first = true;
224 boolean progressBarSet = false;
226 // Combine the APPEND and OPEN files into one list, along with whether it
227 // was APPEND or OPEN
228 List<ArgValue> openAvList = new ArrayList<>();
229 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
230 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
231 // sort avlist based on av.getArgIndex()
232 Collections.sort(openAvList);
233 for (ArgValue av : openAvList)
236 SubVals sv = av.getSubVals();
237 String openFile = av.getValue();
238 if (openFile == null)
241 theseArgsWereParsed = true;
245 if (!headless && desktop != null)
247 SwingUtilities.invokeLater(new Runnable()
252 desktop.setProgressBar(
253 MessageManager.getString(
254 "status.processing_commandline_args"),
259 progressBarSet = true;
263 if (!Platform.isJS())
265 * ignore in JavaScript -- can't just file existence - could load it?
270 if (!HttpUtils.startsWithHttpOrHttps(openFile))
272 if (!(new File(openFile)).exists())
274 addError("Can't find file '" + openFile + "'");
281 DataSourceType protocol = AppletFormatAdapter
282 .checkProtocol(openFile);
284 FileFormatI format = null;
287 format = new IdentifyFile().identify(openFile, protocol);
288 } catch (FileFormatException e1)
290 addError("Unknown file format for '" + openFile + "'");
296 // When to open a new AlignFrame
297 if (af == null || "true".equals(av.getSubVal("new"))
298 || a == Arg.OPEN || format == FileFormat.Jalview)
302 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
307 "Opening '" + openFile + "' in new alignment frame");
308 FileLoader fileLoader = new FileLoader(!headless);
309 boolean xception = false;
312 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
314 } catch (Throwable thr)
317 addError("Couldn't open '" + openFile + "' as " + format + " "
318 + thr.getLocalizedMessage()
319 + " (Enable debug for full stack trace)");
321 Console.debug("Exception when opening '" + openFile + "'", thr);
324 if (af == null && !xception)
326 addInfo("Ignoring '" + openFile
327 + "' - no alignment data found.");
333 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
334 null, "DEFAULT_COLOUR_PROT", "");
335 this.colourAlignFrame(af, colour);
337 // Change alignment frame title
338 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
343 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
347 String featuresfile = avm.getValueFromSubValOrArg(av,
349 if (featuresfile != null)
351 af.parseFeaturesFile(featuresfile,
352 AppletFormatAdapter.checkProtocol(featuresfile));
353 Jalview.testoutput(argParser, Arg.FEATURES,
354 "examples/testdata/plantfdx.features", featuresfile);
357 // Add annotations from file
358 String annotationsfile = avm.getValueFromSubValOrArg(av,
359 Arg.ANNOTATIONS, sv);
360 if (annotationsfile != null)
362 af.loadJalviewDataFile(annotationsfile, null, null, null);
363 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
364 "examples/testdata/plantfdx.annotations",
368 // Set or clear the sortbytree flag
369 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
373 af.getViewport().setSortByTree(true);
374 Jalview.testoutput(argParser, Arg.SORTBYTREE);
377 // Load tree from file
378 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
379 if (treefile != null)
383 NewickFile nf = new NewickFile(treefile,
384 AppletFormatAdapter.checkProtocol(treefile));
385 af.getViewport().setCurrentTree(
386 af.showNewickTree(nf, treefile).getTree());
387 Jalview.testoutput(argParser, Arg.TREE,
388 "examples/testdata/uniref50_test_tree", treefile);
389 } catch (IOException e)
391 addError("Couldn't add tree " + treefile, e);
396 // Show secondary structure annotations?
397 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
398 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
399 "STRUCT_FROM_PDB", true);
401 // Show sequence annotations?
402 boolean showAnnotations = avm.getFromSubValArgOrPref(
403 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
404 "SHOW_ANNOTATIONS", true);
406 boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
407 final AlignFrame _af = af;
408 // many of jalview's format/layout methods are only thread safe on the
409 // swingworker thread.
410 // all these methods should be on the alignViewController so it can
411 // coordinate such details
414 SwingUtilities.invokeAndWait(new Runnable()
420 _af.setAnnotationsVisibility(showSSAnnotations, true,
423 _af.setAnnotationsVisibility(showAnnotations, false, true);
425 // show temperature factor annotations?
428 // do this better (annotation types?)
429 List<String> hideThese = new ArrayList<>();
430 hideThese.add("Temperature Factor");
431 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
432 AlignmentUtils.showOrHideSequenceAnnotations(
433 _af.getCurrentView().getAlignment(), hideThese,
438 } catch (Exception x)
441 "Unexpected exception adjusting annotation row visibility.",
445 // wrap alignment? do this last for formatting reasons
446 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
447 "WRAP_ALIGNMENT", false);
448 // af.setWrapFormat(wrap) is applied after structures are opened for
449 // annotation reasons
451 // store the AlignFrame for this id
454 // is it its own structure file?
455 if (format.isStructureFile())
457 StructureSelectionManager ssm = StructureSelectionManager
458 .getStructureSelectionManager(Desktop.instance);
459 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
460 ssm.computeMapping(false, new SequenceI[] { seq }, null,
461 openFile, DataSourceType.FILE, null, null, null, false);
467 "Opening '" + openFile + "' in existing alignment frame");
469 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
471 : DataSourceType.FILE;
473 FileLoader fileLoader = new FileLoader(!headless);
474 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
478 Console.debug("Command " + Arg.APPEND + " executed successfully!");
481 if (first) // first=true means nothing opened
485 Jalview.exit("Could not open any files in headless mode",
490 Console.info("No more files to open");
493 if (progressBarSet && desktop != null)
495 desktop.setProgressBar(null, progress);
499 // open the structure (from same PDB file or given PDBfile)
500 if (!avm.getBoolean(Arg.NOSTRUCTURE))
503 AlignFrame af = afMap.get(id);
504 if (avm.containsArg(Arg.STRUCTURE))
506 commandArgsProvided = true;
509 ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
511 argParser.setStructureFilename(null);
512 String val = av.getValue();
513 SubVals subVals = av.getSubVals();
514 int argIndex = av.getArgIndex();
515 SequenceI seq = getSpecifiedSequence(af, avm, av);
518 // Could not find sequence from subId, let's assume the first
519 // sequence in the alignframe
520 AlignmentI al = af.getCurrentView().getAlignment();
521 seq = al.getSequenceAt(0);
526 addWarn("Could not find sequence for argument "
527 + Arg.STRUCTURE.argString() + "=" + val);
530 String structureFilename = null;
531 File structureFile = null;
532 if (subVals.getContent() != null
533 && subVals.getContent().length() != 0)
535 structureFilename = subVals.getContent();
536 Console.debug("Using structure file (from argument) '"
537 + structureFilename + "'");
538 structureFile = new File(structureFilename);
540 /* THIS DOESN'T WORK */
541 else if (seq.getAllPDBEntries() != null
542 && seq.getAllPDBEntries().size() > 0)
544 structureFile = new File(
545 seq.getAllPDBEntries().elementAt(0).getFile());
546 if (structureFile != null)
548 Console.debug("Using structure file (from sequence) '"
549 + structureFile.getAbsolutePath() + "'");
551 structureFilename = structureFile.getAbsolutePath();
554 if (structureFilename == null || structureFile == null)
556 addWarn("Not provided structure file with '" + val + "'");
560 if (!structureFile.exists())
562 addWarn("Structure file '" + structureFile.getAbsoluteFile()
567 Console.debug("Using structure file "
568 + structureFile.getAbsolutePath());
570 argParser.setStructureFilename(structureFilename);
572 // open structure view
573 AlignmentPanel ap = af.alignPanel;
576 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
577 StructureViewer.ViewerType.JMOL.toString());
580 String structureFilepath = structureFile.getAbsolutePath();
582 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
583 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
584 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
585 subVals, null, null, null);
586 if (paeFilepath != null)
588 File paeFile = new File(paeFilepath);
592 paeFilepath = paeFile.getCanonicalPath();
593 } catch (IOException e)
595 paeFilepath = paeFile.getAbsolutePath();
596 addWarn("Problem with the PAE file path: '"
597 + paeFile.getPath() + "'");
601 // showing annotations from structure file or not
602 boolean ssFromStructure = avm.getFromSubValArgOrPref(
603 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
606 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
607 // reference annotations
608 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
609 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
610 subVals, null, null, null);
611 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
612 subVals, null, "ADD_TEMPFACT_ANN", false, true);
613 TFType tft = notempfac ? null : TFType.DEFAULT;
614 if (tftString != null && !notempfac)
616 // get kind of temperature factor annotation
619 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
620 Console.debug("Obtained Temperature Factor type of '" + tft
621 + "' for structure '" + structureFilepath + "'");
622 } catch (IllegalArgumentException e)
624 // Just an error message!
625 StringBuilder sb = new StringBuilder().append("Cannot set ")
626 .append(Arg.TEMPFAC.argString()).append(" to '")
628 .append("', ignoring. Valid values are: ");
629 Iterator<TFType> it = Arrays.stream(TFType.values())
633 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
637 addWarn(sb.toString());
641 String sViewerName = avm.getFromSubValArgOrPref(
642 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
643 subVals, null, null, "jmol");
644 ViewerType viewerType = ViewerType.getFromString(sViewerName);
646 // TODO use ssFromStructure
647 StructureViewer structureViewer = StructureChooser
648 .openStructureFileForSequence(null, null, ap, seq, false,
649 structureFilepath, tft, paeFilepath, false,
650 ssFromStructure, false, viewerType);
652 if (structureViewer == null)
654 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
656 addError("Failed to import and open structure view for file '"
657 + structureFile + "'.");
664 while (structureViewer.isBusy() && tries > 0)
667 if (structureViewer.isBusy())
671 "Waiting for viewer for " + structureFilepath);
674 if (tries == 0 && structureViewer.isBusy())
676 addWarn("Gave up waiting for structure viewer to load file '"
678 + "'. Something may have gone wrong.");
680 } catch (Exception x)
682 addError("Exception whilst waiting for structure viewer "
683 + structureFilepath, x);
687 // add StructureViewer to svMap list
690 svMap = new HashMap<>();
692 if (svMap.get(id) == null)
694 svMap.put(id, new ArrayList<>());
696 svMap.get(id).add(structureViewer);
699 "Successfully opened viewer for " + structureFilepath);
701 if (avm.containsArg(Arg.STRUCTUREIMAGE))
703 for (ArgValue structureImageArgValue : avm
704 .getArgValueList(Arg.STRUCTUREIMAGE))
706 String structureImageFilename = argParser.makeSubstitutions(
707 structureImageArgValue.getValue(), id, true);
708 if (structureViewer != null && structureImageFilename != null)
710 SubVals structureImageSubVals = null;
711 structureImageSubVals = structureImageArgValue.getSubVals();
712 File structureImageFile = new File(structureImageFilename);
713 String width = avm.getValueFromSubValOrArg(
714 structureImageArgValue, Arg.WIDTH,
715 structureImageSubVals);
716 String height = avm.getValueFromSubValOrArg(
717 structureImageArgValue, Arg.HEIGHT,
718 structureImageSubVals);
719 String scale = avm.getValueFromSubValOrArg(
720 structureImageArgValue, Arg.SCALE,
721 structureImageSubVals);
722 String renderer = avm.getValueFromSubValOrArg(
723 structureImageArgValue, Arg.TEXTRENDERER,
724 structureImageSubVals);
725 String typeS = avm.getValueFromSubValOrArg(
726 structureImageArgValue, Arg.TYPE,
727 structureImageSubVals);
728 if (typeS == null || typeS.length() == 0)
730 typeS = FileUtils.getExtension(structureImageFile);
735 imageType = Enum.valueOf(TYPE.class,
736 typeS.toUpperCase(Locale.ROOT));
737 } catch (IllegalArgumentException e)
739 addWarn("Do not know image format '" + typeS
741 imageType = TYPE.PNG;
743 BitmapImageSizing userBis = ImageMaker
744 .parseScaleWidthHeightStrings(scale, width, height);
747 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
748 if (viewerType != ViewerType.JMOL)
750 addWarn("Cannot export image for structure viewer "
751 + viewerType.name() + " yet");
756 // Apply the temporary colourscheme to the linked alignment
757 // TODO: enhance for multiple linked alignments.
759 String imageColour = avm.getValueFromSubValOrArg(
760 structureImageArgValue, Arg.IMAGECOLOUR,
761 structureImageSubVals);
762 ColourSchemeI originalColourScheme = this
763 .getColourScheme(af);
764 this.colourAlignFrame(af, imageColour);
767 // custom image background colour
769 String bgcolourstring = avm.getValueFromSubValOrArg(
770 structureImageArgValue, Arg.BGCOLOUR,
771 structureImageSubVals);
772 Color bgcolour = null;
773 if (bgcolourstring != null && bgcolourstring.length() > 0)
775 bgcolour = ColorUtils.parseColourString(bgcolourstring);
776 if (bgcolour == null)
779 "Background colour string '" + bgcolourstring
780 + "' not recognised -- using default");
784 JalviewStructureDisplayI sview = structureViewer
785 .getJalviewStructureDisplay();
787 File sessionToRestore = null;
789 List<StructureCommandI> extraCommands = new ArrayList<>();
791 if (extraCommands.size() > 0 || bgcolour != null)
795 sessionToRestore = sview.saveSession();
796 } catch (Throwable t)
799 "Unable to save temporary session file before custom structure view export operation.");
806 if (bgcolour != null)
808 sview.getBinding().setBackgroundColour(bgcolour);
811 sview.getBinding().executeCommands(extraCommands, false,
812 "Executing Custom Commands");
814 // and export the view as an image
815 boolean success = this.checksBeforeWritingToFile(avm,
816 subVals, false, structureImageFilename,
817 "structure image", isError);
823 Console.debug("Rendering image to " + structureImageFile);
825 // TODO - extend StructureViewer / Binding with makePDBImage so
826 // we can do this with every viewer
831 // We don't expect class cast exception
832 AppJmol jmol = (AppJmol) sview;
833 jmol.makePDBImage(structureImageFile, imageType, renderer,
835 Console.info("Exported structure image to "
836 + structureImageFile);
838 // RESTORE SESSION AFTER EXPORT IF NEED BE
839 if (sessionToRestore != null)
842 "Restoring session from " + sessionToRestore);
844 sview.getBinding().restoreSession(
845 sessionToRestore.getAbsolutePath());
848 } catch (ImageOutputException ioexec)
851 "Unexpected error when restoring structure viewer session after custom view operations.");
858 this.colourAlignFrame(af, originalColourScheme);
859 } catch (Exception t)
862 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
869 argParser.setStructureFilename(null);
877 AlignFrame af = afMap.get(id);
880 af.setWrapFormat(wrap, true);
885 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
888 AlignFrame af = afMap.get(id);
889 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
890 .findAnnotation(PDBChain.class.getName().toString()))
892 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
893 af.alignPanel.av.getGlobalColourScheme(), 0);
894 acg.setSeqAssociated(true);
895 af.changeColour(acg);
896 Console.info("Changed colour " + acg.toString());
901 return theseArgsWereParsed && !isError;
904 protected void processGroovyScript(String id)
906 ArgValuesMap avm = argParser.getLinkedArgs(id);
907 AlignFrame af = afMap.get(id);
909 if (avm != null && !avm.containsArg(Arg.GROOVY))
917 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
920 if (avm.containsArg(Arg.GROOVY))
922 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
924 String groovyscript = groovyAv.getValue();
925 if (groovyscript != null)
927 // Execute the groovy script after we've done all the rendering stuff
928 // and before any images or figures are generated.
929 Console.info("Executing script " + groovyscript);
930 Jalview.getInstance().executeGroovyScript(groovyscript, af);
936 protected boolean processImages(String id)
938 ArgValuesMap avm = argParser.getLinkedArgs(id);
939 AlignFrame af = afMap.get(id);
941 if (avm != null && !avm.containsArg(Arg.IMAGE))
949 addWarn("Do not have an alignment window to create image from (id="
950 + id + "). Not proceeding.");
954 Boolean isError = Boolean.valueOf(false);
955 if (avm.containsArg(Arg.IMAGE))
957 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
959 String val = imageAv.getValue();
960 SubVals imageSubVals = imageAv.getSubVals();
961 String fileName = imageSubVals.getContent();
962 File file = new File(fileName);
963 String name = af.getName();
964 String renderer = avm.getValueFromSubValOrArg(imageAv,
965 Arg.TEXTRENDERER, imageSubVals);
966 if (renderer == null)
968 String type = "png"; // default
970 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
972 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
974 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
976 BitmapImageSizing userBis = ImageMaker
977 .parseScaleWidthHeightStrings(scale, width, height);
979 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
980 if (type == null && fileName != null)
982 for (String ext : new String[] { "svg", "png", "html", "eps" })
984 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
990 // for moment we disable JSON export
991 Cache.setPropsAreReadOnly(true);
992 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
994 String imageColour = avm.getValueFromSubValOrArg(imageAv,
995 Arg.IMAGECOLOUR, imageSubVals);
996 ColourSchemeI originalColourScheme = this.getColourScheme(af);
997 this.colourAlignFrame(af, imageColour);
999 Console.info("Writing " + file);
1001 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
1002 false, fileName, "image", isError);
1014 Console.debug("Outputting type '" + type + "' to " + fileName);
1015 af.createSVG(file, renderer);
1019 Console.debug("Outputting type '" + type + "' to " + fileName);
1020 af.createPNG(file, null, userBis);
1024 Console.debug("Outputting type '" + type + "' to " + fileName);
1025 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1026 htmlSVG.exportHTML(fileName, renderer);
1031 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1034 BioJsHTMLOutput.refreshVersionInfo(
1035 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1036 } catch (URISyntaxException e)
1038 e.printStackTrace();
1040 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1041 bjs.exportHTML(fileName);
1045 Console.debug("Outputting EPS file: " + fileName);
1046 af.createEPS(file, renderer);
1050 Console.debug("Outputting ImageMap file: " + fileName);
1051 af.createImageMap(file, name);
1055 addWarn(Arg.IMAGE.argString() + " type '" + type
1056 + "' not known. Ignoring");
1059 } catch (Exception ioex)
1061 addError("Unexpected error during export to '" + fileName + "'",
1066 this.colourAlignFrame(af, originalColourScheme);
1072 protected boolean processOutput(String id)
1074 ArgValuesMap avm = argParser.getLinkedArgs(id);
1075 AlignFrame af = afMap.get(id);
1077 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1085 addWarn("Do not have an alignment window (id=" + id
1086 + "). Not proceeding.");
1090 Boolean isError = Boolean.valueOf(false);
1092 if (avm.containsArg(Arg.OUTPUT))
1094 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1096 String val = av.getValue();
1097 SubVals subVals = av.getSubVals();
1098 String fileName = subVals.getContent();
1099 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1100 File file = new File(fileName);
1102 String name = af.getName();
1103 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1105 FileFormats ffs = FileFormats.getInstance();
1106 List<String> validFormats = ffs.getWritableFormats(false);
1108 FileFormatI ff = null;
1109 if (format == null && fileName != null)
1111 FORMAT: for (String fname : validFormats)
1113 FileFormatI tff = ffs.forName(fname);
1114 String[] extensions = tff.getExtensions().split(",");
1115 for (String ext : extensions)
1117 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1120 format = ff.getName();
1126 if (ff == null && format != null)
1128 ff = ffs.forName(format);
1134 ff = FileFormat.Fasta;
1138 StringBuilder validSB = new StringBuilder();
1139 for (String f : validFormats)
1141 if (validSB.length() > 0)
1142 validSB.append(", ");
1144 FileFormatI tff = ffs.forName(f);
1145 validSB.append(" (");
1146 validSB.append(tff.getExtensions());
1147 validSB.append(")");
1150 addError("No valid format specified for "
1151 + Arg.OUTPUT.argString() + ". Valid formats are "
1152 + validSB.toString() + ".");
1157 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1158 fileName, ff.getName(), isError);
1164 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1165 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1166 !Platform.isHeadless());
1168 Console.info("Writing " + fileName);
1170 af.saveAlignment(fileName, ff, stdout, backups);
1171 if (af.isSaveAlignmentSuccessful())
1173 Console.debug("Written alignment '" + name + "' in "
1174 + ff.getName() + " format to '" + file + "'");
1178 addError("Error writing file '" + file + "' in " + ff.getName()
1189 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1192 SubVals subVals = av.getSubVals();
1193 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1194 SequenceI seq = null;
1195 if (subVals == null && idAv == null)
1197 if (af == null || af.getCurrentView() == null)
1201 AlignmentI al = af.getCurrentView().getAlignment();
1206 if (subVals != null)
1208 if (subVals.has(Arg.SEQID.getName()))
1210 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1212 else if (-1 < subVals.getIndex()
1213 && subVals.getIndex() < al.getSequences().size())
1215 seq = al.getSequenceAt(subVals.getIndex());
1218 if (seq == null && idAv != null)
1220 seq = al.findName(idAv.getValue());
1225 public AlignFrame[] getAlignFrames()
1227 AlignFrame[] afs = null;
1230 afs = (AlignFrame[]) afMap.values().toArray();
1236 public List<StructureViewer> getStructureViewers()
1238 List<StructureViewer> svs = null;
1241 for (List<StructureViewer> svList : svMap.values())
1245 svs = new ArrayList<>();
1253 private void colourAlignFrame(AlignFrame af, String colour)
1255 // use string "none" to remove colour scheme
1256 if (colour != null && "" != colour)
1258 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1259 af.getViewport(), af.getViewport().getAlignment(), colour);
1260 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1262 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1266 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1267 colourAlignFrame(af, cs);
1272 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1274 // Note that cs == null removes colour scheme from af
1275 af.changeColour(cs);
1278 private ColourSchemeI getColourScheme(AlignFrame af)
1280 return af.getViewport().getGlobalColourScheme();
1283 private void addInfo(String errorMessage)
1285 Console.info(errorMessage);
1286 errors.add(errorMessage);
1289 private void addWarn(String errorMessage)
1291 Console.warn(errorMessage);
1292 errors.add(errorMessage);
1295 private void addError(String errorMessage)
1297 addError(errorMessage, null);
1300 private void addError(String errorMessage, Exception e)
1302 Console.error(errorMessage, e);
1303 errors.add(errorMessage);
1306 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1307 SubVals subVal, boolean includeBackups, String filename,
1308 String adjective, Boolean isError)
1310 File file = new File(filename);
1312 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1313 null, "OVERWRITE_OUTPUT", false);
1314 boolean stdout = false;
1315 boolean backups = false;
1318 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1319 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1320 // otherwise if headless assume false, if not headless use the user
1321 // preference with default true.
1322 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1323 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1324 !Platform.isHeadless());
1327 if (file.exists() && !(overwrite || backups || stdout))
1329 addWarn("Won't overwrite file '" + filename + "' without "
1330 + Arg.OVERWRITE.argString()
1331 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1336 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1337 "MKDIRS_OUTPUT", false);
1339 if (!FileUtils.checkParentDir(file, mkdirs))
1341 addError("Directory '"
1342 + FileUtils.getParentDir(file).getAbsolutePath()
1343 + "' does not exist for " + adjective + " file '" + filename
1345 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1353 public List<String> getErrors()
1358 public String errorsToString()
1360 StringBuilder sb = new StringBuilder();
1361 for (String error : errors)
1363 if (sb.length() > 0)
1365 sb.append("- " + error);
1367 return sb.toString();