5 import java.io.IOException;
6 import java.lang.reflect.Field;
7 import java.net.URISyntaxException;
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.Collections;
11 import java.util.HashMap;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Locale;
17 import jalview.analysis.AlignmentUtils;
18 import jalview.api.structures.JalviewStructureDisplayI;
19 import jalview.bin.Jalview.ExitCode;
20 import jalview.bin.argparser.Arg;
21 import jalview.bin.argparser.ArgParser;
22 import jalview.bin.argparser.ArgValue;
23 import jalview.bin.argparser.ArgValuesMap;
24 import jalview.bin.argparser.SubVals;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceI;
27 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
28 import jalview.ext.jmol.JalviewJmolBinding;
29 import jalview.ext.jmol.JmolCommands;
30 import jalview.gui.AlignFrame;
31 import jalview.gui.AlignmentPanel;
32 import jalview.gui.AppJmol;
33 import jalview.gui.Desktop;
34 import jalview.gui.Preferences;
35 import jalview.gui.StructureChooser;
36 import jalview.gui.StructureViewer;
37 import jalview.gui.StructureViewer.ViewerType;
38 import jalview.io.AppletFormatAdapter;
39 import jalview.io.BackupFiles;
40 import jalview.io.BioJsHTMLOutput;
41 import jalview.io.DataSourceType;
42 import jalview.io.FileFormat;
43 import jalview.io.FileFormatException;
44 import jalview.io.FileFormatI;
45 import jalview.io.FileFormats;
46 import jalview.io.FileLoader;
47 import jalview.io.HtmlSvgOutput;
48 import jalview.io.IdentifyFile;
49 import jalview.io.NewickFile;
50 import jalview.io.exceptions.ImageOutputException;
51 import jalview.schemes.ColourSchemeI;
52 import jalview.schemes.ColourSchemeProperty;
53 import jalview.structure.StructureCommandI;
54 import jalview.structure.StructureCommandsI;
55 import jalview.structure.StructureImportSettings.TFType;
56 import jalview.structure.StructureSelectionManager;
57 import jalview.util.ColorUtils;
58 import jalview.util.FileUtils;
59 import jalview.util.HttpUtils;
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;
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 desktop.setProgressBar(
228 MessageManager.getString(
229 "status.processing_commandline_args"),
230 progress = System.currentTimeMillis());
231 progressBarSet = true;
235 if (!Platform.isJS())
237 * ignore in JavaScript -- can't just file existence - could load it?
242 if (!HttpUtils.startsWithHttpOrHttps(openFile))
244 if (!(new File(openFile)).exists())
246 addError("Can't find file '" + openFile + "'");
253 DataSourceType protocol = AppletFormatAdapter
254 .checkProtocol(openFile);
256 FileFormatI format = null;
259 format = new IdentifyFile().identify(openFile, protocol);
260 } catch (FileFormatException e1)
262 addError("Unknown file format for '" + openFile + "'");
268 // When to open a new AlignFrame
269 if (af == null || "true".equals(av.getSubVal("new"))
270 || a == Arg.OPEN || format == FileFormat.Jalview)
274 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
279 "Opening '" + openFile + "' in new alignment frame");
280 FileLoader fileLoader = new FileLoader(!headless);
281 boolean xception = false;
284 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
286 } catch (Throwable thr)
289 addError("Couldn't open '" + openFile + "' as " + format + " "
290 + thr.getLocalizedMessage()
291 + " (Enable debug for full stack trace)");
293 Console.debug("Exception when opening '" + openFile + "'", thr);
296 if (af == null && !xception)
298 addInfo("Ignoring '" + openFile
299 + "' - no alignment data found.");
305 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
306 null, "DEFAULT_COLOUR_PROT", "");
307 this.colourAlignFrame(af, colour);
309 // Change alignment frame title
310 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
315 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
319 String featuresfile = avm.getValueFromSubValOrArg(av,
321 if (featuresfile != null)
323 af.parseFeaturesFile(featuresfile,
324 AppletFormatAdapter.checkProtocol(featuresfile));
325 Jalview.testoutput(argParser, Arg.FEATURES,
326 "examples/testdata/plantfdx.features", featuresfile);
329 // Add annotations from file
330 String annotationsfile = avm.getValueFromSubValOrArg(av,
331 Arg.ANNOTATIONS, sv);
332 if (annotationsfile != null)
334 af.loadJalviewDataFile(annotationsfile, null, null, null);
335 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
336 "examples/testdata/plantfdx.annotations",
340 // Set or clear the sortbytree flag
341 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
345 af.getViewport().setSortByTree(true);
346 Jalview.testoutput(argParser, Arg.SORTBYTREE);
349 // Load tree from file
350 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
351 if (treefile != null)
355 NewickFile nf = new NewickFile(treefile,
356 AppletFormatAdapter.checkProtocol(treefile));
357 af.getViewport().setCurrentTree(
358 af.showNewickTree(nf, treefile).getTree());
359 Jalview.testoutput(argParser, Arg.TREE,
360 "examples/testdata/uniref50_test_tree", treefile);
361 } catch (IOException e)
363 addError("Couldn't add tree " + treefile, e);
368 // Show secondary structure annotations?
369 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
370 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
371 "STRUCT_FROM_PDB", true);
372 af.setAnnotationsVisibility(showSSAnnotations, true, false);
374 // Show sequence annotations?
375 boolean showAnnotations = avm.getFromSubValArgOrPref(
376 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
377 "SHOW_ANNOTATIONS", true);
378 af.setAnnotationsVisibility(showAnnotations, false, true);
380 // show temperature factor annotations?
381 if (avm.getBoolean(Arg.NOTEMPFAC))
383 // do this better (annotation types?)
384 List<String> hideThese = new ArrayList<>();
385 hideThese.add("Temperature Factor");
386 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
387 AlignmentUtils.showOrHideSequenceAnnotations(
388 af.getCurrentView().getAlignment(), hideThese, null,
392 // wrap alignment? do this last for formatting reasons
393 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
394 "WRAP_ALIGNMENT", false);
395 // af.setWrapFormat(wrap) is applied after structures are opened for
396 // annotation reasons
398 // store the AlignFrame for this id
401 // is it its own structure file?
402 if (format.isStructureFile())
404 StructureSelectionManager ssm = StructureSelectionManager
405 .getStructureSelectionManager(Desktop.instance);
406 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
407 ssm.computeMapping(false, new SequenceI[] { seq }, null,
408 openFile, DataSourceType.FILE, null, null, null, false);
414 "Opening '" + openFile + "' in existing alignment frame");
415 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
417 : DataSourceType.FILE;
418 FileLoader fileLoader = new FileLoader(!headless);
419 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
423 Console.debug("Command " + Arg.APPEND + " executed successfully!");
426 if (first) // first=true means nothing opened
430 Jalview.exit("Could not open any files in headless mode",
435 Console.info("No more files to open");
438 if (progressBarSet && desktop != null)
439 desktop.setProgressBar(null, progress);
443 // open the structure (from same PDB file or given PDBfile)
444 if (!avm.getBoolean(Arg.NOSTRUCTURE))
446 AlignFrame af = afMap.get(id);
447 if (avm.containsArg(Arg.STRUCTURE))
449 commandArgsProvided = true;
450 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
452 argParser.setStructureFilename(null);
453 String val = av.getValue();
454 SubVals subVals = av.getSubVals();
455 int argIndex = av.getArgIndex();
456 SequenceI seq = getSpecifiedSequence(af, avm, av);
459 // Could not find sequence from subId, let's assume the first
460 // sequence in the alignframe
461 AlignmentI al = af.getCurrentView().getAlignment();
462 seq = al.getSequenceAt(0);
467 addWarn("Could not find sequence for argument "
468 + Arg.STRUCTURE.argString() + "=" + val);
471 String structureFilename = null;
472 File structureFile = null;
473 if (subVals.getContent() != null
474 && subVals.getContent().length() != 0)
476 structureFilename = subVals.getContent();
477 Console.debug("Using structure file (from argument) '"
478 + structureFilename + "'");
479 structureFile = new File(structureFilename);
481 /* THIS DOESN'T WORK */
482 else if (seq.getAllPDBEntries() != null
483 && seq.getAllPDBEntries().size() > 0)
485 structureFile = new File(
486 seq.getAllPDBEntries().elementAt(0).getFile());
487 if (structureFile != null)
489 Console.debug("Using structure file (from sequence) '"
490 + structureFile.getAbsolutePath() + "'");
492 structureFilename = structureFile.getAbsolutePath();
495 if (structureFilename == null || structureFile == null)
497 addWarn("Not provided structure file with '" + val + "'");
501 if (!structureFile.exists())
503 addWarn("Structure file '" + structureFile.getAbsoluteFile()
508 Console.debug("Using structure file "
509 + structureFile.getAbsolutePath());
511 argParser.setStructureFilename(structureFilename);
513 // open structure view
514 AlignmentPanel ap = af.alignPanel;
517 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
518 StructureViewer.ViewerType.JMOL.toString());
521 String structureFilepath = structureFile.getAbsolutePath();
523 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
524 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
525 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
526 subVals, null, null, null);
527 if (paeFilepath != null)
529 File paeFile = new File(paeFilepath);
533 paeFilepath = paeFile.getCanonicalPath();
534 } catch (IOException e)
536 paeFilepath = paeFile.getAbsolutePath();
537 addWarn("Problem with the PAE file path: '"
538 + paeFile.getPath() + "'");
542 // showing annotations from structure file or not
543 boolean ssFromStructure = avm.getFromSubValArgOrPref(
544 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
547 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
548 // reference annotations
549 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
550 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
551 subVals, null, null, null);
552 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
553 subVals, null, "ADD_TEMPFACT_ANN", false, true);
554 TFType tft = notempfac ? null : TFType.DEFAULT;
555 if (tftString != null && !notempfac)
557 // get kind of temperature factor annotation
560 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
561 Console.debug("Obtained Temperature Factor type of '" + tft
562 + "' for structure '" + structureFilepath + "'");
563 } catch (IllegalArgumentException e)
565 // Just an error message!
566 StringBuilder sb = new StringBuilder().append("Cannot set ")
567 .append(Arg.TEMPFAC.argString()).append(" to '")
569 .append("', ignoring. Valid values are: ");
570 Iterator<TFType> it = Arrays.stream(TFType.values())
574 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
578 addWarn(sb.toString());
582 String sViewerName = avm.getFromSubValArgOrPref(
583 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
584 subVals, null, null, "jmol");
585 ViewerType viewerType = ViewerType.getFromString(sViewerName);
587 // TODO use ssFromStructure
588 StructureViewer structureViewer = StructureChooser
589 .openStructureFileForSequence(null, null, ap, seq, false,
590 structureFilepath, tft, paeFilepath, false,
591 ssFromStructure, false, viewerType);
593 if (structureViewer == null)
595 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
597 addError("Failed to import and open structure view for file '"
598 + structureFile + "'.");
605 while (structureViewer.isBusy() && tries > 0)
608 if (structureViewer.isBusy())
612 "Waiting for viewer for " + structureFilepath);
615 if (tries == 0 && structureViewer.isBusy())
617 addWarn("Gave up waiting for structure viewer to load file '"
619 + "'. Something may have gone wrong.");
621 } catch (Exception x)
623 addError("Exception whilst waiting for structure viewer "
624 + structureFilepath, x);
628 // add StructureViewer to svMap list
631 svMap = new HashMap<>();
633 if (svMap.get(id) == null)
635 svMap.put(id, new ArrayList<>());
637 svMap.get(id).add(structureViewer);
640 "Successfully opened viewer for " + structureFilepath);
642 if (avm.containsArg(Arg.STRUCTUREIMAGE))
644 for (ArgValue structureImageArgValue : avm
645 .getArgValueList(Arg.STRUCTUREIMAGE))
647 String structureImageFilename = argParser.makeSubstitutions(
648 structureImageArgValue.getValue(), id, true);
649 if (structureViewer != null && structureImageFilename != null)
651 SubVals structureImageSubVals = null;
652 structureImageSubVals = structureImageArgValue.getSubVals();
653 File structureImageFile = new File(structureImageFilename);
654 String width = avm.getValueFromSubValOrArg(
655 structureImageArgValue, Arg.WIDTH,
656 structureImageSubVals);
657 String height = avm.getValueFromSubValOrArg(
658 structureImageArgValue, Arg.HEIGHT,
659 structureImageSubVals);
660 String scale = avm.getValueFromSubValOrArg(
661 structureImageArgValue, Arg.SCALE,
662 structureImageSubVals);
663 String renderer = avm.getValueFromSubValOrArg(
664 structureImageArgValue, Arg.TEXTRENDERER,
665 structureImageSubVals);
666 String typeS = avm.getValueFromSubValOrArg(
667 structureImageArgValue, Arg.TYPE,
668 structureImageSubVals);
669 if (typeS == null || typeS.length() == 0)
671 typeS = FileUtils.getExtension(structureImageFile);
676 imageType = Enum.valueOf(TYPE.class,
677 typeS.toUpperCase(Locale.ROOT));
678 } catch (IllegalArgumentException e)
680 addWarn("Do not know image format '" + typeS
682 imageType = TYPE.PNG;
684 BitmapImageSizing userBis = ImageMaker
685 .parseScaleWidthHeightStrings(scale, width, height);
688 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
689 if (viewerType!=ViewerType.JMOL) {
690 addWarn("Cannot export image for structure viewer "
691 + viewerType.name() + " yet");
696 // Apply the temporary colourscheme to the linked alignment
697 // TODO: enhance for multiple linked alignments.
699 String imageColour = avm.getValueFromSubValOrArg(
700 structureImageArgValue, Arg.IMAGECOLOUR,
701 structureImageSubVals);
702 ColourSchemeI originalColourScheme = this
703 .getColourScheme(af);
704 this.colourAlignFrame(af, imageColour);
707 // custom image background colour
709 String bgcolourstring = avm.getValueFromSubValOrArg(
710 structureImageArgValue, Arg.BGCOLOUR,
711 structureImageSubVals);
712 Color bgcolour = null;
713 if (bgcolourstring != null && bgcolourstring.length() > 0)
718 // FIXME: Why not use ColorUtils.parseColourString(bgcolourstring) - this is consistent and backwards compatible
720 if (bgcolourstring.charAt(0) == '#')
722 bgcolour = Color.decode(bgcolourstring);
726 Field field = Color.class.getField(bgcolourstring);
727 bgcolour = (Color) field.get(null);
729 } catch (IllegalArgumentException | NoSuchFieldException
730 | SecurityException | IllegalAccessException nfe)
733 "Background colour string '" + bgcolourstring
734 + "' not recognised -- using default");
735 //bgcolour = Color.black;
739 JalviewStructureDisplayI sview = structureViewer
740 .getJalviewStructureDisplay();
742 File sessionToRestore = null;
744 List<StructureCommandI> extraCommands=new ArrayList<>();
746 if (extraCommands.size() > 0 || bgcolour!=null)
749 sessionToRestore = sview.saveSession();
750 } catch (Throwable t)
752 Console.warn("Unable to save temporary session file before custom structure view export operation.");
759 sview.getBinding().setBackgroundColour(bgcolour);
761 sview.getBinding().executeCommands(extraCommands, false, "Executing Custom Commands");
763 // and export the view as an image
764 boolean success = this.checksBeforeWritingToFile(avm,
765 subVals, false, structureImageFilename,
766 "structure image", isError);
773 "Rendering image to " + structureImageFile);
775 // TODO - extend StructureViewer / Binding with makePDBImage so we can do this with every viewer
779 // We don't expect class cast exception
780 AppJmol jmol = (AppJmol) sview;
781 jmol.makePDBImage(structureImageFile, imageType,
783 Console.debug("Finished Rendering image to "
784 + structureImageFile);
786 // RESTORE SESSION AFTER EXPORT IF NEED BE
787 if (sessionToRestore != null)
789 Console.debug("Restoring session from "
792 sview.getBinding().restoreSession(sessionToRestore.getAbsolutePath());
795 } catch (ImageOutputException ioexc)
797 addError("Unexpected error whilst exporting image to "
798 + structureImageFile, ioexc);
805 this.colourAlignFrame(af, originalColourScheme);
806 } catch (Exception t)
808 addError("Unexpected error when restoring colourscheme to alignment after temporary change for export.",t);
814 argParser.setStructureFilename(null);
821 AlignFrame af = afMap.get(id);
824 af.setWrapFormat(wrap, true);
829 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
832 AlignFrame af = afMap.get(id);
833 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
834 .findAnnotation(PDBChain.class.getName().toString()))
836 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
837 af.alignPanel.av.getGlobalColourScheme(), 0);
838 acg.setSeqAssociated(true);
839 af.changeColour(acg);
840 Console.info("Changed colour " + acg.toString());
845 return theseArgsWereParsed && !isError;
848 protected void processGroovyScript(String id)
850 ArgValuesMap avm = argParser.getLinkedArgs(id);
851 AlignFrame af = afMap.get(id);
855 addWarn("Did not have an alignment window for id=" + id);
859 if (avm.containsArg(Arg.GROOVY))
861 String groovyscript = avm.getValue(Arg.GROOVY);
862 if (groovyscript != null)
864 // Execute the groovy script after we've done all the rendering stuff
865 // and before any images or figures are generated.
866 Console.info("Executing script " + groovyscript);
867 Jalview.getInstance().executeGroovyScript(groovyscript, af);
872 protected boolean processImages(String id)
874 ArgValuesMap avm = argParser.getLinkedArgs(id);
875 AlignFrame af = afMap.get(id);
879 addWarn("Did not have an alignment window for id=" + id);
883 Boolean isError = Boolean.valueOf(false);
884 if (avm.containsArg(Arg.IMAGE))
886 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
888 String val = imageAv.getValue();
889 SubVals imageSubVals = imageAv.getSubVals();
890 String fileName = imageSubVals.getContent();
891 File file = new File(fileName);
892 String name = af.getName();
893 String renderer = avm.getValueFromSubValOrArg(imageAv,
894 Arg.TEXTRENDERER, imageSubVals);
895 if (renderer == null)
897 String type = "png"; // default
899 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
901 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
903 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
905 BitmapImageSizing userBis = ImageMaker
906 .parseScaleWidthHeightStrings(scale, width, height);
908 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
909 if (type == null && fileName != null)
911 for (String ext : new String[] { "svg", "png", "html", "eps" })
913 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
919 // for moment we disable JSON export
920 Cache.setPropsAreReadOnly(true);
921 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
923 String imageColour = avm.getValueFromSubValOrArg(imageAv,
924 Arg.IMAGECOLOUR, imageSubVals);
925 ColourSchemeI originalColourScheme = this.getColourScheme(af);
926 this.colourAlignFrame(af, imageColour);
928 Console.info("Writing " + file);
930 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
931 false, fileName, "image", isError);
943 Console.debug("Outputting type '" + type + "' to " + fileName);
944 af.createSVG(file, renderer);
948 Console.debug("Outputting type '" + type + "' to " + fileName);
949 af.createPNG(file, null, userBis);
953 Console.debug("Outputting type '" + type + "' to " + fileName);
954 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
955 htmlSVG.exportHTML(fileName, renderer);
960 "Outputting BioJS MSA Viwer HTML file: " + fileName);
963 BioJsHTMLOutput.refreshVersionInfo(
964 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
965 } catch (URISyntaxException e)
969 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
970 bjs.exportHTML(fileName);
974 Console.debug("Outputting EPS file: " + fileName);
975 af.createEPS(file, renderer);
979 Console.debug("Outputting ImageMap file: " + fileName);
980 af.createImageMap(file, name);
984 addWarn(Arg.IMAGE.argString() + " type '" + type
985 + "' not known. Ignoring");
988 } catch (Exception ioex)
990 addError("Unexpected error during export to '" + fileName + "'",
995 this.colourAlignFrame(af, originalColourScheme);
1001 protected boolean processOutput(String id)
1003 ArgValuesMap avm = argParser.getLinkedArgs(id);
1004 AlignFrame af = afMap.get(id);
1008 addWarn("Did not have an alignment window for id=" + id);
1012 Boolean isError = Boolean.valueOf(false);
1014 if (avm.containsArg(Arg.OUTPUT))
1016 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1018 String val = av.getValue();
1019 SubVals subVals = av.getSubVals();
1020 String fileName = subVals.getContent();
1021 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1022 File file = new File(fileName);
1024 String name = af.getName();
1025 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1027 FileFormats ffs = FileFormats.getInstance();
1028 List<String> validFormats = ffs.getWritableFormats(false);
1030 FileFormatI ff = null;
1031 if (format == null && fileName != null)
1033 FORMAT: for (String fname : validFormats)
1035 FileFormatI tff = ffs.forName(fname);
1036 String[] extensions = tff.getExtensions().split(",");
1037 for (String ext : extensions)
1039 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1042 format = ff.getName();
1048 if (ff == null && format != null)
1050 ff = ffs.forName(format);
1056 ff = FileFormat.Fasta;
1060 StringBuilder validSB = new StringBuilder();
1061 for (String f : validFormats)
1063 if (validSB.length() > 0)
1064 validSB.append(", ");
1066 FileFormatI tff = ffs.forName(f);
1067 validSB.append(" (");
1068 validSB.append(tff.getExtensions());
1069 validSB.append(")");
1072 addError("No valid format specified for "
1073 + Arg.OUTPUT.argString() + ". Valid formats are "
1074 + validSB.toString() + ".");
1079 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1080 fileName, ff.getName(), isError);
1086 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1087 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1088 !Platform.isHeadless());
1090 Console.info("Writing " + fileName);
1092 af.saveAlignment(fileName, ff, stdout, backups);
1093 if (af.isSaveAlignmentSuccessful())
1095 Console.debug("Written alignment '" + name + "' in "
1096 + ff.getName() + " format to '" + file + "'");
1100 addError("Error writing file '" + file + "' in " + ff.getName()
1111 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1114 SubVals subVals = av.getSubVals();
1115 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1116 SequenceI seq = null;
1117 if (subVals == null && idAv == null)
1119 if (af == null || af.getCurrentView() == null)
1123 AlignmentI al = af.getCurrentView().getAlignment();
1128 if (subVals != null)
1130 if (subVals.has(Arg.SEQID.getName()))
1132 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1134 else if (-1 < subVals.getIndex()
1135 && subVals.getIndex() < al.getSequences().size())
1137 seq = al.getSequenceAt(subVals.getIndex());
1140 if (seq == null && idAv != null)
1142 seq = al.findName(idAv.getValue());
1147 public AlignFrame[] getAlignFrames()
1149 AlignFrame[] afs = null;
1152 afs = (AlignFrame[]) afMap.values().toArray();
1158 public List<StructureViewer> getStructureViewers()
1160 List<StructureViewer> svs = null;
1163 for (List<StructureViewer> svList : svMap.values())
1167 svs = new ArrayList<>();
1175 private void colourAlignFrame(AlignFrame af, String colour)
1177 // use string "none" to remove colour scheme
1178 if (colour != null && "" != colour)
1180 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1181 af.getViewport(), af.getViewport().getAlignment(), colour);
1182 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1184 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1188 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1189 colourAlignFrame(af, cs);
1194 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1196 // Note that cs == null removes colour scheme from af
1197 af.changeColour(cs);
1200 private ColourSchemeI getColourScheme(AlignFrame af)
1202 return af.getViewport().getGlobalColourScheme();
1205 private void addInfo(String errorMessage)
1207 Console.info(errorMessage);
1208 errors.add(errorMessage);
1211 private void addWarn(String errorMessage)
1213 Console.warn(errorMessage);
1214 errors.add(errorMessage);
1217 private void addError(String errorMessage)
1219 addError(errorMessage, null);
1222 private void addError(String errorMessage, Exception e)
1224 Console.error(errorMessage, e);
1225 errors.add(errorMessage);
1228 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1229 SubVals subVal, boolean includeBackups, String filename,
1230 String adjective, Boolean isError)
1232 File file = new File(filename);
1234 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1235 null, "OVERWRITE_OUTPUT", false);
1236 boolean stdout = false;
1237 boolean backups = false;
1240 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1241 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1242 // otherwise if headless assume false, if not headless use the user
1243 // preference with default true.
1244 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1245 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1246 !Platform.isHeadless());
1249 if (file.exists() && !(overwrite || backups || stdout))
1251 addWarn("Won't overwrite file '" + filename + "' without "
1252 + Arg.OVERWRITE.argString()
1253 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1258 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1259 "MKDIRS_OUTPUT", false);
1261 if (!FileUtils.checkParentDir(file, mkdirs))
1263 addError("Directory '"
1264 + FileUtils.getParentDir(file).getAbsolutePath()
1265 + "' does not exist for " + adjective + " file '" + filename
1267 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1275 public List<String> getErrors()
1280 public String errorsToString()
1282 StringBuilder sb = new StringBuilder();
1283 for (String error : errors)
1285 if (sb.length() > 0)
1287 sb.append("- " + error);
1289 return sb.toString();