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);
154 "The following errors and warnings occurred whilst processing files:\n"
156 // gui errors reported in Jalview
158 if (argParser.getBoolean(Arg.QUIT))
160 Jalview.getInstance().exit(
161 "Exiting due to " + Arg.QUIT.argString() + " argument.",
165 // carry on with jalview.bin.Jalview
166 argsWereParsed = theseArgsWereParsed;
167 return argsWereParsed;
170 public boolean commandArgsProvided()
172 return commandArgsProvided;
175 public boolean argsWereParsed()
177 return argsWereParsed;
180 protected boolean processLinked(String id)
182 boolean theseArgsWereParsed = false;
183 ArgValuesMap avm = argParser.getLinkedArgs(id);
189 Boolean isError = Boolean.valueOf(false);
191 // set wrap scope here so it can be applied after structures are opened
192 boolean wrap = false;
194 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
196 commandArgsProvided = true;
199 boolean first = true;
200 boolean progressBarSet = false;
202 // Combine the APPEND and OPEN files into one list, along with whether it
203 // was APPEND or OPEN
204 List<ArgValue> openAvList = new ArrayList<>();
205 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
206 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
207 // sort avlist based on av.getArgIndex()
208 Collections.sort(openAvList);
209 for (ArgValue av : openAvList)
212 SubVals sv = av.getSubVals();
213 String openFile = av.getValue();
214 if (openFile == null)
217 theseArgsWereParsed = true;
221 if (!headless && desktop != null)
223 desktop.setProgressBar(
224 MessageManager.getString(
225 "status.processing_commandline_args"),
226 progress = System.currentTimeMillis());
227 progressBarSet = true;
231 if (!Platform.isJS())
233 * ignore in JavaScript -- can't just file existence - could load it?
238 if (!HttpUtils.startsWithHttpOrHttps(openFile))
240 if (!(new File(openFile)).exists())
242 addError("Can't find file '" + openFile + "'");
249 DataSourceType protocol = AppletFormatAdapter
250 .checkProtocol(openFile);
252 FileFormatI format = null;
255 format = new IdentifyFile().identify(openFile, protocol);
256 } catch (FileFormatException e1)
258 addError("Unknown file format for '" + openFile + "'");
264 // When to open a new AlignFrame
265 if (af == null || "true".equals(av.getSubVal("new"))
266 || a == Arg.OPEN || format == FileFormat.Jalview)
270 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
275 "Opening '" + openFile + "' in new alignment frame");
276 FileLoader fileLoader = new FileLoader(!headless);
277 boolean xception = false;
280 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
282 } catch (Throwable thr)
285 addError("Couldn't open '" + openFile + "' as " + format + " "
286 + thr.getLocalizedMessage()
287 + " (Enable debug for full stack trace)");
289 Console.debug("Exception when opening '" + openFile + "'", thr);
292 if (af == null && !xception)
294 addInfo("Ignoring '" + openFile
295 + "' - no alignment data found.");
301 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
302 null, "DEFAULT_COLOUR_PROT", "");
303 this.colourAlignFrame(af, colour);
305 // Change alignment frame title
306 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
311 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
315 String featuresfile = avm.getValueFromSubValOrArg(av,
317 if (featuresfile != null)
319 af.parseFeaturesFile(featuresfile,
320 AppletFormatAdapter.checkProtocol(featuresfile));
321 Jalview.testoutput(argParser, Arg.FEATURES,
322 "examples/testdata/plantfdx.features", featuresfile);
325 // Add annotations from file
326 String annotationsfile = avm.getValueFromSubValOrArg(av,
327 Arg.ANNOTATIONS, sv);
328 if (annotationsfile != null)
330 af.loadJalviewDataFile(annotationsfile, null, null, null);
331 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
332 "examples/testdata/plantfdx.annotations",
336 // Set or clear the sortbytree flag
337 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
341 af.getViewport().setSortByTree(true);
342 Jalview.testoutput(argParser, Arg.SORTBYTREE);
345 // Load tree from file
346 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
347 if (treefile != null)
351 NewickFile nf = new NewickFile(treefile,
352 AppletFormatAdapter.checkProtocol(treefile));
353 af.getViewport().setCurrentTree(
354 af.showNewickTree(nf, treefile).getTree());
355 Jalview.testoutput(argParser, Arg.TREE,
356 "examples/testdata/uniref50_test_tree", treefile);
357 } catch (IOException e)
359 addError("Couldn't add tree " + treefile, e);
364 // Show secondary structure annotations?
365 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
366 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
367 "STRUCT_FROM_PDB", true);
368 af.setAnnotationsVisibility(showSSAnnotations, true, false);
370 // Show sequence annotations?
371 boolean showAnnotations = avm.getFromSubValArgOrPref(
372 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
373 "SHOW_ANNOTATIONS", true);
374 af.setAnnotationsVisibility(showAnnotations, false, true);
376 // show temperature factor annotations?
377 if (avm.getBoolean(Arg.NOTEMPFAC))
379 // do this better (annotation types?)
380 List<String> hideThese = new ArrayList<>();
381 hideThese.add("Temperature Factor");
382 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
383 AlignmentUtils.showOrHideSequenceAnnotations(
384 af.getCurrentView().getAlignment(), hideThese, null,
388 // wrap alignment? do this last for formatting reasons
389 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
390 "WRAP_ALIGNMENT", false);
391 // af.setWrapFormat(wrap) is applied after structures are opened for
392 // annotation reasons
394 // store the AlignFrame for this id
397 // is it its own structure file?
398 if (format.isStructureFile())
400 StructureSelectionManager ssm = StructureSelectionManager
401 .getStructureSelectionManager(Desktop.instance);
402 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
403 ssm.computeMapping(false, new SequenceI[] { seq }, null,
404 openFile, DataSourceType.FILE, null, null, null, false);
410 "Opening '" + openFile + "' in existing alignment frame");
411 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
413 : DataSourceType.FILE;
414 FileLoader fileLoader = new FileLoader(!headless);
415 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
419 Console.debug("Command " + Arg.APPEND + " executed successfully!");
422 if (first) // first=true means nothing opened
426 Jalview.exit("Could not open any files in headless mode",
431 Console.info("No more files to open");
434 if (progressBarSet && desktop != null)
435 desktop.setProgressBar(null, progress);
439 // open the structure (from same PDB file or given PDBfile)
440 if (!avm.getBoolean(Arg.NOSTRUCTURE))
442 AlignFrame af = afMap.get(id);
443 if (avm.containsArg(Arg.STRUCTURE))
445 commandArgsProvided = true;
446 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
448 argParser.setStructureFilename(null);
449 String val = av.getValue();
450 SubVals subVals = av.getSubVals();
451 int argIndex = av.getArgIndex();
452 SequenceI seq = getSpecifiedSequence(af, avm, av);
455 // Could not find sequence from subId, let's assume the first
456 // sequence in the alignframe
457 AlignmentI al = af.getCurrentView().getAlignment();
458 seq = al.getSequenceAt(0);
463 addWarn("Could not find sequence for argument "
464 + Arg.STRUCTURE.argString() + "=" + val);
467 String structureFilename = null;
468 File structureFile = null;
469 if (subVals.getContent() != null
470 && subVals.getContent().length() != 0)
472 structureFilename = subVals.getContent();
473 Console.debug("Using structure file (from argument) '"
474 + structureFilename + "'");
475 structureFile = new File(structureFilename);
477 /* THIS DOESN'T WORK */
478 else if (seq.getAllPDBEntries() != null
479 && seq.getAllPDBEntries().size() > 0)
481 structureFile = new File(
482 seq.getAllPDBEntries().elementAt(0).getFile());
483 if (structureFile != null)
485 Console.debug("Using structure file (from sequence) '"
486 + structureFile.getAbsolutePath() + "'");
488 structureFilename = structureFile.getAbsolutePath();
491 if (structureFilename == null || structureFile == null)
493 addWarn("Not provided structure file with '" + val + "'");
497 if (!structureFile.exists())
499 addWarn("Structure file '" + structureFile.getAbsoluteFile()
504 Console.debug("Using structure file "
505 + structureFile.getAbsolutePath());
507 argParser.setStructureFilename(structureFilename);
509 // open structure view
510 AlignmentPanel ap = af.alignPanel;
513 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
514 StructureViewer.ViewerType.JMOL.toString());
517 String structureFilepath = structureFile.getAbsolutePath();
519 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
520 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
521 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
522 subVals, null, null, null);
523 if (paeFilepath != null)
525 File paeFile = new File(paeFilepath);
529 paeFilepath = paeFile.getCanonicalPath();
530 } catch (IOException e)
532 paeFilepath = paeFile.getAbsolutePath();
533 addWarn("Problem with the PAE file path: '"
534 + paeFile.getPath() + "'");
538 // showing annotations from structure file or not
539 boolean ssFromStructure = avm.getFromSubValArgOrPref(
540 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
543 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
544 // reference annotations
545 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
546 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
547 subVals, null, null, null);
548 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
549 subVals, null, "ADD_TEMPFACT_ANN", false, true);
550 TFType tft = notempfac ? null : TFType.DEFAULT;
551 if (tftString != null && !notempfac)
553 // get kind of temperature factor annotation
556 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
557 Console.debug("Obtained Temperature Factor type of '" + tft
558 + "' for structure '" + structureFilepath + "'");
559 } catch (IllegalArgumentException e)
561 // Just an error message!
562 StringBuilder sb = new StringBuilder().append("Cannot set ")
563 .append(Arg.TEMPFAC.argString()).append(" to '")
565 .append("', ignoring. Valid values are: ");
566 Iterator<TFType> it = Arrays.stream(TFType.values())
570 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
574 addWarn(sb.toString());
578 String sViewerName = avm.getFromSubValArgOrPref(
579 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
580 subVals, null, null, "jmol");
581 ViewerType viewerType = ViewerType.getFromString(sViewerName);
583 // TODO use ssFromStructure
584 StructureViewer structureViewer = StructureChooser
585 .openStructureFileForSequence(null, null, ap, seq, false,
586 structureFilepath, tft, paeFilepath, false,
587 ssFromStructure, false, viewerType);
589 if (structureViewer == null)
591 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
593 addError("Failed to import and open structure view for file '"
594 + structureFile + "'.");
601 while (structureViewer.isBusy() && tries > 0)
604 if (structureViewer.isBusy())
608 "Waiting for viewer for " + structureFilepath);
611 if (tries == 0 && structureViewer.isBusy())
613 addWarn("Gave up waiting for structure viewer to load file '"
615 + "'. Something may have gone wrong.");
617 } catch (Exception x)
619 addError("Exception whilst waiting for structure viewer "
620 + structureFilepath, x);
624 // add StructureViewer to svMap list
627 svMap = new HashMap<>();
629 if (svMap.get(id) == null)
631 svMap.put(id, new ArrayList<>());
633 svMap.get(id).add(structureViewer);
636 "Successfully opened viewer for " + structureFilepath);
638 if (avm.containsArg(Arg.STRUCTUREIMAGE))
640 for (ArgValue structureImageArgValue : avm
641 .getArgValueList(Arg.STRUCTUREIMAGE))
643 String structureImageFilename = argParser.makeSubstitutions(
644 structureImageArgValue.getValue(), id, true);
645 if (structureViewer != null && structureImageFilename != null)
647 SubVals structureImageSubVals = null;
648 structureImageSubVals = structureImageArgValue.getSubVals();
649 File structureImageFile = new File(structureImageFilename);
650 String width = avm.getValueFromSubValOrArg(
651 structureImageArgValue, Arg.WIDTH,
652 structureImageSubVals);
653 String height = avm.getValueFromSubValOrArg(
654 structureImageArgValue, Arg.HEIGHT,
655 structureImageSubVals);
656 String scale = avm.getValueFromSubValOrArg(
657 structureImageArgValue, Arg.SCALE,
658 structureImageSubVals);
659 String renderer = avm.getValueFromSubValOrArg(
660 structureImageArgValue, Arg.TEXTRENDERER,
661 structureImageSubVals);
662 String typeS = avm.getValueFromSubValOrArg(
663 structureImageArgValue, Arg.TYPE,
664 structureImageSubVals);
665 if (typeS == null || typeS.length() == 0)
667 typeS = FileUtils.getExtension(structureImageFile);
672 imageType = Enum.valueOf(TYPE.class,
673 typeS.toUpperCase(Locale.ROOT));
674 } catch (IllegalArgumentException e)
676 addWarn("Do not know image format '" + typeS
678 imageType = TYPE.PNG;
680 BitmapImageSizing userBis = ImageMaker
681 .parseScaleWidthHeightStrings(scale, width, height);
684 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
685 if (viewerType!=ViewerType.JMOL) {
686 addWarn("Cannot export image for structure viewer "
687 + viewerType.name() + " yet");
692 // Apply the temporary colourscheme to the linked alignment
693 // TODO: enhance for multiple linked alignments.
695 String imageColour = avm.getValueFromSubValOrArg(
696 structureImageArgValue, Arg.IMAGECOLOUR,
697 structureImageSubVals);
698 ColourSchemeI originalColourScheme = this
699 .getColourScheme(af);
700 this.colourAlignFrame(af, imageColour);
703 // custom image background colour
705 String bgcolourstring = avm.getValueFromSubValOrArg(
706 structureImageArgValue, Arg.BGCOLOUR,
707 structureImageSubVals);
708 Color bgcolour = null;
709 if (bgcolourstring != null && bgcolourstring.length() > 0)
714 // FIXME: Why not use ColorUtils.parseColourString(bgcolourstring) - this is consistent and backwards compatible
716 if (bgcolourstring.charAt(0) == '#')
718 bgcolour = Color.decode(bgcolourstring);
722 Field field = Color.class.getField(bgcolourstring);
723 bgcolour = (Color) field.get(null);
725 } catch (IllegalArgumentException | NoSuchFieldException
726 | SecurityException | IllegalAccessException nfe)
729 "Background colour string '" + bgcolourstring
730 + "' not recognised -- using default");
731 //bgcolour = Color.black;
735 JalviewStructureDisplayI sview = structureViewer
736 .getJalviewStructureDisplay();
738 File sessionToRestore = null;
740 List<StructureCommandI> extraCommands=new ArrayList<>();
742 if (extraCommands.size() > 0 || bgcolour!=null)
745 sessionToRestore = sview.saveSession();
746 } catch (Throwable t)
748 Console.warn("Unable to save temporary session file before custom structure view export operation.");
755 sview.getBinding().setBackgroundColour(bgcolour);
757 sview.getBinding().executeCommands(extraCommands, false, "Executing Custom Commands");
759 // and export the view as an image
760 boolean success = this.checksBeforeWritingToFile(avm,
761 subVals, false, structureImageFilename,
762 "structure image", isError);
769 "Rendering image to " + structureImageFile);
771 // TODO - extend StructureViewer / Binding with makePDBImage so we can do this with every viewer
775 // We don't expect class cast exception
776 AppJmol jmol = (AppJmol) sview;
777 jmol.makePDBImage(structureImageFile, imageType,
779 Console.debug("Finished Rendering image to "
780 + structureImageFile);
782 // RESTORE SESSION AFTER EXPORT IF NEED BE
783 if (sessionToRestore != null)
785 Console.debug("Restoring session from "
788 sview.getBinding().restoreSession(sessionToRestore.getAbsolutePath());
791 } catch (ImageOutputException ioexc)
793 addError("Unexpected error whilst exporting image to "
794 + structureImageFile, ioexc);
801 this.colourAlignFrame(af, originalColourScheme);
802 } catch (Exception t)
804 addError("Unexpected error when restoring colourscheme to alignment after temporary change for export.",t);
810 argParser.setStructureFilename(null);
817 AlignFrame af = afMap.get(id);
820 af.setWrapFormat(wrap, true);
825 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
828 AlignFrame af = afMap.get(id);
829 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
830 .findAnnotation(PDBChain.class.getName().toString()))
832 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
833 af.alignPanel.av.getGlobalColourScheme(), 0);
834 acg.setSeqAssociated(true);
835 af.changeColour(acg);
836 Console.info("Changed colour " + acg.toString());
841 return theseArgsWereParsed && !isError;
844 protected void processGroovyScript(String id)
846 ArgValuesMap avm = argParser.getLinkedArgs(id);
847 AlignFrame af = afMap.get(id);
851 addWarn("Did not have an alignment window for id=" + id);
855 if (avm.containsArg(Arg.GROOVY))
857 String groovyscript = avm.getValue(Arg.GROOVY);
858 if (groovyscript != null)
860 // Execute the groovy script after we've done all the rendering stuff
861 // and before any images or figures are generated.
862 Console.info("Executing script " + groovyscript);
863 Jalview.getInstance().executeGroovyScript(groovyscript, af);
868 protected boolean processImages(String id)
870 ArgValuesMap avm = argParser.getLinkedArgs(id);
871 AlignFrame af = afMap.get(id);
875 addWarn("Did not have an alignment window for id=" + id);
879 Boolean isError = Boolean.valueOf(false);
880 if (avm.containsArg(Arg.IMAGE))
882 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
884 String val = imageAv.getValue();
885 SubVals imageSubVals = imageAv.getSubVals();
886 String fileName = imageSubVals.getContent();
887 File file = new File(fileName);
888 String name = af.getName();
889 String renderer = avm.getValueFromSubValOrArg(imageAv,
890 Arg.TEXTRENDERER, imageSubVals);
891 if (renderer == null)
893 String type = "png"; // default
895 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
897 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
899 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
901 BitmapImageSizing userBis = ImageMaker
902 .parseScaleWidthHeightStrings(scale, width, height);
904 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
905 if (type == null && fileName != null)
907 for (String ext : new String[] { "svg", "png", "html", "eps" })
909 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
915 // for moment we disable JSON export
916 Cache.setPropsAreReadOnly(true);
917 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
919 String imageColour = avm.getValueFromSubValOrArg(imageAv,
920 Arg.IMAGECOLOUR, imageSubVals);
921 ColourSchemeI originalColourScheme = this.getColourScheme(af);
922 this.colourAlignFrame(af, imageColour);
924 Console.info("Writing " + file);
926 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
927 false, fileName, "image", isError);
939 Console.debug("Outputting type '" + type + "' to " + fileName);
940 af.createSVG(file, renderer);
944 Console.debug("Outputting type '" + type + "' to " + fileName);
945 af.createPNG(file, null, userBis);
949 Console.debug("Outputting type '" + type + "' to " + fileName);
950 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
951 htmlSVG.exportHTML(fileName, renderer);
956 "Outputting BioJS MSA Viwer HTML file: " + fileName);
959 BioJsHTMLOutput.refreshVersionInfo(
960 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
961 } catch (URISyntaxException e)
965 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
966 bjs.exportHTML(fileName);
970 Console.debug("Outputting EPS file: " + fileName);
971 af.createEPS(file, renderer);
975 Console.debug("Outputting ImageMap file: " + fileName);
976 af.createImageMap(file, name);
980 addWarn(Arg.IMAGE.argString() + " type '" + type
981 + "' not known. Ignoring");
984 } catch (Exception ioex)
986 addError("Unexpected error during export to '" + fileName + "'",
991 this.colourAlignFrame(af, originalColourScheme);
997 protected boolean processOutput(String id)
999 ArgValuesMap avm = argParser.getLinkedArgs(id);
1000 AlignFrame af = afMap.get(id);
1004 addWarn("Did not have an alignment window for id=" + id);
1008 Boolean isError = Boolean.valueOf(false);
1010 if (avm.containsArg(Arg.OUTPUT))
1012 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1014 String val = av.getValue();
1015 SubVals subVals = av.getSubVals();
1016 String fileName = subVals.getContent();
1017 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1018 File file = new File(fileName);
1020 String name = af.getName();
1021 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1023 FileFormats ffs = FileFormats.getInstance();
1024 List<String> validFormats = ffs.getWritableFormats(false);
1026 FileFormatI ff = null;
1027 if (format == null && fileName != null)
1029 FORMAT: for (String fname : validFormats)
1031 FileFormatI tff = ffs.forName(fname);
1032 String[] extensions = tff.getExtensions().split(",");
1033 for (String ext : extensions)
1035 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1038 format = ff.getName();
1044 if (ff == null && format != null)
1046 ff = ffs.forName(format);
1052 ff = FileFormat.Fasta;
1056 StringBuilder validSB = new StringBuilder();
1057 for (String f : validFormats)
1059 if (validSB.length() > 0)
1060 validSB.append(", ");
1062 FileFormatI tff = ffs.forName(f);
1063 validSB.append(" (");
1064 validSB.append(tff.getExtensions());
1065 validSB.append(")");
1068 addError("No valid format specified for "
1069 + Arg.OUTPUT.argString() + ". Valid formats are "
1070 + validSB.toString() + ".");
1075 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1076 fileName, ff.getName(), isError);
1082 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1083 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1084 !Platform.isHeadless());
1086 Console.info("Writing " + fileName);
1088 af.saveAlignment(fileName, ff, stdout, backups);
1089 if (af.isSaveAlignmentSuccessful())
1091 Console.debug("Written alignment '" + name + "' in "
1092 + ff.getName() + " format to '" + file + "'");
1096 addError("Error writing file '" + file + "' in " + ff.getName()
1107 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1110 SubVals subVals = av.getSubVals();
1111 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1112 SequenceI seq = null;
1113 if (subVals == null && idAv == null)
1115 if (af == null || af.getCurrentView() == null)
1119 AlignmentI al = af.getCurrentView().getAlignment();
1124 if (subVals != null)
1126 if (subVals.has(Arg.SEQID.getName()))
1128 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1130 else if (-1 < subVals.getIndex()
1131 && subVals.getIndex() < al.getSequences().size())
1133 seq = al.getSequenceAt(subVals.getIndex());
1136 if (seq == null && idAv != null)
1138 seq = al.findName(idAv.getValue());
1143 public AlignFrame[] getAlignFrames()
1145 AlignFrame[] afs = null;
1148 afs = (AlignFrame[]) afMap.values().toArray();
1154 public List<StructureViewer> getStructureViewers()
1156 List<StructureViewer> svs = null;
1159 for (List<StructureViewer> svList : svMap.values())
1163 svs = new ArrayList<>();
1171 private void colourAlignFrame(AlignFrame af, String colour)
1173 // use string "none" to remove colour scheme
1174 if (colour != null && "" != colour)
1176 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1177 af.getViewport(), af.getViewport().getAlignment(), colour);
1178 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1180 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1184 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1185 colourAlignFrame(af, cs);
1190 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1192 // Note that cs == null removes colour scheme from af
1193 af.changeColour(cs);
1196 private ColourSchemeI getColourScheme(AlignFrame af)
1198 return af.getViewport().getGlobalColourScheme();
1201 private void addInfo(String errorMessage)
1203 Console.info(errorMessage);
1204 errors.add(errorMessage);
1207 private void addWarn(String errorMessage)
1209 Console.warn(errorMessage);
1210 errors.add(errorMessage);
1213 private void addError(String errorMessage)
1215 addError(errorMessage, null);
1218 private void addError(String errorMessage, Exception e)
1220 Console.error(errorMessage, e);
1221 errors.add(errorMessage);
1224 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1225 SubVals subVal, boolean includeBackups, String filename,
1226 String adjective, Boolean isError)
1228 File file = new File(filename);
1230 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1231 null, "OVERWRITE_OUTPUT", false);
1232 boolean stdout = false;
1233 boolean backups = false;
1236 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1237 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1238 // otherwise if headless assume false, if not headless use the user
1239 // preference with default true.
1240 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1241 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1242 !Platform.isHeadless());
1245 if (file.exists() && !(overwrite || backups || stdout))
1247 addWarn("Won't overwrite file '" + filename + "' without "
1248 + Arg.OVERWRITE.argString()
1249 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1254 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1255 "MKDIRS_OUTPUT", false);
1257 if (!FileUtils.checkParentDir(file, mkdirs))
1259 addError("Directory '"
1260 + FileUtils.getParentDir(file).getAbsolutePath()
1261 + "' does not exist for " + adjective + " file '" + filename
1263 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1271 public List<String> getErrors()
1276 public String errorsToString()
1278 StringBuilder sb = new StringBuilder();
1279 for (String error : errors)
1281 if (sb.length() > 0)
1283 sb.append("- " + error);
1285 return sb.toString();