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 scope here so it can be applied after structures are opened
214 boolean wrap = false;
216 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
218 commandArgsProvided = true;
219 final long progress = System.currentTimeMillis();
221 boolean first = true;
222 boolean progressBarSet = false;
224 // Combine the APPEND and OPEN files into one list, along with whether it
225 // was APPEND or OPEN
226 List<ArgValue> openAvList = new ArrayList<>();
227 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
228 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
229 // sort avlist based on av.getArgIndex()
230 Collections.sort(openAvList);
231 for (ArgValue av : openAvList)
234 SubVals sv = av.getSubVals();
235 String openFile = av.getValue();
236 if (openFile == null)
239 theseArgsWereParsed = true;
243 if (!headless && desktop != null)
245 SwingUtilities.invokeLater(new Runnable()
250 desktop.setProgressBar(
251 MessageManager.getString(
252 "status.processing_commandline_args"),
257 progressBarSet = true;
261 if (!Platform.isJS())
263 * ignore in JavaScript -- can't just file existence - could load it?
268 if (!HttpUtils.startsWithHttpOrHttps(openFile))
270 if (!(new File(openFile)).exists())
272 addError("Can't find file '" + openFile + "'");
279 DataSourceType protocol = AppletFormatAdapter
280 .checkProtocol(openFile);
282 FileFormatI format = null;
285 format = new IdentifyFile().identify(openFile, protocol);
286 } catch (FileFormatException e1)
288 addError("Unknown file format for '" + openFile + "'");
294 // When to open a new AlignFrame
295 if (af == null || "true".equals(av.getSubVal("new"))
296 || a == Arg.OPEN || format == FileFormat.Jalview)
300 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
305 "Opening '" + openFile + "' in new alignment frame");
306 FileLoader fileLoader = new FileLoader(!headless);
307 boolean xception = false;
310 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
312 } catch (Throwable thr)
315 addError("Couldn't open '" + openFile + "' as " + format + " "
316 + thr.getLocalizedMessage()
317 + " (Enable debug for full stack trace)");
319 Console.debug("Exception when opening '" + openFile + "'", thr);
322 if (af == null && !xception)
324 addInfo("Ignoring '" + openFile
325 + "' - no alignment data found.");
331 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
332 null, "DEFAULT_COLOUR_PROT", "");
333 this.colourAlignFrame(af, colour);
335 // Change alignment frame title
336 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
341 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
345 String featuresfile = avm.getValueFromSubValOrArg(av,
347 if (featuresfile != null)
349 af.parseFeaturesFile(featuresfile,
350 AppletFormatAdapter.checkProtocol(featuresfile));
351 Jalview.testoutput(argParser, Arg.FEATURES,
352 "examples/testdata/plantfdx.features", featuresfile);
355 // Add annotations from file
356 String annotationsfile = avm.getValueFromSubValOrArg(av,
357 Arg.ANNOTATIONS, sv);
358 if (annotationsfile != null)
360 af.loadJalviewDataFile(annotationsfile, null, null, null);
361 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
362 "examples/testdata/plantfdx.annotations",
366 // Set or clear the sortbytree flag
367 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
371 af.getViewport().setSortByTree(true);
372 Jalview.testoutput(argParser, Arg.SORTBYTREE);
375 // Load tree from file
376 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
377 if (treefile != null)
381 NewickFile nf = new NewickFile(treefile,
382 AppletFormatAdapter.checkProtocol(treefile));
383 af.getViewport().setCurrentTree(
384 af.showNewickTree(nf, treefile).getTree());
385 Jalview.testoutput(argParser, Arg.TREE,
386 "examples/testdata/uniref50_test_tree", treefile);
387 } catch (IOException e)
389 addError("Couldn't add tree " + treefile, e);
394 // Show secondary structure annotations?
395 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
396 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
397 "STRUCT_FROM_PDB", true);
399 // Show sequence annotations?
400 boolean showAnnotations = avm.getFromSubValArgOrPref(
401 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
402 "SHOW_ANNOTATIONS", true);
404 boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
405 final AlignFrame _af = af;
406 // many of jalview's format/layout methods are only thread safe on the
407 // swingworker thread.
408 // all these methods should be on the alignViewController so it can
409 // coordinate such details
412 SwingUtilities.invokeAndWait(new Runnable()
418 _af.setAnnotationsVisibility(showSSAnnotations, true,
421 _af.setAnnotationsVisibility(showAnnotations, false, true);
423 // show temperature factor annotations?
426 // do this better (annotation types?)
427 List<String> hideThese = new ArrayList<>();
428 hideThese.add("Temperature Factor");
429 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
430 AlignmentUtils.showOrHideSequenceAnnotations(
431 _af.getCurrentView().getAlignment(), hideThese,
436 } catch (Exception x)
439 "Unexpected exception adjusting annotation row visibility.",
443 // wrap alignment? do this last for formatting reasons
444 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
445 "WRAP_ALIGNMENT", false);
446 // af.setWrapFormat(wrap) is applied after structures are opened for
447 // annotation reasons
449 // store the AlignFrame for this id
452 // is it its own structure file?
453 if (format.isStructureFile())
455 StructureSelectionManager ssm = StructureSelectionManager
456 .getStructureSelectionManager(Desktop.instance);
457 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
458 ssm.computeMapping(false, new SequenceI[] { seq }, null,
459 openFile, DataSourceType.FILE, null, null, null, false);
465 "Opening '" + openFile + "' in existing alignment frame");
467 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
469 : DataSourceType.FILE;
471 FileLoader fileLoader = new FileLoader(!headless);
472 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
476 Console.debug("Command " + Arg.APPEND + " executed successfully!");
479 if (first) // first=true means nothing opened
483 Jalview.exit("Could not open any files in headless mode",
488 Console.info("No more files to open");
491 if (progressBarSet && desktop != null)
492 desktop.setProgressBar(null, progress);
496 // open the structure (from same PDB file or given PDBfile)
497 if (!avm.getBoolean(Arg.NOSTRUCTURE))
500 AlignFrame af = afMap.get(id);
501 if (avm.containsArg(Arg.STRUCTURE))
503 commandArgsProvided = true;
504 for (ArgValue structureAv : avm.getArgValueList(Arg.STRUCTURE))
506 argParser.setStructureFilename(null);
507 String val = structureAv.getValue();
508 SubVals subVals = structureAv.getSubVals();
509 int argIndex = structureAv.getArgIndex();
510 SequenceI seq = getSpecifiedSequence(af, avm, structureAv);
513 // Could not find sequence from subId, let's assume the first
514 // sequence in the alignframe
515 AlignmentI al = af.getCurrentView().getAlignment();
516 seq = al.getSequenceAt(0);
521 addWarn("Could not find sequence for argument "
522 + Arg.STRUCTURE.argString() + "=" + val);
525 String structureFilename = null;
526 File structureFile = null;
527 if (subVals.getContent() != null
528 && subVals.getContent().length() != 0)
530 structureFilename = subVals.getContent();
531 Console.debug("Using structure file (from argument) '"
532 + structureFilename + "'");
533 structureFile = new File(structureFilename);
535 /* THIS DOESN'T WORK */
536 else if (seq.getAllPDBEntries() != null
537 && seq.getAllPDBEntries().size() > 0)
539 structureFile = new File(
540 seq.getAllPDBEntries().elementAt(0).getFile());
541 if (structureFile != null)
543 Console.debug("Using structure file (from sequence) '"
544 + structureFile.getAbsolutePath() + "'");
546 structureFilename = structureFile.getAbsolutePath();
549 if (structureFilename == null || structureFile == null)
551 addWarn("Not provided structure file with '" + val + "'");
555 if (!structureFile.exists())
557 addWarn("Structure file '" + structureFile.getAbsoluteFile()
562 Console.debug("Using structure file "
563 + structureFile.getAbsolutePath());
565 argParser.setStructureFilename(structureFilename);
567 // open structure view
568 AlignmentPanel ap = af.alignPanel;
571 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
572 StructureViewer.ViewerType.JMOL.toString());
575 String structureFilepath = structureFile.getAbsolutePath();
577 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
578 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
579 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER,
580 structureAv, subVals, null, null, null);
581 if (paeFilepath != null)
583 File paeFile = new File(paeFilepath);
587 paeFilepath = paeFile.getCanonicalPath();
588 } catch (IOException e)
590 paeFilepath = paeFile.getAbsolutePath();
591 addWarn("Problem with the PAE file path: '"
592 + paeFile.getPath() + "'");
596 // showing annotations from structure file or not
597 boolean ssFromStructure = avm.getFromSubValArgOrPref(
598 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
601 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
602 // reference annotations
603 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
604 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER,
605 structureAv, subVals, null, null, null);
606 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
607 subVals, null, "ADD_TEMPFACT_ANN", false, true);
608 TFType tft = notempfac ? null : TFType.DEFAULT;
609 if (tftString != null && !notempfac)
611 // get kind of temperature factor annotation
614 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
615 Console.debug("Obtained Temperature Factor type of '" + tft
616 + "' for structure '" + structureFilepath + "'");
617 } catch (IllegalArgumentException e)
619 // Just an error message!
620 StringBuilder sb = new StringBuilder().append("Cannot set ")
621 .append(Arg.TEMPFAC.argString()).append(" to '")
623 .append("', ignoring. Valid values are: ");
624 Iterator<TFType> it = Arrays.stream(TFType.values())
628 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
632 addWarn(sb.toString());
636 String sViewerName = avm.getFromSubValArgOrPref(
637 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER,
638 structureAv, subVals, null, null, "jmol");
639 ViewerType viewerType = ViewerType.getFromString(sViewerName);
641 // TODO use ssFromStructure
642 StructureViewer structureViewer = StructureChooser
643 .openStructureFileForSequence(null, null, ap, seq, false,
644 structureFilepath, tft, paeFilepath, false,
645 ssFromStructure, false, viewerType);
647 if (structureViewer == null)
649 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
651 addError("Failed to import and open structure view for file '"
652 + structureFile + "'.");
659 while (structureViewer.isBusy() && tries > 0)
662 if (structureViewer.isBusy())
666 "Waiting for viewer for " + structureFilepath);
669 if (tries == 0 && structureViewer.isBusy())
671 addWarn("Gave up waiting for structure viewer to load file '"
673 + "'. Something may have gone wrong.");
675 } catch (Exception x)
677 addError("Exception whilst waiting for structure viewer "
678 + structureFilepath, x);
682 // add StructureViewer to svMap list
685 svMap = new HashMap<>();
687 if (svMap.get(id) == null)
689 svMap.put(id, new ArrayList<>());
691 svMap.get(id).add(structureViewer);
694 "Successfully opened viewer for " + structureFilepath);
696 if (avm.containsArg(Arg.STRUCTUREIMAGE))
698 for (ArgValue structureImageArgValue : avm
699 .getArgValueListFromSubValOrArg(structureAv,
700 Arg.STRUCTUREIMAGE, subVals))
702 String structureImageFilename = argParser.makeSubstitutions(
703 structureImageArgValue.getValue(), id, true);
704 if (structureViewer != null && structureImageFilename != null)
706 SubVals structureImageSubVals = null;
707 structureImageSubVals = structureImageArgValue.getSubVals();
708 File structureImageFile = new File(structureImageFilename);
709 String width = avm.getValueFromSubValOrArg(
710 structureImageArgValue, Arg.WIDTH,
711 structureImageSubVals);
712 String height = avm.getValueFromSubValOrArg(
713 structureImageArgValue, Arg.HEIGHT,
714 structureImageSubVals);
715 String scale = avm.getValueFromSubValOrArg(
716 structureImageArgValue, Arg.SCALE,
717 structureImageSubVals);
718 String renderer = avm.getValueFromSubValOrArg(
719 structureImageArgValue, Arg.TEXTRENDERER,
720 structureImageSubVals);
721 String typeS = avm.getValueFromSubValOrArg(
722 structureImageArgValue, Arg.TYPE,
723 structureImageSubVals);
724 if (typeS == null || typeS.length() == 0)
726 typeS = FileUtils.getExtension(structureImageFile);
731 imageType = Enum.valueOf(TYPE.class,
732 typeS.toUpperCase(Locale.ROOT));
733 } catch (IllegalArgumentException e)
735 addWarn("Do not know image format '" + typeS
737 imageType = TYPE.PNG;
739 BitmapImageSizing userBis = ImageMaker
740 .parseScaleWidthHeightStrings(scale, width, height);
743 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
744 if (viewerType != ViewerType.JMOL)
746 addWarn("Cannot export image for structure viewer "
747 + viewerType.name() + " yet");
752 // Apply the temporary colourscheme to the linked alignment
753 // TODO: enhance for multiple linked alignments.
755 String imageColour = avm.getValueFromSubValOrArg(
756 structureImageArgValue, Arg.IMAGECOLOUR,
757 structureImageSubVals);
758 ColourSchemeI originalColourScheme = this
759 .getColourScheme(af);
760 this.colourAlignFrame(af, imageColour);
763 // custom image background colour
765 String bgcolourstring = avm.getValueFromSubValOrArg(
766 structureImageArgValue, Arg.BGCOLOUR,
767 structureImageSubVals);
768 Color bgcolour = null;
769 if (bgcolourstring != null && bgcolourstring.length() > 0)
771 bgcolour = ColorUtils.parseColourString(bgcolourstring);
772 if (bgcolour == null)
775 "Background colour string '" + bgcolourstring
776 + "' not recognised -- using default");
780 JalviewStructureDisplayI sview = structureViewer
781 .getJalviewStructureDisplay();
783 File sessionToRestore = null;
785 List<StructureCommandI> extraCommands = new ArrayList<>();
787 if (extraCommands.size() > 0 || bgcolour != null)
791 sessionToRestore = sview.saveSession();
792 } catch (Throwable t)
795 "Unable to save temporary session file before custom structure view export operation.");
802 if (bgcolour != null)
804 sview.getBinding().setBackgroundColour(bgcolour);
807 sview.getBinding().executeCommands(extraCommands, false,
808 "Executing Custom Commands");
810 // and export the view as an image
811 boolean success = this.checksBeforeWritingToFile(avm,
812 subVals, false, structureImageFilename,
813 "structure image", isError);
819 Console.debug("Rendering image to " + structureImageFile);
821 // TODO - extend StructureViewer / Binding with makePDBImage so
822 // we can do this with every viewer
827 // We don't expect class cast exception
828 AppJmol jmol = (AppJmol) sview;
829 jmol.makePDBImage(structureImageFile, imageType, renderer,
831 Console.info("Exported structure image to "
832 + structureImageFile);
834 // RESTORE SESSION AFTER EXPORT IF NEED BE
835 if (sessionToRestore != null)
838 "Restoring session from " + sessionToRestore);
840 sview.getBinding().restoreSession(
841 sessionToRestore.getAbsolutePath());
844 } catch (ImageOutputException ioexec)
847 "Unexpected error when restoring structure viewer session after custom view operations.");
854 this.colourAlignFrame(af, originalColourScheme);
855 } catch (Exception t)
858 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
865 argParser.setStructureFilename(null);
873 AlignFrame af = afMap.get(id);
876 af.setWrapFormat(wrap, true);
881 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
884 AlignFrame af = afMap.get(id);
885 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
886 .findAnnotation(PDBChain.class.getName().toString()))
888 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
889 af.alignPanel.av.getGlobalColourScheme(), 0);
890 acg.setSeqAssociated(true);
891 af.changeColour(acg);
892 Console.info("Changed colour " + acg.toString());
897 return theseArgsWereParsed && !isError;
900 protected void processGroovyScript(String id)
902 ArgValuesMap avm = argParser.getLinkedArgs(id);
903 AlignFrame af = afMap.get(id);
905 if (avm != null && !avm.containsArg(Arg.GROOVY))
913 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
916 if (avm.containsArg(Arg.GROOVY))
918 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
920 String groovyscript = groovyAv.getValue();
921 if (groovyscript != null)
923 // Execute the groovy script after we've done all the rendering stuff
924 // and before any images or figures are generated.
925 Console.info("Executing script " + groovyscript);
926 Jalview.getInstance().executeGroovyScript(groovyscript, af);
932 protected boolean processImages(String id)
934 ArgValuesMap avm = argParser.getLinkedArgs(id);
935 AlignFrame af = afMap.get(id);
937 if (avm != null && !avm.containsArg(Arg.IMAGE))
945 addWarn("Do not have an alignment window to create image from (id="
946 + id + "). Not proceeding.");
950 Boolean isError = Boolean.valueOf(false);
951 if (avm.containsArg(Arg.IMAGE))
953 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
955 String val = imageAv.getValue();
956 SubVals imageSubVals = imageAv.getSubVals();
957 String fileName = imageSubVals.getContent();
958 File file = new File(fileName);
959 String name = af.getName();
960 String renderer = avm.getValueFromSubValOrArg(imageAv,
961 Arg.TEXTRENDERER, imageSubVals);
962 if (renderer == null)
964 String type = "png"; // default
966 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
968 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
970 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
972 BitmapImageSizing userBis = ImageMaker
973 .parseScaleWidthHeightStrings(scale, width, height);
975 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
976 if (type == null && fileName != null)
978 for (String ext : new String[] { "svg", "png", "html", "eps" })
980 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
986 // for moment we disable JSON export
987 Cache.setPropsAreReadOnly(true);
988 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
990 String imageColour = avm.getValueFromSubValOrArg(imageAv,
991 Arg.IMAGECOLOUR, imageSubVals);
992 ColourSchemeI originalColourScheme = this.getColourScheme(af);
993 this.colourAlignFrame(af, imageColour);
995 Console.info("Writing " + file);
997 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
998 false, fileName, "image", isError);
1010 Console.debug("Outputting type '" + type + "' to " + fileName);
1011 af.createSVG(file, renderer);
1015 Console.debug("Outputting type '" + type + "' to " + fileName);
1016 af.createPNG(file, null, userBis);
1020 Console.debug("Outputting type '" + type + "' to " + fileName);
1021 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1022 htmlSVG.exportHTML(fileName, renderer);
1027 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1030 BioJsHTMLOutput.refreshVersionInfo(
1031 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1032 } catch (URISyntaxException e)
1034 e.printStackTrace();
1036 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1037 bjs.exportHTML(fileName);
1041 Console.debug("Outputting EPS file: " + fileName);
1042 af.createEPS(file, renderer);
1046 Console.debug("Outputting ImageMap file: " + fileName);
1047 af.createImageMap(file, name);
1051 addWarn(Arg.IMAGE.argString() + " type '" + type
1052 + "' not known. Ignoring");
1055 } catch (Exception ioex)
1057 addError("Unexpected error during export to '" + fileName + "'",
1062 this.colourAlignFrame(af, originalColourScheme);
1068 protected boolean processOutput(String id)
1070 ArgValuesMap avm = argParser.getLinkedArgs(id);
1071 AlignFrame af = afMap.get(id);
1073 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1081 addWarn("Do not have an alignment window (id=" + id
1082 + "). Not proceeding.");
1086 Boolean isError = Boolean.valueOf(false);
1088 if (avm.containsArg(Arg.OUTPUT))
1090 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1092 String val = av.getValue();
1093 SubVals subVals = av.getSubVals();
1094 String fileName = subVals.getContent();
1095 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1096 File file = new File(fileName);
1098 String name = af.getName();
1099 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1101 FileFormats ffs = FileFormats.getInstance();
1102 List<String> validFormats = ffs.getWritableFormats(false);
1104 FileFormatI ff = null;
1105 if (format == null && fileName != null)
1107 FORMAT: for (String fname : validFormats)
1109 FileFormatI tff = ffs.forName(fname);
1110 String[] extensions = tff.getExtensions().split(",");
1111 for (String ext : extensions)
1113 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1116 format = ff.getName();
1122 if (ff == null && format != null)
1124 ff = ffs.forName(format);
1130 ff = FileFormat.Fasta;
1134 StringBuilder validSB = new StringBuilder();
1135 for (String f : validFormats)
1137 if (validSB.length() > 0)
1138 validSB.append(", ");
1140 FileFormatI tff = ffs.forName(f);
1141 validSB.append(" (");
1142 validSB.append(tff.getExtensions());
1143 validSB.append(")");
1146 addError("No valid format specified for "
1147 + Arg.OUTPUT.argString() + ". Valid formats are "
1148 + validSB.toString() + ".");
1153 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1154 fileName, ff.getName(), isError);
1160 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1161 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1162 !Platform.isHeadless());
1164 Console.info("Writing " + fileName);
1166 af.saveAlignment(fileName, ff, stdout, backups);
1167 if (af.isSaveAlignmentSuccessful())
1169 Console.debug("Written alignment '" + name + "' in "
1170 + ff.getName() + " format to '" + file + "'");
1174 addError("Error writing file '" + file + "' in " + ff.getName()
1185 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1188 SubVals subVals = av.getSubVals();
1189 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1190 SequenceI seq = null;
1191 if (subVals == null && idAv == null)
1193 if (af == null || af.getCurrentView() == null)
1197 AlignmentI al = af.getCurrentView().getAlignment();
1202 if (subVals != null)
1204 if (subVals.has(Arg.SEQID.getName()))
1206 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1208 else if (-1 < subVals.getIndex()
1209 && subVals.getIndex() < al.getSequences().size())
1211 seq = al.getSequenceAt(subVals.getIndex());
1214 if (seq == null && idAv != null)
1216 seq = al.findName(idAv.getValue());
1221 public AlignFrame[] getAlignFrames()
1223 AlignFrame[] afs = null;
1226 afs = (AlignFrame[]) afMap.values().toArray();
1232 public List<StructureViewer> getStructureViewers()
1234 List<StructureViewer> svs = null;
1237 for (List<StructureViewer> svList : svMap.values())
1241 svs = new ArrayList<>();
1249 private void colourAlignFrame(AlignFrame af, String colour)
1251 // use string "none" to remove colour scheme
1252 if (colour != null && "" != colour)
1254 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1255 af.getViewport(), af.getViewport().getAlignment(), colour);
1256 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1258 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1262 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1263 colourAlignFrame(af, cs);
1268 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1270 // Note that cs == null removes colour scheme from af
1271 af.changeColour(cs);
1274 private ColourSchemeI getColourScheme(AlignFrame af)
1276 return af.getViewport().getGlobalColourScheme();
1279 private void addInfo(String errorMessage)
1281 Console.info(errorMessage);
1282 errors.add(errorMessage);
1285 private void addWarn(String errorMessage)
1287 Console.warn(errorMessage);
1288 errors.add(errorMessage);
1291 private void addError(String errorMessage)
1293 addError(errorMessage, null);
1296 private void addError(String errorMessage, Exception e)
1298 Console.error(errorMessage, e);
1299 errors.add(errorMessage);
1302 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1303 SubVals subVal, boolean includeBackups, String filename,
1304 String adjective, Boolean isError)
1306 File file = new File(filename);
1308 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1309 null, "OVERWRITE_OUTPUT", false);
1310 boolean stdout = false;
1311 boolean backups = false;
1314 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1315 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1316 // otherwise if headless assume false, if not headless use the user
1317 // preference with default true.
1318 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1319 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1320 !Platform.isHeadless());
1323 if (file.exists() && !(overwrite || backups || stdout))
1325 addWarn("Won't overwrite file '" + filename + "' without "
1326 + Arg.OVERWRITE.argString()
1327 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1332 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1333 "MKDIRS_OUTPUT", false);
1335 if (!FileUtils.checkParentDir(file, mkdirs))
1337 addError("Directory '"
1338 + FileUtils.getParentDir(file).getAbsolutePath()
1339 + "' does not exist for " + adjective + " file '" + filename
1341 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1349 public List<String> getErrors()
1354 public String errorsToString()
1356 StringBuilder sb = new StringBuilder();
1357 for (String error : errors)
1359 if (sb.length() > 0)
1361 sb.append("- " + error);
1363 return sb.toString();