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 = null;
332 if (avm.containsArg(Arg.COLOUR)
333 || !(format == FileFormat.Jalview))
335 colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv, null,
336 "DEFAULT_COLOUR_PROT", null);
340 this.colourAlignFrame(af, colour);
343 // Change alignment frame title
344 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
349 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
353 String featuresfile = avm.getValueFromSubValOrArg(av,
355 if (featuresfile != null)
357 af.parseFeaturesFile(featuresfile,
358 AppletFormatAdapter.checkProtocol(featuresfile));
359 Jalview.testoutput(argParser, Arg.FEATURES,
360 "examples/testdata/plantfdx.features", featuresfile);
363 // Add annotations from file
364 String annotationsfile = avm.getValueFromSubValOrArg(av,
365 Arg.ANNOTATIONS, sv);
366 if (annotationsfile != null)
368 af.loadJalviewDataFile(annotationsfile, null, null, null);
369 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
370 "examples/testdata/plantfdx.annotations",
374 // Set or clear the sortbytree flag
375 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
379 af.getViewport().setSortByTree(true);
380 Jalview.testoutput(argParser, Arg.SORTBYTREE);
383 // Load tree from file
384 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
385 if (treefile != null)
389 NewickFile nf = new NewickFile(treefile,
390 AppletFormatAdapter.checkProtocol(treefile));
391 af.getViewport().setCurrentTree(
392 af.showNewickTree(nf, treefile).getTree());
393 Jalview.testoutput(argParser, Arg.TREE,
394 "examples/testdata/uniref50_test_tree", treefile);
395 } catch (IOException e)
397 addError("Couldn't add tree " + treefile, e);
402 // Show secondary structure annotations?
403 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
404 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
405 "STRUCT_FROM_PDB", true);
407 // Show sequence annotations?
408 boolean showAnnotations = avm.getFromSubValArgOrPref(
409 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
410 "SHOW_ANNOTATIONS", true);
412 boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
413 final AlignFrame _af = af;
414 // many of jalview's format/layout methods are only thread safe on the
415 // swingworker thread.
416 // all these methods should be on the alignViewController so it can
417 // coordinate such details
420 SwingUtilities.invokeAndWait(new Runnable()
426 _af.setAnnotationsVisibility(showSSAnnotations, true,
429 _af.setAnnotationsVisibility(showAnnotations, false, true);
431 // show temperature factor annotations?
434 // do this better (annotation types?)
435 List<String> hideThese = new ArrayList<>();
436 hideThese.add("Temperature Factor");
437 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
438 AlignmentUtils.showOrHideSequenceAnnotations(
439 _af.getCurrentView().getAlignment(), hideThese,
444 } catch (Exception x)
447 "Unexpected exception adjusting annotation row visibility.",
451 // wrap alignment? do this last for formatting reasons
452 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
453 "WRAP_ALIGNMENT", false);
454 // af.setWrapFormat(wrap) is applied after structures are opened for
455 // annotation reasons
457 // store the AlignFrame for this id
460 // is it its own structure file?
461 if (format.isStructureFile())
463 StructureSelectionManager ssm = StructureSelectionManager
464 .getStructureSelectionManager(Desktop.instance);
465 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
466 ssm.computeMapping(false, new SequenceI[] { seq }, null,
467 openFile, DataSourceType.FILE, null, null, null, false);
473 "Opening '" + openFile + "' in existing alignment frame");
475 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
477 : DataSourceType.FILE;
479 FileLoader fileLoader = new FileLoader(!headless);
480 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
484 Console.debug("Command " + Arg.APPEND + " executed successfully!");
487 if (first) // first=true means nothing opened
491 Jalview.exit("Could not open any files in headless mode",
496 Console.info("No more files to open");
499 if (progressBarSet && desktop != null)
500 desktop.setProgressBar(null, progress);
504 // open the structure (from same PDB file or given PDBfile)
505 if (!avm.getBoolean(Arg.NOSTRUCTURE))
508 AlignFrame af = afMap.get(id);
509 if (avm.containsArg(Arg.STRUCTURE))
511 commandArgsProvided = true;
512 for (ArgValue structureAv : avm.getArgValueList(Arg.STRUCTURE))
514 argParser.setStructureFilename(null);
515 String val = structureAv.getValue();
516 SubVals subVals = structureAv.getSubVals();
517 int argIndex = structureAv.getArgIndex();
518 SequenceI seq = getSpecifiedSequence(af, avm, structureAv);
521 // Could not find sequence from subId, let's assume the first
522 // sequence in the alignframe
523 AlignmentI al = af.getCurrentView().getAlignment();
524 seq = al.getSequenceAt(0);
529 addWarn("Could not find sequence for argument "
530 + Arg.STRUCTURE.argString() + "=" + val);
533 String structureFilename = null;
534 File structureFile = null;
535 if (subVals.getContent() != null
536 && subVals.getContent().length() != 0)
538 structureFilename = subVals.getContent();
539 Console.debug("Using structure file (from argument) '"
540 + structureFilename + "'");
541 structureFile = new File(structureFilename);
543 /* THIS DOESN'T WORK */
544 else if (seq.getAllPDBEntries() != null
545 && seq.getAllPDBEntries().size() > 0)
547 structureFile = new File(
548 seq.getAllPDBEntries().elementAt(0).getFile());
549 if (structureFile != null)
551 Console.debug("Using structure file (from sequence) '"
552 + structureFile.getAbsolutePath() + "'");
554 structureFilename = structureFile.getAbsolutePath();
557 if (structureFilename == null || structureFile == null)
559 addWarn("Not provided structure file with '" + val + "'");
563 if (!structureFile.exists())
565 addWarn("Structure file '" + structureFile.getAbsoluteFile()
570 Console.debug("Using structure file "
571 + structureFile.getAbsolutePath());
573 argParser.setStructureFilename(structureFilename);
575 // open structure view
576 AlignmentPanel ap = af.alignPanel;
579 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
580 StructureViewer.ViewerType.JMOL.toString());
583 String structureFilepath = structureFile.getAbsolutePath();
585 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
586 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
587 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER,
588 structureAv, subVals, null, null, null);
589 if (paeFilepath != null)
591 File paeFile = new File(paeFilepath);
595 paeFilepath = paeFile.getCanonicalPath();
596 } catch (IOException e)
598 paeFilepath = paeFile.getAbsolutePath();
599 addWarn("Problem with the PAE file path: '"
600 + paeFile.getPath() + "'");
604 // showing annotations from structure file or not
605 boolean ssFromStructure = avm.getFromSubValArgOrPref(
606 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
609 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
610 // reference annotations
611 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
612 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER,
613 structureAv, subVals, null, null, null);
614 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
615 subVals, null, "ADD_TEMPFACT_ANN", false, true);
616 TFType tft = notempfac ? null : TFType.DEFAULT;
617 if (tftString != null && !notempfac)
619 // get kind of temperature factor annotation
622 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
623 Console.debug("Obtained Temperature Factor type of '" + tft
624 + "' for structure '" + structureFilepath + "'");
625 } catch (IllegalArgumentException e)
627 // Just an error message!
628 StringBuilder sb = new StringBuilder().append("Cannot set ")
629 .append(Arg.TEMPFAC.argString()).append(" to '")
631 .append("', ignoring. Valid values are: ");
632 Iterator<TFType> it = Arrays.stream(TFType.values())
636 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
640 addWarn(sb.toString());
644 String sViewerName = avm.getFromSubValArgOrPref(
645 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER,
646 structureAv, subVals, null, null, "jmol");
647 ViewerType viewerType = ViewerType.getFromString(sViewerName);
649 // TODO use ssFromStructure
650 StructureViewer structureViewer = StructureChooser
651 .openStructureFileForSequence(null, null, ap, seq, false,
652 structureFilepath, tft, paeFilepath, false,
653 ssFromStructure, false, viewerType);
655 if (structureViewer == null)
657 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
659 addError("Failed to import and open structure view for file '"
660 + structureFile + "'.");
667 while (structureViewer.isBusy() && tries > 0)
670 if (structureViewer.isBusy())
674 "Waiting for viewer for " + structureFilepath);
677 if (tries == 0 && structureViewer.isBusy())
679 addWarn("Gave up waiting for structure viewer to load file '"
681 + "'. Something may have gone wrong.");
683 } catch (Exception x)
685 addError("Exception whilst waiting for structure viewer "
686 + structureFilepath, x);
690 // add StructureViewer to svMap list
693 svMap = new HashMap<>();
695 if (svMap.get(id) == null)
697 svMap.put(id, new ArrayList<>());
699 svMap.get(id).add(structureViewer);
702 "Successfully opened viewer for " + structureFilepath);
704 if (avm.containsArg(Arg.STRUCTUREIMAGE))
706 for (ArgValue structureImageArgValue : avm
707 .getArgValueListFromSubValOrArg(structureAv,
708 Arg.STRUCTUREIMAGE, subVals))
710 String structureImageFilename = argParser.makeSubstitutions(
711 structureImageArgValue.getValue(), id, true);
712 if (structureViewer != null && structureImageFilename != null)
714 SubVals structureImageSubVals = null;
715 structureImageSubVals = structureImageArgValue.getSubVals();
716 File structureImageFile = new File(structureImageFilename);
717 String width = avm.getValueFromSubValOrArg(
718 structureImageArgValue, Arg.WIDTH,
719 structureImageSubVals);
720 String height = avm.getValueFromSubValOrArg(
721 structureImageArgValue, Arg.HEIGHT,
722 structureImageSubVals);
723 String scale = avm.getValueFromSubValOrArg(
724 structureImageArgValue, Arg.SCALE,
725 structureImageSubVals);
726 String renderer = avm.getValueFromSubValOrArg(
727 structureImageArgValue, Arg.TEXTRENDERER,
728 structureImageSubVals);
729 String typeS = avm.getValueFromSubValOrArg(
730 structureImageArgValue, Arg.TYPE,
731 structureImageSubVals);
732 if (typeS == null || typeS.length() == 0)
734 typeS = FileUtils.getExtension(structureImageFile);
739 imageType = Enum.valueOf(TYPE.class,
740 typeS.toUpperCase(Locale.ROOT));
741 } catch (IllegalArgumentException e)
743 addWarn("Do not know image format '" + typeS
745 imageType = TYPE.PNG;
747 BitmapImageSizing userBis = ImageMaker
748 .parseScaleWidthHeightStrings(scale, width, height);
751 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
752 if (viewerType != ViewerType.JMOL)
754 addWarn("Cannot export image for structure viewer "
755 + viewerType.name() + " yet");
760 // Apply the temporary colourscheme to the linked alignment
761 // TODO: enhance for multiple linked alignments.
763 String imageColour = avm.getValueFromSubValOrArg(
764 structureImageArgValue, Arg.IMAGECOLOUR,
765 structureImageSubVals);
766 ColourSchemeI originalColourScheme = this
767 .getColourScheme(af);
768 this.colourAlignFrame(af, imageColour);
771 // custom image background colour
773 String bgcolourstring = avm.getValueFromSubValOrArg(
774 structureImageArgValue, Arg.BGCOLOUR,
775 structureImageSubVals);
776 Color bgcolour = null;
777 if (bgcolourstring != null && bgcolourstring.length() > 0)
779 bgcolour = ColorUtils.parseColourString(bgcolourstring);
780 if (bgcolour == null)
783 "Background colour string '" + bgcolourstring
784 + "' not recognised -- using default");
788 JalviewStructureDisplayI sview = structureViewer
789 .getJalviewStructureDisplay();
791 File sessionToRestore = null;
793 List<StructureCommandI> extraCommands = new ArrayList<>();
795 if (extraCommands.size() > 0 || bgcolour != null)
799 sessionToRestore = sview.saveSession();
800 } catch (Throwable t)
803 "Unable to save temporary session file before custom structure view export operation.");
810 if (bgcolour != null)
812 sview.getBinding().setBackgroundColour(bgcolour);
815 sview.getBinding().executeCommands(extraCommands, false,
816 "Executing Custom Commands");
818 // and export the view as an image
819 boolean success = this.checksBeforeWritingToFile(avm,
820 subVals, false, structureImageFilename,
821 "structure image", isError);
827 Console.debug("Rendering image to " + structureImageFile);
829 // TODO - extend StructureViewer / Binding with makePDBImage so
830 // we can do this with every viewer
835 // We don't expect class cast exception
836 AppJmol jmol = (AppJmol) sview;
837 jmol.makePDBImage(structureImageFile, imageType, renderer,
839 Console.info("Exported structure image to "
840 + structureImageFile);
842 // RESTORE SESSION AFTER EXPORT IF NEED BE
843 if (sessionToRestore != null)
846 "Restoring session from " + sessionToRestore);
848 sview.getBinding().restoreSession(
849 sessionToRestore.getAbsolutePath());
852 } catch (ImageOutputException ioexec)
855 "Unexpected error when restoring structure viewer session after custom view operations.");
862 this.colourAlignFrame(af, originalColourScheme);
863 } catch (Exception t)
866 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
873 argParser.setStructureFilename(null);
881 AlignFrame af = afMap.get(id);
884 af.setWrapFormat(wrap, true);
889 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
892 AlignFrame af = afMap.get(id);
893 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
894 .findAnnotation(PDBChain.class.getName().toString()))
896 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
897 af.alignPanel.av.getGlobalColourScheme(), 0);
898 acg.setSeqAssociated(true);
899 af.changeColour(acg);
900 Console.info("Changed colour " + acg.toString());
905 return theseArgsWereParsed && !isError;
908 protected void processGroovyScript(String id)
910 ArgValuesMap avm = argParser.getLinkedArgs(id);
911 AlignFrame af = afMap.get(id);
913 if (avm != null && !avm.containsArg(Arg.GROOVY))
921 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
924 if (avm.containsArg(Arg.GROOVY))
926 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
928 String groovyscript = groovyAv.getValue();
929 if (groovyscript != null)
931 // Execute the groovy script after we've done all the rendering stuff
932 // and before any images or figures are generated.
933 Console.info("Executing script " + groovyscript);
934 Jalview.getInstance().executeGroovyScript(groovyscript, af);
940 protected boolean processImages(String id)
942 ArgValuesMap avm = argParser.getLinkedArgs(id);
943 AlignFrame af = afMap.get(id);
945 if (avm != null && !avm.containsArg(Arg.IMAGE))
953 addWarn("Do not have an alignment window to create image from (id="
954 + id + "). Not proceeding.");
958 Boolean isError = Boolean.valueOf(false);
959 if (avm.containsArg(Arg.IMAGE))
961 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
963 String val = imageAv.getValue();
964 SubVals imageSubVals = imageAv.getSubVals();
965 String fileName = imageSubVals.getContent();
966 File file = new File(fileName);
967 String name = af.getName();
968 String renderer = avm.getValueFromSubValOrArg(imageAv,
969 Arg.TEXTRENDERER, imageSubVals);
970 if (renderer == null)
972 String type = "png"; // default
974 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
976 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
978 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
980 BitmapImageSizing userBis = ImageMaker
981 .parseScaleWidthHeightStrings(scale, width, height);
983 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
984 if (type == null && fileName != null)
986 for (String ext : new String[] { "svg", "png", "html", "eps" })
988 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
994 // for moment we disable JSON export
995 Cache.setPropsAreReadOnly(true);
996 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
998 String imageColour = avm.getValueFromSubValOrArg(imageAv,
999 Arg.IMAGECOLOUR, imageSubVals);
1000 ColourSchemeI originalColourScheme = this.getColourScheme(af);
1001 this.colourAlignFrame(af, imageColour);
1003 Console.info("Writing " + file);
1005 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
1006 false, fileName, "image", isError);
1018 Console.debug("Outputting type '" + type + "' to " + fileName);
1019 af.createSVG(file, renderer);
1023 Console.debug("Outputting type '" + type + "' to " + fileName);
1024 af.createPNG(file, null, userBis);
1028 Console.debug("Outputting type '" + type + "' to " + fileName);
1029 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1030 htmlSVG.exportHTML(fileName, renderer);
1035 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1038 BioJsHTMLOutput.refreshVersionInfo(
1039 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1040 } catch (URISyntaxException e)
1042 e.printStackTrace();
1044 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1045 bjs.exportHTML(fileName);
1049 Console.debug("Outputting EPS file: " + fileName);
1050 af.createEPS(file, renderer);
1054 Console.debug("Outputting ImageMap file: " + fileName);
1055 af.createImageMap(file, name);
1059 addWarn(Arg.IMAGE.argString() + " type '" + type
1060 + "' not known. Ignoring");
1063 } catch (Exception ioex)
1065 addError("Unexpected error during export to '" + fileName + "'",
1070 this.colourAlignFrame(af, originalColourScheme);
1076 protected boolean processOutput(String id)
1078 ArgValuesMap avm = argParser.getLinkedArgs(id);
1079 AlignFrame af = afMap.get(id);
1081 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1089 addWarn("Do not have an alignment window (id=" + id
1090 + "). Not proceeding.");
1094 Boolean isError = Boolean.valueOf(false);
1096 if (avm.containsArg(Arg.OUTPUT))
1098 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1100 String val = av.getValue();
1101 SubVals subVals = av.getSubVals();
1102 String fileName = subVals.getContent();
1103 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1104 File file = new File(fileName);
1106 String name = af.getName();
1107 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1109 FileFormats ffs = FileFormats.getInstance();
1110 List<String> validFormats = ffs.getWritableFormats(false);
1112 FileFormatI ff = null;
1113 if (format == null && fileName != null)
1115 FORMAT: for (String fname : validFormats)
1117 FileFormatI tff = ffs.forName(fname);
1118 String[] extensions = tff.getExtensions().split(",");
1119 for (String ext : extensions)
1121 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1124 format = ff.getName();
1130 if (ff == null && format != null)
1132 ff = ffs.forName(format);
1138 ff = FileFormat.Fasta;
1142 StringBuilder validSB = new StringBuilder();
1143 for (String f : validFormats)
1145 if (validSB.length() > 0)
1146 validSB.append(", ");
1148 FileFormatI tff = ffs.forName(f);
1149 validSB.append(" (");
1150 validSB.append(tff.getExtensions());
1151 validSB.append(")");
1154 addError("No valid format specified for "
1155 + Arg.OUTPUT.argString() + ". Valid formats are "
1156 + validSB.toString() + ".");
1161 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1162 fileName, ff.getName(), isError);
1168 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1169 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1170 !Platform.isHeadless());
1172 Console.info("Writing " + fileName);
1174 af.saveAlignment(fileName, ff, stdout, backups);
1175 if (af.isSaveAlignmentSuccessful())
1177 Console.debug("Written alignment '" + name + "' in "
1178 + ff.getName() + " format to '" + file + "'");
1182 addError("Error writing file '" + file + "' in " + ff.getName()
1193 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1196 SubVals subVals = av.getSubVals();
1197 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1198 SequenceI seq = null;
1199 if (subVals == null && idAv == null)
1201 if (af == null || af.getCurrentView() == null)
1205 AlignmentI al = af.getCurrentView().getAlignment();
1210 if (subVals != null)
1212 if (subVals.has(Arg.SEQID.getName()))
1214 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1216 else if (-1 < subVals.getIndex()
1217 && subVals.getIndex() < al.getSequences().size())
1219 seq = al.getSequenceAt(subVals.getIndex());
1222 if (seq == null && idAv != null)
1224 seq = al.findName(idAv.getValue());
1229 public AlignFrame[] getAlignFrames()
1231 AlignFrame[] afs = null;
1234 afs = (AlignFrame[]) afMap.values().toArray();
1240 public List<StructureViewer> getStructureViewers()
1242 List<StructureViewer> svs = null;
1245 for (List<StructureViewer> svList : svMap.values())
1249 svs = new ArrayList<>();
1257 private void colourAlignFrame(AlignFrame af, String colour)
1259 // use string "none" to remove colour scheme
1260 if (colour != null && "" != colour)
1262 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1263 af.getViewport(), af.getViewport().getAlignment(), colour);
1264 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1266 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1270 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1271 colourAlignFrame(af, cs);
1276 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1278 // Note that cs == null removes colour scheme from af
1279 af.changeColour(cs);
1282 private ColourSchemeI getColourScheme(AlignFrame af)
1284 return af.getViewport().getGlobalColourScheme();
1287 private void addInfo(String errorMessage)
1289 Console.info(errorMessage);
1290 errors.add(errorMessage);
1293 private void addWarn(String errorMessage)
1295 Console.warn(errorMessage);
1296 errors.add(errorMessage);
1299 private void addError(String errorMessage)
1301 addError(errorMessage, null);
1304 private void addError(String errorMessage, Exception e)
1306 Console.error(errorMessage, e);
1307 errors.add(errorMessage);
1310 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1311 SubVals subVal, boolean includeBackups, String filename,
1312 String adjective, Boolean isError)
1314 File file = new File(filename);
1316 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1317 null, "OVERWRITE_OUTPUT", false);
1318 boolean stdout = false;
1319 boolean backups = false;
1322 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1323 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1324 // otherwise if headless assume false, if not headless use the user
1325 // preference with default true.
1326 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1327 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1328 !Platform.isHeadless());
1331 if (file.exists() && !(overwrite || backups || stdout))
1333 addWarn("Won't overwrite file '" + filename + "' without "
1334 + Arg.OVERWRITE.argString()
1335 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1340 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1341 "MKDIRS_OUTPUT", false);
1343 if (!FileUtils.checkParentDir(file, mkdirs))
1345 addError("Directory '"
1346 + FileUtils.getParentDir(file).getAbsolutePath()
1347 + "' does not exist for " + adjective + " file '" + filename
1349 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1357 public List<String> getErrors()
1362 public String errorsToString()
1364 StringBuilder sb = new StringBuilder();
1365 for (String error : errors)
1367 if (sb.length() > 0)
1369 sb.append("- " + error);
1371 return sb.toString();