5 import java.io.IOException;
6 import java.net.URISyntaxException;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Locale;
16 import javax.swing.SwingUtilities;
18 import jalview.analysis.AlignmentUtils;
19 import jalview.api.structures.JalviewStructureDisplayI;
20 import jalview.bin.Jalview.ExitCode;
21 import jalview.bin.argparser.Arg;
22 import jalview.bin.argparser.ArgParser;
23 import jalview.bin.argparser.ArgValue;
24 import jalview.bin.argparser.ArgValuesMap;
25 import jalview.bin.argparser.SubVals;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceI;
28 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.AlignmentPanel;
31 import jalview.gui.AppJmol;
32 import jalview.gui.Desktop;
33 import jalview.gui.Preferences;
34 import jalview.gui.StructureChooser;
35 import jalview.gui.StructureViewer;
36 import jalview.gui.StructureViewer.ViewerType;
37 import jalview.io.AppletFormatAdapter;
38 import jalview.io.BackupFiles;
39 import jalview.io.BioJsHTMLOutput;
40 import jalview.io.DataSourceType;
41 import jalview.io.FileFormat;
42 import jalview.io.FileFormatException;
43 import jalview.io.FileFormatI;
44 import jalview.io.FileFormats;
45 import jalview.io.FileLoader;
46 import jalview.io.HtmlSvgOutput;
47 import jalview.io.IdentifyFile;
48 import jalview.io.NewickFile;
49 import jalview.io.exceptions.ImageOutputException;
50 import jalview.schemes.ColourSchemeI;
51 import jalview.schemes.ColourSchemeProperty;
52 import jalview.structure.StructureCommandI;
53 import jalview.structure.StructureImportSettings.TFType;
54 import jalview.structure.StructureSelectionManager;
55 import jalview.util.ColorUtils;
56 import jalview.util.FileUtils;
57 import jalview.util.HttpUtils;
58 import jalview.util.IdUtils;
59 import jalview.util.IdUtils.IdType;
60 import jalview.util.ImageMaker;
61 import jalview.util.ImageMaker.TYPE;
62 import jalview.util.MessageManager;
63 import jalview.util.Platform;
64 import jalview.util.StringUtils;
65 import jalview.util.imagemaker.BitmapImageSizing;
71 private boolean headless;
73 private ArgParser argParser;
75 private Map<String, AlignFrame> afMap;
77 private Map<String, List<StructureViewer>> svMap;
79 private boolean commandArgsProvided = false;
81 private boolean argsWereParsed = false;
83 private List<String> errors = new ArrayList<>();
85 public Commands(ArgParser argparser, boolean headless)
87 this(Desktop.instance, argparser, headless);
90 public Commands(Desktop d, ArgParser argparser, boolean h)
92 argParser = argparser;
95 afMap = new HashMap<>();
98 protected boolean processArgs()
100 if (argParser == null)
105 boolean theseArgsWereParsed = false;
107 if (argParser != null && argParser.getLinkedIds() != null)
109 for (String id : argParser.getLinkedIds())
111 ArgValuesMap avm = argParser.getLinkedArgs(id);
112 theseArgsWereParsed = true;
113 boolean processLinkedOkay = processLinked(id);
114 theseArgsWereParsed &= processLinkedOkay;
116 processGroovyScript(id);
118 // wait around until alignFrame isn't busy
119 AlignFrame af = afMap.get(id);
120 while (af != null && af.getViewport().isCalcInProgress())
125 } catch (Exception q)
131 theseArgsWereParsed &= processImages(id);
133 if (processLinkedOkay)
135 theseArgsWereParsed &= processOutput(id);
139 if (avm.getBoolean(Arg.CLOSE))
144 af.closeMenuItem_actionPerformed(true);
152 // report errors - if any
153 String errorsRaised = errorsToString();
154 if (errorsRaised.trim().length() > 0)
157 "The following errors and warnings occurred whilst processing files:\n"
160 // gui errors reported in Jalview
162 if (argParser.getBoolean(Arg.QUIT))
164 Jalview.getInstance().exit(
165 "Exiting due to " + Arg.QUIT.argString() + " argument.",
169 // carry on with jalview.bin.Jalview
170 argsWereParsed = theseArgsWereParsed;
171 return argsWereParsed;
174 public boolean commandArgsProvided()
176 return commandArgsProvided;
179 public boolean argsWereParsed()
181 return argsWereParsed;
184 protected boolean processLinked(String id)
186 boolean theseArgsWereParsed = false;
187 ArgValuesMap avm = argParser.getLinkedArgs(id);
193 Boolean isError = Boolean.valueOf(false);
195 // set wrap scope here so it can be applied after structures are opened
196 boolean wrap = false;
198 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
200 commandArgsProvided = true;
201 final long progress = IdUtils.newId(IdType.PROGRESS);
203 boolean first = true;
204 boolean progressBarSet = false;
206 // Combine the APPEND and OPEN files into one list, along with whether it
207 // was APPEND or OPEN
208 List<ArgValue> openAvList = new ArrayList<>();
209 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
210 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
211 // sort avlist based on av.getArgIndex()
212 Collections.sort(openAvList);
213 for (ArgValue av : openAvList)
216 SubVals sv = av.getSubVals();
217 String openFile = av.getValue();
218 if (openFile == null)
221 theseArgsWereParsed = true;
225 if (!headless && desktop != null)
227 SwingUtilities.invokeLater(new Runnable()
232 desktop.setProgressBar(
233 MessageManager.getString(
234 "status.processing_commandline_args"),
239 progressBarSet = true;
243 if (!Platform.isJS())
245 * ignore in JavaScript -- can't just file existence - could load it?
250 if (!HttpUtils.startsWithHttpOrHttps(openFile))
252 if (!(new File(openFile)).exists())
254 addError("Can't find file '" + openFile + "'");
261 DataSourceType protocol = AppletFormatAdapter
262 .checkProtocol(openFile);
264 FileFormatI format = null;
267 format = new IdentifyFile().identify(openFile, protocol);
268 } catch (FileFormatException e1)
270 addError("Unknown file format for '" + openFile + "'");
276 // When to open a new AlignFrame
277 if (af == null || "true".equals(av.getSubVal("new"))
278 || a == Arg.OPEN || format == FileFormat.Jalview)
282 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
287 "Opening '" + openFile + "' in new alignment frame");
288 FileLoader fileLoader = new FileLoader(!headless);
289 boolean xception = false;
292 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
294 } catch (Throwable thr)
297 addError("Couldn't open '" + openFile + "' as " + format + " "
298 + thr.getLocalizedMessage()
299 + " (Enable debug for full stack trace)");
301 Console.debug("Exception when opening '" + openFile + "'", thr);
304 if (af == null && !xception)
306 addInfo("Ignoring '" + openFile
307 + "' - no alignment data found.");
313 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
314 null, "DEFAULT_COLOUR_PROT", "");
315 this.colourAlignFrame(af, colour);
317 // Change alignment frame title
318 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
323 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
327 String featuresfile = avm.getValueFromSubValOrArg(av,
329 if (featuresfile != null)
331 af.parseFeaturesFile(featuresfile,
332 AppletFormatAdapter.checkProtocol(featuresfile));
333 Jalview.testoutput(argParser, Arg.FEATURES,
334 "examples/testdata/plantfdx.features", featuresfile);
337 // Add annotations from file
338 String annotationsfile = avm.getValueFromSubValOrArg(av,
339 Arg.ANNOTATIONS, sv);
340 if (annotationsfile != null)
342 af.loadJalviewDataFile(annotationsfile, null, null, null);
343 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
344 "examples/testdata/plantfdx.annotations",
348 // Set or clear the sortbytree flag
349 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
353 af.getViewport().setSortByTree(true);
354 Jalview.testoutput(argParser, Arg.SORTBYTREE);
357 // Load tree from file
358 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
359 if (treefile != null)
363 NewickFile nf = new NewickFile(treefile,
364 AppletFormatAdapter.checkProtocol(treefile));
365 af.getViewport().setCurrentTree(
366 af.showNewickTree(nf, treefile).getTree());
367 Jalview.testoutput(argParser, Arg.TREE,
368 "examples/testdata/uniref50_test_tree", treefile);
369 } catch (IOException e)
371 addError("Couldn't add tree " + treefile, e);
376 // Show secondary structure annotations?
377 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
378 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
379 "STRUCT_FROM_PDB", true);
381 // Show sequence annotations?
382 boolean showAnnotations = avm.getFromSubValArgOrPref(
383 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
384 "SHOW_ANNOTATIONS", true);
386 boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
387 final AlignFrame _af = af;
388 // many of jalview's format/layout methods are only thread safe on the
389 // swingworker thread.
390 // all these methods should be on the alignViewController so it can
391 // coordinate such details
394 SwingUtilities.invokeAndWait(new Runnable()
400 _af.setAnnotationsVisibility(showSSAnnotations, true,
403 _af.setAnnotationsVisibility(showAnnotations, false, true);
405 // show temperature factor annotations?
408 // do this better (annotation types?)
409 List<String> hideThese = new ArrayList<>();
410 hideThese.add("Temperature Factor");
411 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
412 AlignmentUtils.showOrHideSequenceAnnotations(
413 _af.getCurrentView().getAlignment(), hideThese,
418 } catch (Exception x)
421 "Unexpected exception adjusting annotation row visibility.",
425 // wrap alignment? do this last for formatting reasons
426 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
427 "WRAP_ALIGNMENT", false);
428 // af.setWrapFormat(wrap) is applied after structures are opened for
429 // annotation reasons
431 // store the AlignFrame for this id
434 // is it its own structure file?
435 if (format.isStructureFile())
437 StructureSelectionManager ssm = StructureSelectionManager
438 .getStructureSelectionManager(Desktop.instance);
439 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
440 ssm.computeMapping(false, new SequenceI[] { seq }, null,
441 openFile, DataSourceType.FILE, null, null, null, false);
447 "Opening '" + openFile + "' in existing alignment frame");
449 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
451 : DataSourceType.FILE;
453 FileLoader fileLoader = new FileLoader(!headless);
454 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
458 Console.debug("Command " + Arg.APPEND + " executed successfully!");
461 if (first) // first=true means nothing opened
465 Jalview.exit("Could not open any files in headless mode",
470 Console.info("No more files to open");
473 if (progressBarSet && desktop != null)
475 desktop.setProgressBar(null, progress);
479 // open the structure (from same PDB file or given PDBfile)
480 if (!avm.getBoolean(Arg.NOSTRUCTURE))
483 AlignFrame af = afMap.get(id);
484 if (avm.containsArg(Arg.STRUCTURE))
486 commandArgsProvided = true;
489 ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
491 argParser.setStructureFilename(null);
492 String val = av.getValue();
493 SubVals subVals = av.getSubVals();
494 int argIndex = av.getArgIndex();
495 SequenceI seq = getSpecifiedSequence(af, avm, av);
498 // Could not find sequence from subId, let's assume the first
499 // sequence in the alignframe
500 AlignmentI al = af.getCurrentView().getAlignment();
501 seq = al.getSequenceAt(0);
506 addWarn("Could not find sequence for argument "
507 + Arg.STRUCTURE.argString() + "=" + val);
510 String structureFilename = null;
511 File structureFile = null;
512 if (subVals.getContent() != null
513 && subVals.getContent().length() != 0)
515 structureFilename = subVals.getContent();
516 Console.debug("Using structure file (from argument) '"
517 + structureFilename + "'");
518 structureFile = new File(structureFilename);
520 /* THIS DOESN'T WORK */
521 else if (seq.getAllPDBEntries() != null
522 && seq.getAllPDBEntries().size() > 0)
524 structureFile = new File(
525 seq.getAllPDBEntries().elementAt(0).getFile());
526 if (structureFile != null)
528 Console.debug("Using structure file (from sequence) '"
529 + structureFile.getAbsolutePath() + "'");
531 structureFilename = structureFile.getAbsolutePath();
534 if (structureFilename == null || structureFile == null)
536 addWarn("Not provided structure file with '" + val + "'");
540 if (!structureFile.exists())
542 addWarn("Structure file '" + structureFile.getAbsoluteFile()
547 Console.debug("Using structure file "
548 + structureFile.getAbsolutePath());
550 argParser.setStructureFilename(structureFilename);
552 // open structure view
553 AlignmentPanel ap = af.alignPanel;
556 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
557 StructureViewer.ViewerType.JMOL.toString());
560 String structureFilepath = structureFile.getAbsolutePath();
562 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
563 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
564 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
565 subVals, null, null, null);
566 if (paeFilepath != null)
568 File paeFile = new File(paeFilepath);
572 paeFilepath = paeFile.getCanonicalPath();
573 } catch (IOException e)
575 paeFilepath = paeFile.getAbsolutePath();
576 addWarn("Problem with the PAE file path: '"
577 + paeFile.getPath() + "'");
581 // showing annotations from structure file or not
582 boolean ssFromStructure = avm.getFromSubValArgOrPref(
583 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
586 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
587 // reference annotations
588 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
589 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
590 subVals, null, null, null);
591 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
592 subVals, null, "ADD_TEMPFACT_ANN", false, true);
593 TFType tft = notempfac ? null : TFType.DEFAULT;
594 if (tftString != null && !notempfac)
596 // get kind of temperature factor annotation
599 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
600 Console.debug("Obtained Temperature Factor type of '" + tft
601 + "' for structure '" + structureFilepath + "'");
602 } catch (IllegalArgumentException e)
604 // Just an error message!
605 StringBuilder sb = new StringBuilder().append("Cannot set ")
606 .append(Arg.TEMPFAC.argString()).append(" to '")
608 .append("', ignoring. Valid values are: ");
609 Iterator<TFType> it = Arrays.stream(TFType.values())
613 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
617 addWarn(sb.toString());
621 String sViewerName = avm.getFromSubValArgOrPref(
622 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
623 subVals, null, null, "jmol");
624 ViewerType viewerType = ViewerType.getFromString(sViewerName);
626 // TODO use ssFromStructure
627 StructureViewer structureViewer = StructureChooser
628 .openStructureFileForSequence(null, null, ap, seq, false,
629 structureFilepath, tft, paeFilepath, false,
630 ssFromStructure, false, viewerType);
632 if (structureViewer == null)
634 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
636 addError("Failed to import and open structure view for file '"
637 + structureFile + "'.");
644 while (structureViewer.isBusy() && tries > 0)
647 if (structureViewer.isBusy())
651 "Waiting for viewer for " + structureFilepath);
654 if (tries == 0 && structureViewer.isBusy())
656 addWarn("Gave up waiting for structure viewer to load file '"
658 + "'. Something may have gone wrong.");
660 } catch (Exception x)
662 addError("Exception whilst waiting for structure viewer "
663 + structureFilepath, x);
667 // add StructureViewer to svMap list
670 svMap = new HashMap<>();
672 if (svMap.get(id) == null)
674 svMap.put(id, new ArrayList<>());
676 svMap.get(id).add(structureViewer);
679 "Successfully opened viewer for " + structureFilepath);
681 if (avm.containsArg(Arg.STRUCTUREIMAGE))
683 for (ArgValue structureImageArgValue : avm
684 .getArgValueList(Arg.STRUCTUREIMAGE))
686 String structureImageFilename = argParser.makeSubstitutions(
687 structureImageArgValue.getValue(), id, true);
688 if (structureViewer != null && structureImageFilename != null)
690 SubVals structureImageSubVals = null;
691 structureImageSubVals = structureImageArgValue.getSubVals();
692 File structureImageFile = new File(structureImageFilename);
693 String width = avm.getValueFromSubValOrArg(
694 structureImageArgValue, Arg.WIDTH,
695 structureImageSubVals);
696 String height = avm.getValueFromSubValOrArg(
697 structureImageArgValue, Arg.HEIGHT,
698 structureImageSubVals);
699 String scale = avm.getValueFromSubValOrArg(
700 structureImageArgValue, Arg.SCALE,
701 structureImageSubVals);
702 String renderer = avm.getValueFromSubValOrArg(
703 structureImageArgValue, Arg.TEXTRENDERER,
704 structureImageSubVals);
705 String typeS = avm.getValueFromSubValOrArg(
706 structureImageArgValue, Arg.TYPE,
707 structureImageSubVals);
708 if (typeS == null || typeS.length() == 0)
710 typeS = FileUtils.getExtension(structureImageFile);
715 imageType = Enum.valueOf(TYPE.class,
716 typeS.toUpperCase(Locale.ROOT));
717 } catch (IllegalArgumentException e)
719 addWarn("Do not know image format '" + typeS
721 imageType = TYPE.PNG;
723 BitmapImageSizing userBis = ImageMaker
724 .parseScaleWidthHeightStrings(scale, width, height);
727 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
728 if (viewerType != ViewerType.JMOL)
730 addWarn("Cannot export image for structure viewer "
731 + viewerType.name() + " yet");
736 // Apply the temporary colourscheme to the linked alignment
737 // TODO: enhance for multiple linked alignments.
739 String imageColour = avm.getValueFromSubValOrArg(
740 structureImageArgValue, Arg.IMAGECOLOUR,
741 structureImageSubVals);
742 ColourSchemeI originalColourScheme = this
743 .getColourScheme(af);
744 this.colourAlignFrame(af, imageColour);
747 // custom image background colour
749 String bgcolourstring = avm.getValueFromSubValOrArg(
750 structureImageArgValue, Arg.BGCOLOUR,
751 structureImageSubVals);
752 Color bgcolour = null;
753 if (bgcolourstring != null && bgcolourstring.length() > 0)
755 bgcolour = ColorUtils.parseColourString(bgcolourstring);
756 if (bgcolour == null)
759 "Background colour string '" + bgcolourstring
760 + "' not recognised -- using default");
764 JalviewStructureDisplayI sview = structureViewer
765 .getJalviewStructureDisplay();
767 File sessionToRestore = null;
769 List<StructureCommandI> extraCommands = new ArrayList<>();
771 if (extraCommands.size() > 0 || bgcolour != null)
775 sessionToRestore = sview.saveSession();
776 } catch (Throwable t)
779 "Unable to save temporary session file before custom structure view export operation.");
786 if (bgcolour != null)
788 sview.getBinding().setBackgroundColour(bgcolour);
791 sview.getBinding().executeCommands(extraCommands, false,
792 "Executing Custom Commands");
794 // and export the view as an image
795 boolean success = this.checksBeforeWritingToFile(avm,
796 subVals, false, structureImageFilename,
797 "structure image", isError);
803 Console.debug("Rendering image to " + structureImageFile);
805 // TODO - extend StructureViewer / Binding with makePDBImage so
806 // we can do this with every viewer
811 // We don't expect class cast exception
812 AppJmol jmol = (AppJmol) sview;
813 jmol.makePDBImage(structureImageFile, imageType, renderer,
815 Console.info("Exported structure image to "
816 + structureImageFile);
818 // RESTORE SESSION AFTER EXPORT IF NEED BE
819 if (sessionToRestore != null)
822 "Restoring session from " + sessionToRestore);
824 sview.getBinding().restoreSession(
825 sessionToRestore.getAbsolutePath());
828 } catch (ImageOutputException ioexec)
831 "Unexpected error when restoring structure viewer session after custom view operations.");
838 this.colourAlignFrame(af, originalColourScheme);
839 } catch (Exception t)
842 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
849 argParser.setStructureFilename(null);
857 AlignFrame af = afMap.get(id);
860 af.setWrapFormat(wrap, true);
865 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
868 AlignFrame af = afMap.get(id);
869 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
870 .findAnnotation(PDBChain.class.getName().toString()))
872 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
873 af.alignPanel.av.getGlobalColourScheme(), 0);
874 acg.setSeqAssociated(true);
875 af.changeColour(acg);
876 Console.info("Changed colour " + acg.toString());
881 return theseArgsWereParsed && !isError;
884 protected void processGroovyScript(String id)
886 ArgValuesMap avm = argParser.getLinkedArgs(id);
887 AlignFrame af = afMap.get(id);
889 if (avm != null && !avm.containsArg(Arg.GROOVY))
897 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
900 if (avm.containsArg(Arg.GROOVY))
902 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
904 String groovyscript = groovyAv.getValue();
905 if (groovyscript != null)
907 // Execute the groovy script after we've done all the rendering stuff
908 // and before any images or figures are generated.
909 Console.info("Executing script " + groovyscript);
910 Jalview.getInstance().executeGroovyScript(groovyscript, af);
916 protected boolean processImages(String id)
918 ArgValuesMap avm = argParser.getLinkedArgs(id);
919 AlignFrame af = afMap.get(id);
921 if (avm != null && !avm.containsArg(Arg.IMAGE))
929 addWarn("Do not have an alignment window to create image from (id="
930 + id + "). Not proceeding.");
934 Boolean isError = Boolean.valueOf(false);
935 if (avm.containsArg(Arg.IMAGE))
937 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
939 String val = imageAv.getValue();
940 SubVals imageSubVals = imageAv.getSubVals();
941 String fileName = imageSubVals.getContent();
942 File file = new File(fileName);
943 String name = af.getName();
944 String renderer = avm.getValueFromSubValOrArg(imageAv,
945 Arg.TEXTRENDERER, imageSubVals);
946 if (renderer == null)
948 String type = "png"; // default
950 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
952 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
954 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
956 BitmapImageSizing userBis = ImageMaker
957 .parseScaleWidthHeightStrings(scale, width, height);
959 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
960 if (type == null && fileName != null)
962 for (String ext : new String[] { "svg", "png", "html", "eps" })
964 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
970 // for moment we disable JSON export
971 Cache.setPropsAreReadOnly(true);
972 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
974 String imageColour = avm.getValueFromSubValOrArg(imageAv,
975 Arg.IMAGECOLOUR, imageSubVals);
976 ColourSchemeI originalColourScheme = this.getColourScheme(af);
977 this.colourAlignFrame(af, imageColour);
979 Console.info("Writing " + file);
981 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
982 false, fileName, "image", isError);
994 Console.debug("Outputting type '" + type + "' to " + fileName);
995 af.createSVG(file, renderer);
999 Console.debug("Outputting type '" + type + "' to " + fileName);
1000 af.createPNG(file, null, userBis);
1004 Console.debug("Outputting type '" + type + "' to " + fileName);
1005 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1006 htmlSVG.exportHTML(fileName, renderer);
1011 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1014 BioJsHTMLOutput.refreshVersionInfo(
1015 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1016 } catch (URISyntaxException e)
1018 e.printStackTrace();
1020 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1021 bjs.exportHTML(fileName);
1025 Console.debug("Outputting EPS file: " + fileName);
1026 af.createEPS(file, renderer);
1030 Console.debug("Outputting ImageMap file: " + fileName);
1031 af.createImageMap(file, name);
1035 addWarn(Arg.IMAGE.argString() + " type '" + type
1036 + "' not known. Ignoring");
1039 } catch (Exception ioex)
1041 addError("Unexpected error during export to '" + fileName + "'",
1046 this.colourAlignFrame(af, originalColourScheme);
1052 protected boolean processOutput(String id)
1054 ArgValuesMap avm = argParser.getLinkedArgs(id);
1055 AlignFrame af = afMap.get(id);
1057 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1065 addWarn("Do not have an alignment window (id=" + id
1066 + "). Not proceeding.");
1070 Boolean isError = Boolean.valueOf(false);
1072 if (avm.containsArg(Arg.OUTPUT))
1074 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1076 String val = av.getValue();
1077 SubVals subVals = av.getSubVals();
1078 String fileName = subVals.getContent();
1079 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1080 File file = new File(fileName);
1082 String name = af.getName();
1083 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1085 FileFormats ffs = FileFormats.getInstance();
1086 List<String> validFormats = ffs.getWritableFormats(false);
1088 FileFormatI ff = null;
1089 if (format == null && fileName != null)
1091 FORMAT: for (String fname : validFormats)
1093 FileFormatI tff = ffs.forName(fname);
1094 String[] extensions = tff.getExtensions().split(",");
1095 for (String ext : extensions)
1097 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1100 format = ff.getName();
1106 if (ff == null && format != null)
1108 ff = ffs.forName(format);
1114 ff = FileFormat.Fasta;
1118 StringBuilder validSB = new StringBuilder();
1119 for (String f : validFormats)
1121 if (validSB.length() > 0)
1122 validSB.append(", ");
1124 FileFormatI tff = ffs.forName(f);
1125 validSB.append(" (");
1126 validSB.append(tff.getExtensions());
1127 validSB.append(")");
1130 addError("No valid format specified for "
1131 + Arg.OUTPUT.argString() + ". Valid formats are "
1132 + validSB.toString() + ".");
1137 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1138 fileName, ff.getName(), isError);
1144 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1145 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1146 !Platform.isHeadless());
1148 Console.info("Writing " + fileName);
1150 af.saveAlignment(fileName, ff, stdout, backups);
1151 if (af.isSaveAlignmentSuccessful())
1153 Console.debug("Written alignment '" + name + "' in "
1154 + ff.getName() + " format to '" + file + "'");
1158 addError("Error writing file '" + file + "' in " + ff.getName()
1169 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1172 SubVals subVals = av.getSubVals();
1173 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1174 SequenceI seq = null;
1175 if (subVals == null && idAv == null)
1177 if (af == null || af.getCurrentView() == null)
1181 AlignmentI al = af.getCurrentView().getAlignment();
1186 if (subVals != null)
1188 if (subVals.has(Arg.SEQID.getName()))
1190 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1192 else if (-1 < subVals.getIndex()
1193 && subVals.getIndex() < al.getSequences().size())
1195 seq = al.getSequenceAt(subVals.getIndex());
1198 if (seq == null && idAv != null)
1200 seq = al.findName(idAv.getValue());
1205 public AlignFrame[] getAlignFrames()
1207 AlignFrame[] afs = null;
1210 afs = (AlignFrame[]) afMap.values().toArray();
1216 public List<StructureViewer> getStructureViewers()
1218 List<StructureViewer> svs = null;
1221 for (List<StructureViewer> svList : svMap.values())
1225 svs = new ArrayList<>();
1233 private void colourAlignFrame(AlignFrame af, String colour)
1235 // use string "none" to remove colour scheme
1236 if (colour != null && "" != colour)
1238 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1239 af.getViewport(), af.getViewport().getAlignment(), colour);
1240 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1242 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1246 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1247 colourAlignFrame(af, cs);
1252 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1254 // Note that cs == null removes colour scheme from af
1255 af.changeColour(cs);
1258 private ColourSchemeI getColourScheme(AlignFrame af)
1260 return af.getViewport().getGlobalColourScheme();
1263 private void addInfo(String errorMessage)
1265 Console.info(errorMessage);
1266 errors.add(errorMessage);
1269 private void addWarn(String errorMessage)
1271 Console.warn(errorMessage);
1272 errors.add(errorMessage);
1275 private void addError(String errorMessage)
1277 addError(errorMessage, null);
1280 private void addError(String errorMessage, Exception e)
1282 Console.error(errorMessage, e);
1283 errors.add(errorMessage);
1286 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1287 SubVals subVal, boolean includeBackups, String filename,
1288 String adjective, Boolean isError)
1290 File file = new File(filename);
1292 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1293 null, "OVERWRITE_OUTPUT", false);
1294 boolean stdout = false;
1295 boolean backups = false;
1298 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1299 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1300 // otherwise if headless assume false, if not headless use the user
1301 // preference with default true.
1302 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1303 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1304 !Platform.isHeadless());
1307 if (file.exists() && !(overwrite || backups || stdout))
1309 addWarn("Won't overwrite file '" + filename + "' without "
1310 + Arg.OVERWRITE.argString()
1311 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1316 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1317 "MKDIRS_OUTPUT", false);
1319 if (!FileUtils.checkParentDir(file, mkdirs))
1321 addError("Directory '"
1322 + FileUtils.getParentDir(file).getAbsolutePath()
1323 + "' does not exist for " + adjective + " file '" + filename
1325 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1333 public List<String> getErrors()
1338 public String errorsToString()
1340 StringBuilder sb = new StringBuilder();
1341 for (String error : errors)
1343 if (sb.length() > 0)
1345 sb.append("- " + error);
1347 return sb.toString();