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.ImageMaker;
59 import jalview.util.ImageMaker.TYPE;
60 import jalview.util.MessageManager;
61 import jalview.util.Platform;
62 import jalview.util.StringUtils;
63 import jalview.util.imagemaker.BitmapImageSizing;
69 private boolean headless;
71 private ArgParser argParser;
73 private Map<String, AlignFrame> afMap;
75 private Map<String, List<StructureViewer>> svMap;
77 private boolean commandArgsProvided = false;
79 private boolean argsWereParsed = false;
81 private List<String> errors = new ArrayList<>();
83 public Commands(ArgParser argparser, boolean headless)
85 this(Desktop.instance, argparser, headless);
88 public Commands(Desktop d, ArgParser argparser, boolean h)
90 argParser = argparser;
93 afMap = new HashMap<>();
96 protected boolean processArgs()
98 if (argParser == null)
103 boolean theseArgsWereParsed = false;
105 if (argParser != null && argParser.getLinkedIds() != null)
107 for (String id : argParser.getLinkedIds())
109 ArgValuesMap avm = argParser.getLinkedArgs(id);
110 theseArgsWereParsed = true;
111 boolean processLinkedOkay = processLinked(id);
112 theseArgsWereParsed &= processLinkedOkay;
114 processGroovyScript(id);
116 // wait around until alignFrame isn't busy
117 AlignFrame af = afMap.get(id);
118 while (af != null && af.getViewport().isCalcInProgress())
123 } catch (Exception q)
129 theseArgsWereParsed &= processImages(id);
131 if (processLinkedOkay)
133 theseArgsWereParsed &= processOutput(id);
137 if (avm.getBoolean(Arg.CLOSE))
142 af.closeMenuItem_actionPerformed(true);
150 // report errors - if any
151 String errorsRaised = errorsToString();
152 if (errorsRaised.trim().length() > 0)
155 "The following errors and warnings occurred whilst processing files:\n"
158 // gui errors reported in Jalview
160 if (argParser.getBoolean(Arg.QUIT))
162 Jalview.getInstance().exit(
163 "Exiting due to " + Arg.QUIT.argString() + " argument.",
167 // carry on with jalview.bin.Jalview
168 argsWereParsed = theseArgsWereParsed;
169 return argsWereParsed;
172 public boolean commandArgsProvided()
174 return commandArgsProvided;
177 public boolean argsWereParsed()
179 return argsWereParsed;
182 protected boolean processLinked(String id)
184 boolean theseArgsWereParsed = false;
185 ArgValuesMap avm = argParser.getLinkedArgs(id);
191 Boolean isError = Boolean.valueOf(false);
193 // set wrap scope here so it can be applied after structures are opened
194 boolean wrap = false;
196 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
198 commandArgsProvided = true;
201 boolean first = true;
202 boolean progressBarSet = false;
204 // Combine the APPEND and OPEN files into one list, along with whether it
205 // was APPEND or OPEN
206 List<ArgValue> openAvList = new ArrayList<>();
207 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
208 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
209 // sort avlist based on av.getArgIndex()
210 Collections.sort(openAvList);
211 for (ArgValue av : openAvList)
214 SubVals sv = av.getSubVals();
215 String openFile = av.getValue();
216 if (openFile == null)
219 theseArgsWereParsed = true;
223 if (!headless && desktop != null)
225 desktop.setProgressBar(
226 MessageManager.getString(
227 "status.processing_commandline_args"),
228 progress = System.currentTimeMillis());
229 progressBarSet = true;
233 if (!Platform.isJS())
235 * ignore in JavaScript -- can't just file existence - could load it?
240 if (!HttpUtils.startsWithHttpOrHttps(openFile))
242 if (!(new File(openFile)).exists())
244 addError("Can't find file '" + openFile + "'");
251 DataSourceType protocol = AppletFormatAdapter
252 .checkProtocol(openFile);
254 FileFormatI format = null;
257 format = new IdentifyFile().identify(openFile, protocol);
258 } catch (FileFormatException e1)
260 addError("Unknown file format for '" + openFile + "'");
266 // When to open a new AlignFrame
267 if (af == null || "true".equals(av.getSubVal("new"))
268 || a == Arg.OPEN || format == FileFormat.Jalview)
272 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
277 "Opening '" + openFile + "' in new alignment frame");
278 FileLoader fileLoader = new FileLoader(!headless);
279 boolean xception = false;
282 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
284 } catch (Throwable thr)
287 addError("Couldn't open '" + openFile + "' as " + format + " "
288 + thr.getLocalizedMessage()
289 + " (Enable debug for full stack trace)");
291 Console.debug("Exception when opening '" + openFile + "'", thr);
294 if (af == null && !xception)
296 addInfo("Ignoring '" + openFile
297 + "' - no alignment data found.");
303 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
304 null, "DEFAULT_COLOUR_PROT", "");
305 this.colourAlignFrame(af, colour);
307 // Change alignment frame title
308 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
313 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
317 String featuresfile = avm.getValueFromSubValOrArg(av,
319 if (featuresfile != null)
321 af.parseFeaturesFile(featuresfile,
322 AppletFormatAdapter.checkProtocol(featuresfile));
323 Jalview.testoutput(argParser, Arg.FEATURES,
324 "examples/testdata/plantfdx.features", featuresfile);
327 // Add annotations from file
328 String annotationsfile = avm.getValueFromSubValOrArg(av,
329 Arg.ANNOTATIONS, sv);
330 if (annotationsfile != null)
332 af.loadJalviewDataFile(annotationsfile, null, null, null);
333 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
334 "examples/testdata/plantfdx.annotations",
338 // Set or clear the sortbytree flag
339 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
343 af.getViewport().setSortByTree(true);
344 Jalview.testoutput(argParser, Arg.SORTBYTREE);
347 // Load tree from file
348 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
349 if (treefile != null)
353 NewickFile nf = new NewickFile(treefile,
354 AppletFormatAdapter.checkProtocol(treefile));
355 af.getViewport().setCurrentTree(
356 af.showNewickTree(nf, treefile).getTree());
357 Jalview.testoutput(argParser, Arg.TREE,
358 "examples/testdata/uniref50_test_tree", treefile);
359 } catch (IOException e)
361 addError("Couldn't add tree " + treefile, e);
367 // Show secondary structure annotations?
368 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
369 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
370 "STRUCT_FROM_PDB", true);
372 // Show sequence annotations?
373 boolean showAnnotations = avm.getFromSubValArgOrPref(
374 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
375 "SHOW_ANNOTATIONS", true);
377 boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
378 final AlignFrame _af = af;
379 // many of jalview's format/layout methods are only thread safe on the swingworker thread.
380 // all these methods should be on the alignViewController so it can coordinate such details
383 SwingUtilities.invokeAndWait(new Runnable()
388 _af.setAnnotationsVisibility(showSSAnnotations, true,
391 _af.setAnnotationsVisibility(showAnnotations, false, true);
393 // show temperature factor annotations?
396 // do this better (annotation types?)
397 List<String> hideThese = new ArrayList<>();
398 hideThese.add("Temperature Factor");
399 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
400 AlignmentUtils.showOrHideSequenceAnnotations(
401 _af.getCurrentView().getAlignment(), hideThese,
406 } catch (Exception x)
409 "Unexpected exception adjusting annotation row visibility.",
413 // wrap alignment? do this last for formatting reasons
414 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
415 "WRAP_ALIGNMENT", false);
416 // af.setWrapFormat(wrap) is applied after structures are opened for
417 // annotation reasons
419 // store the AlignFrame for this id
422 // is it its own structure file?
423 if (format.isStructureFile())
425 StructureSelectionManager ssm = StructureSelectionManager
426 .getStructureSelectionManager(Desktop.instance);
427 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
428 ssm.computeMapping(false, new SequenceI[] { seq }, null,
429 openFile, DataSourceType.FILE, null, null, null, false);
435 "Opening '" + openFile + "' in existing alignment frame");
436 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
438 : DataSourceType.FILE;
439 FileLoader fileLoader = new FileLoader(!headless);
440 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
444 Console.debug("Command " + Arg.APPEND + " executed successfully!");
447 if (first) // first=true means nothing opened
451 Jalview.exit("Could not open any files in headless mode",
456 Console.info("No more files to open");
459 if (progressBarSet && desktop != null)
460 desktop.setProgressBar(null, progress);
464 // open the structure (from same PDB file or given PDBfile)
465 if (!avm.getBoolean(Arg.NOSTRUCTURE))
467 AlignFrame af = afMap.get(id);
468 if (avm.containsArg(Arg.STRUCTURE))
470 commandArgsProvided = true;
471 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
473 argParser.setStructureFilename(null);
474 String val = av.getValue();
475 SubVals subVals = av.getSubVals();
476 int argIndex = av.getArgIndex();
477 SequenceI seq = getSpecifiedSequence(af, avm, av);
480 // Could not find sequence from subId, let's assume the first
481 // sequence in the alignframe
482 AlignmentI al = af.getCurrentView().getAlignment();
483 seq = al.getSequenceAt(0);
488 addWarn("Could not find sequence for argument "
489 + Arg.STRUCTURE.argString() + "=" + val);
492 String structureFilename = null;
493 File structureFile = null;
494 if (subVals.getContent() != null
495 && subVals.getContent().length() != 0)
497 structureFilename = subVals.getContent();
498 Console.debug("Using structure file (from argument) '"
499 + structureFilename + "'");
500 structureFile = new File(structureFilename);
502 /* THIS DOESN'T WORK */
503 else if (seq.getAllPDBEntries() != null
504 && seq.getAllPDBEntries().size() > 0)
506 structureFile = new File(
507 seq.getAllPDBEntries().elementAt(0).getFile());
508 if (structureFile != null)
510 Console.debug("Using structure file (from sequence) '"
511 + structureFile.getAbsolutePath() + "'");
513 structureFilename = structureFile.getAbsolutePath();
516 if (structureFilename == null || structureFile == null)
518 addWarn("Not provided structure file with '" + val + "'");
522 if (!structureFile.exists())
524 addWarn("Structure file '" + structureFile.getAbsoluteFile()
529 Console.debug("Using structure file "
530 + structureFile.getAbsolutePath());
532 argParser.setStructureFilename(structureFilename);
534 // open structure view
535 AlignmentPanel ap = af.alignPanel;
538 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
539 StructureViewer.ViewerType.JMOL.toString());
542 String structureFilepath = structureFile.getAbsolutePath();
544 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
545 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
546 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
547 subVals, null, null, null);
548 if (paeFilepath != null)
550 File paeFile = new File(paeFilepath);
554 paeFilepath = paeFile.getCanonicalPath();
555 } catch (IOException e)
557 paeFilepath = paeFile.getAbsolutePath();
558 addWarn("Problem with the PAE file path: '"
559 + paeFile.getPath() + "'");
563 // showing annotations from structure file or not
564 boolean ssFromStructure = avm.getFromSubValArgOrPref(
565 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
568 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
569 // reference annotations
570 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
571 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
572 subVals, null, null, null);
573 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
574 subVals, null, "ADD_TEMPFACT_ANN", false, true);
575 TFType tft = notempfac ? null : TFType.DEFAULT;
576 if (tftString != null && !notempfac)
578 // get kind of temperature factor annotation
581 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
582 Console.debug("Obtained Temperature Factor type of '" + tft
583 + "' for structure '" + structureFilepath + "'");
584 } catch (IllegalArgumentException e)
586 // Just an error message!
587 StringBuilder sb = new StringBuilder().append("Cannot set ")
588 .append(Arg.TEMPFAC.argString()).append(" to '")
590 .append("', ignoring. Valid values are: ");
591 Iterator<TFType> it = Arrays.stream(TFType.values())
595 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
599 addWarn(sb.toString());
603 String sViewerName = avm.getFromSubValArgOrPref(
604 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
605 subVals, null, null, "jmol");
606 ViewerType viewerType = ViewerType.getFromString(sViewerName);
608 // TODO use ssFromStructure
609 StructureViewer structureViewer = StructureChooser
610 .openStructureFileForSequence(null, null, ap, seq, false,
611 structureFilepath, tft, paeFilepath, false,
612 ssFromStructure, false, viewerType);
614 if (structureViewer == null)
616 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
618 addError("Failed to import and open structure view for file '"
619 + structureFile + "'.");
626 while (structureViewer.isBusy() && tries > 0)
629 if (structureViewer.isBusy())
633 "Waiting for viewer for " + structureFilepath);
636 if (tries == 0 && structureViewer.isBusy())
638 addWarn("Gave up waiting for structure viewer to load file '"
640 + "'. Something may have gone wrong.");
642 } catch (Exception x)
644 addError("Exception whilst waiting for structure viewer "
645 + structureFilepath, x);
649 // add StructureViewer to svMap list
652 svMap = new HashMap<>();
654 if (svMap.get(id) == null)
656 svMap.put(id, new ArrayList<>());
658 svMap.get(id).add(structureViewer);
661 "Successfully opened viewer for " + structureFilepath);
663 if (avm.containsArg(Arg.STRUCTUREIMAGE))
665 for (ArgValue structureImageArgValue : avm
666 .getArgValueList(Arg.STRUCTUREIMAGE))
668 String structureImageFilename = argParser.makeSubstitutions(
669 structureImageArgValue.getValue(), id, true);
670 if (structureViewer != null && structureImageFilename != null)
672 SubVals structureImageSubVals = null;
673 structureImageSubVals = structureImageArgValue.getSubVals();
674 File structureImageFile = new File(structureImageFilename);
675 String width = avm.getValueFromSubValOrArg(
676 structureImageArgValue, Arg.WIDTH,
677 structureImageSubVals);
678 String height = avm.getValueFromSubValOrArg(
679 structureImageArgValue, Arg.HEIGHT,
680 structureImageSubVals);
681 String scale = avm.getValueFromSubValOrArg(
682 structureImageArgValue, Arg.SCALE,
683 structureImageSubVals);
684 String renderer = avm.getValueFromSubValOrArg(
685 structureImageArgValue, Arg.TEXTRENDERER,
686 structureImageSubVals);
687 String typeS = avm.getValueFromSubValOrArg(
688 structureImageArgValue, Arg.TYPE,
689 structureImageSubVals);
690 if (typeS == null || typeS.length() == 0)
692 typeS = FileUtils.getExtension(structureImageFile);
697 imageType = Enum.valueOf(TYPE.class,
698 typeS.toUpperCase(Locale.ROOT));
699 } catch (IllegalArgumentException e)
701 addWarn("Do not know image format '" + typeS
703 imageType = TYPE.PNG;
705 BitmapImageSizing userBis = ImageMaker
706 .parseScaleWidthHeightStrings(scale, width, height);
709 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
710 if (viewerType != ViewerType.JMOL)
712 addWarn("Cannot export image for structure viewer "
713 + viewerType.name() + " yet");
718 // Apply the temporary colourscheme to the linked alignment
719 // TODO: enhance for multiple linked alignments.
721 String imageColour = avm.getValueFromSubValOrArg(
722 structureImageArgValue, Arg.IMAGECOLOUR,
723 structureImageSubVals);
724 ColourSchemeI originalColourScheme = this
725 .getColourScheme(af);
726 this.colourAlignFrame(af, imageColour);
729 // custom image background colour
731 String bgcolourstring = avm.getValueFromSubValOrArg(
732 structureImageArgValue, Arg.BGCOLOUR,
733 structureImageSubVals);
734 Color bgcolour = null;
735 if (bgcolourstring != null && bgcolourstring.length() > 0)
737 bgcolour = ColorUtils.parseColourString(bgcolourstring);
738 if (bgcolour == null)
741 "Background colour string '" + bgcolourstring
742 + "' not recognised -- using default");
746 JalviewStructureDisplayI sview = structureViewer
747 .getJalviewStructureDisplay();
749 File sessionToRestore = null;
751 List<StructureCommandI> extraCommands = new ArrayList<>();
753 if (extraCommands.size() > 0 || bgcolour != null)
757 sessionToRestore = sview.saveSession();
758 } catch (Throwable t)
761 "Unable to save temporary session file before custom structure view export operation.");
768 if (bgcolour != null)
770 sview.getBinding().setBackgroundColour(bgcolour);
773 sview.getBinding().executeCommands(extraCommands, false,
774 "Executing Custom Commands");
776 // and export the view as an image
777 boolean success = this.checksBeforeWritingToFile(avm,
778 subVals, false, structureImageFilename,
779 "structure image", isError);
785 Console.debug("Rendering image to " + structureImageFile);
787 // TODO - extend StructureViewer / Binding with makePDBImage so
788 // we can do this with every viewer
793 // We don't expect class cast exception
794 AppJmol jmol = (AppJmol) sview;
795 jmol.makePDBImage(structureImageFile, imageType, renderer,
797 Console.info("Exported structure image to "
798 + structureImageFile);
800 // RESTORE SESSION AFTER EXPORT IF NEED BE
801 if (sessionToRestore != null)
804 "Restoring session from " + sessionToRestore);
806 sview.getBinding().restoreSession(
807 sessionToRestore.getAbsolutePath());
810 } catch (ImageOutputException ioexec)
813 "Unexpected error when restoring structure viewer session after custom view operations.");
820 this.colourAlignFrame(af, originalColourScheme);
821 } catch (Exception t)
824 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
831 argParser.setStructureFilename(null);
838 AlignFrame af = afMap.get(id);
841 af.setWrapFormat(wrap, true);
846 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
849 AlignFrame af = afMap.get(id);
850 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
851 .findAnnotation(PDBChain.class.getName().toString()))
853 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
854 af.alignPanel.av.getGlobalColourScheme(), 0);
855 acg.setSeqAssociated(true);
856 af.changeColour(acg);
857 Console.info("Changed colour " + acg.toString());
862 return theseArgsWereParsed && !isError;
865 protected void processGroovyScript(String id)
867 ArgValuesMap avm = argParser.getLinkedArgs(id);
868 AlignFrame af = afMap.get(id);
870 if (avm != null && !avm.containsArg(Arg.GROOVY))
878 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
881 if (avm.containsArg(Arg.GROOVY))
883 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
885 String groovyscript = groovyAv.getValue();
886 if (groovyscript != null)
888 // Execute the groovy script after we've done all the rendering stuff
889 // and before any images or figures are generated.
890 Console.info("Executing script " + groovyscript);
891 Jalview.getInstance().executeGroovyScript(groovyscript, af);
897 protected boolean processImages(String id)
899 ArgValuesMap avm = argParser.getLinkedArgs(id);
900 AlignFrame af = afMap.get(id);
902 if (avm != null && !avm.containsArg(Arg.IMAGE))
910 addWarn("Do not have an alignment window to create image from (id="
911 + id + "). Not proceeding.");
915 Boolean isError = Boolean.valueOf(false);
916 if (avm.containsArg(Arg.IMAGE))
918 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
920 String val = imageAv.getValue();
921 SubVals imageSubVals = imageAv.getSubVals();
922 String fileName = imageSubVals.getContent();
923 File file = new File(fileName);
924 String name = af.getName();
925 String renderer = avm.getValueFromSubValOrArg(imageAv,
926 Arg.TEXTRENDERER, imageSubVals);
927 if (renderer == null)
929 String type = "png"; // default
931 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
933 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
935 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
937 BitmapImageSizing userBis = ImageMaker
938 .parseScaleWidthHeightStrings(scale, width, height);
940 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
941 if (type == null && fileName != null)
943 for (String ext : new String[] { "svg", "png", "html", "eps" })
945 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
951 // for moment we disable JSON export
952 Cache.setPropsAreReadOnly(true);
953 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
955 String imageColour = avm.getValueFromSubValOrArg(imageAv,
956 Arg.IMAGECOLOUR, imageSubVals);
957 ColourSchemeI originalColourScheme = this.getColourScheme(af);
958 this.colourAlignFrame(af, imageColour);
960 Console.info("Writing " + file);
962 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
963 false, fileName, "image", isError);
975 Console.debug("Outputting type '" + type + "' to " + fileName);
976 af.createSVG(file, renderer);
980 Console.debug("Outputting type '" + type + "' to " + fileName);
981 af.createPNG(file, null, userBis);
985 Console.debug("Outputting type '" + type + "' to " + fileName);
986 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
987 htmlSVG.exportHTML(fileName, renderer);
992 "Outputting BioJS MSA Viwer HTML file: " + fileName);
995 BioJsHTMLOutput.refreshVersionInfo(
996 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
997 } catch (URISyntaxException e)
1001 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1002 bjs.exportHTML(fileName);
1006 Console.debug("Outputting EPS file: " + fileName);
1007 af.createEPS(file, renderer);
1011 Console.debug("Outputting ImageMap file: " + fileName);
1012 af.createImageMap(file, name);
1016 addWarn(Arg.IMAGE.argString() + " type '" + type
1017 + "' not known. Ignoring");
1020 } catch (Exception ioex)
1022 addError("Unexpected error during export to '" + fileName + "'",
1027 this.colourAlignFrame(af, originalColourScheme);
1033 protected boolean processOutput(String id)
1035 ArgValuesMap avm = argParser.getLinkedArgs(id);
1036 AlignFrame af = afMap.get(id);
1038 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1046 addWarn("Do not have an alignment window (id=" + id
1047 + "). Not proceeding.");
1051 Boolean isError = Boolean.valueOf(false);
1053 if (avm.containsArg(Arg.OUTPUT))
1055 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1057 String val = av.getValue();
1058 SubVals subVals = av.getSubVals();
1059 String fileName = subVals.getContent();
1060 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1061 File file = new File(fileName);
1063 String name = af.getName();
1064 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1066 FileFormats ffs = FileFormats.getInstance();
1067 List<String> validFormats = ffs.getWritableFormats(false);
1069 FileFormatI ff = null;
1070 if (format == null && fileName != null)
1072 FORMAT: for (String fname : validFormats)
1074 FileFormatI tff = ffs.forName(fname);
1075 String[] extensions = tff.getExtensions().split(",");
1076 for (String ext : extensions)
1078 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1081 format = ff.getName();
1087 if (ff == null && format != null)
1089 ff = ffs.forName(format);
1095 ff = FileFormat.Fasta;
1099 StringBuilder validSB = new StringBuilder();
1100 for (String f : validFormats)
1102 if (validSB.length() > 0)
1103 validSB.append(", ");
1105 FileFormatI tff = ffs.forName(f);
1106 validSB.append(" (");
1107 validSB.append(tff.getExtensions());
1108 validSB.append(")");
1111 addError("No valid format specified for "
1112 + Arg.OUTPUT.argString() + ". Valid formats are "
1113 + validSB.toString() + ".");
1118 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1119 fileName, ff.getName(), isError);
1125 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1126 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1127 !Platform.isHeadless());
1129 Console.info("Writing " + fileName);
1131 af.saveAlignment(fileName, ff, stdout, backups);
1132 if (af.isSaveAlignmentSuccessful())
1134 Console.debug("Written alignment '" + name + "' in "
1135 + ff.getName() + " format to '" + file + "'");
1139 addError("Error writing file '" + file + "' in " + ff.getName()
1150 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1153 SubVals subVals = av.getSubVals();
1154 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1155 SequenceI seq = null;
1156 if (subVals == null && idAv == null)
1158 if (af == null || af.getCurrentView() == null)
1162 AlignmentI al = af.getCurrentView().getAlignment();
1167 if (subVals != null)
1169 if (subVals.has(Arg.SEQID.getName()))
1171 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1173 else if (-1 < subVals.getIndex()
1174 && subVals.getIndex() < al.getSequences().size())
1176 seq = al.getSequenceAt(subVals.getIndex());
1179 if (seq == null && idAv != null)
1181 seq = al.findName(idAv.getValue());
1186 public AlignFrame[] getAlignFrames()
1188 AlignFrame[] afs = null;
1191 afs = (AlignFrame[]) afMap.values().toArray();
1197 public List<StructureViewer> getStructureViewers()
1199 List<StructureViewer> svs = null;
1202 for (List<StructureViewer> svList : svMap.values())
1206 svs = new ArrayList<>();
1214 private void colourAlignFrame(AlignFrame af, String colour)
1216 // use string "none" to remove colour scheme
1217 if (colour != null && "" != colour)
1219 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1220 af.getViewport(), af.getViewport().getAlignment(), colour);
1221 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1223 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1227 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1228 colourAlignFrame(af, cs);
1233 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1235 // Note that cs == null removes colour scheme from af
1236 af.changeColour(cs);
1239 private ColourSchemeI getColourScheme(AlignFrame af)
1241 return af.getViewport().getGlobalColourScheme();
1244 private void addInfo(String errorMessage)
1246 Console.info(errorMessage);
1247 errors.add(errorMessage);
1250 private void addWarn(String errorMessage)
1252 Console.warn(errorMessage);
1253 errors.add(errorMessage);
1256 private void addError(String errorMessage)
1258 addError(errorMessage, null);
1261 private void addError(String errorMessage, Exception e)
1263 Console.error(errorMessage, e);
1264 errors.add(errorMessage);
1267 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1268 SubVals subVal, boolean includeBackups, String filename,
1269 String adjective, Boolean isError)
1271 File file = new File(filename);
1273 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1274 null, "OVERWRITE_OUTPUT", false);
1275 boolean stdout = false;
1276 boolean backups = false;
1279 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1280 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1281 // otherwise if headless assume false, if not headless use the user
1282 // preference with default true.
1283 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1284 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1285 !Platform.isHeadless());
1288 if (file.exists() && !(overwrite || backups || stdout))
1290 addWarn("Won't overwrite file '" + filename + "' without "
1291 + Arg.OVERWRITE.argString()
1292 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1297 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1298 "MKDIRS_OUTPUT", false);
1300 if (!FileUtils.checkParentDir(file, mkdirs))
1302 addError("Directory '"
1303 + FileUtils.getParentDir(file).getAbsolutePath()
1304 + "' does not exist for " + adjective + " file '" + filename
1306 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1314 public List<String> getErrors()
1319 public String errorsToString()
1321 StringBuilder sb = new StringBuilder();
1322 for (String error : errors)
1324 if (sb.length() > 0)
1326 sb.append("- " + error);
1328 return sb.toString();