4 import java.io.IOException;
5 import java.net.URISyntaxException;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Locale;
15 import jalview.analysis.AlignmentUtils;
16 import jalview.api.structures.JalviewStructureDisplayI;
17 import jalview.bin.Jalview.ExitCode;
18 import jalview.bin.argparser.Arg;
19 import jalview.bin.argparser.ArgParser;
20 import jalview.bin.argparser.ArgValue;
21 import jalview.bin.argparser.ArgValuesMap;
22 import jalview.bin.argparser.SubVals;
23 import jalview.datamodel.AlignmentI;
24 import jalview.datamodel.SequenceI;
25 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
26 import jalview.gui.AlignFrame;
27 import jalview.gui.AlignmentPanel;
28 import jalview.gui.AppJmol;
29 import jalview.gui.Desktop;
30 import jalview.gui.Preferences;
31 import jalview.gui.StructureChooser;
32 import jalview.gui.StructureViewer;
33 import jalview.gui.StructureViewer.ViewerType;
34 import jalview.io.AppletFormatAdapter;
35 import jalview.io.BackupFiles;
36 import jalview.io.BioJsHTMLOutput;
37 import jalview.io.DataSourceType;
38 import jalview.io.FileFormat;
39 import jalview.io.FileFormatException;
40 import jalview.io.FileFormatI;
41 import jalview.io.FileFormats;
42 import jalview.io.FileLoader;
43 import jalview.io.HtmlSvgOutput;
44 import jalview.io.IdentifyFile;
45 import jalview.io.NewickFile;
46 import jalview.io.exceptions.ImageOutputException;
47 import jalview.schemes.ColourSchemeI;
48 import jalview.schemes.ColourSchemeProperty;
49 import jalview.structure.StructureImportSettings.TFType;
50 import jalview.structure.StructureSelectionManager;
51 import jalview.util.FileUtils;
52 import jalview.util.HttpUtils;
53 import jalview.util.ImageMaker;
54 import jalview.util.ImageMaker.TYPE;
55 import jalview.util.MessageManager;
56 import jalview.util.Platform;
57 import jalview.util.StringUtils;
58 import jalview.util.imagemaker.BitmapImageSizing;
64 private boolean headless;
66 private ArgParser argParser;
68 private Map<String, AlignFrame> afMap;
70 private Map<String, List<StructureViewer>> svMap;
72 private boolean commandArgsProvided = false;
74 private boolean argsWereParsed = false;
76 private List<String> errors = new ArrayList<>();
78 public Commands(ArgParser argparser, boolean headless)
80 this(Desktop.instance, argparser, headless);
83 public Commands(Desktop d, ArgParser argparser, boolean h)
85 argParser = argparser;
88 afMap = new HashMap<>();
91 protected boolean processArgs()
93 if (argParser == null)
98 boolean theseArgsWereParsed = false;
100 if (argParser != null && argParser.getLinkedIds() != null)
102 for (String id : argParser.getLinkedIds())
104 ArgValuesMap avm = argParser.getLinkedArgs(id);
105 theseArgsWereParsed = true;
106 boolean processLinkedOkay = processLinked(id);
107 theseArgsWereParsed &= processLinkedOkay;
109 processGroovyScript(id);
111 // wait around until alignFrame isn't busy
112 AlignFrame af = afMap.get(id);
113 while (af != null && af.getViewport().isCalcInProgress())
118 } catch (Exception q)
124 theseArgsWereParsed &= processImages(id);
126 if (processLinkedOkay)
128 theseArgsWereParsed &= processOutput(id);
132 if (avm.getBoolean(Arg.CLOSE))
137 af.closeMenuItem_actionPerformed(true);
147 "The following errors and warnings occurred whilst processing files:\n"
149 // gui errors reported in Jalview
151 if (argParser.getBoolean(Arg.QUIT))
153 Jalview.getInstance().exit(
154 "Exiting due to " + Arg.QUIT.argString() + " argument.",
158 // carry on with jalview.bin.Jalview
159 argsWereParsed = theseArgsWereParsed;
160 return argsWereParsed;
163 public boolean commandArgsProvided()
165 return commandArgsProvided;
168 public boolean argsWereParsed()
170 return argsWereParsed;
173 protected boolean processLinked(String id)
175 boolean theseArgsWereParsed = false;
176 ArgValuesMap avm = argParser.getLinkedArgs(id);
182 Boolean isError = Boolean.valueOf(false);
184 // set wrap scope here so it can be applied after structures are opened
185 boolean wrap = false;
187 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
189 commandArgsProvided = true;
192 boolean first = true;
193 boolean progressBarSet = false;
195 // Combine the APPEND and OPEN files into one list, along with whether it
196 // was APPEND or OPEN
197 List<ArgValue> openAvList = new ArrayList<>();
198 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
199 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
200 // sort avlist based on av.getArgIndex()
201 Collections.sort(openAvList);
202 for (ArgValue av : openAvList)
205 SubVals sv = av.getSubVals();
206 String openFile = av.getValue();
207 if (openFile == null)
210 theseArgsWereParsed = true;
214 if (!headless && desktop != null)
216 desktop.setProgressBar(
217 MessageManager.getString(
218 "status.processing_commandline_args"),
219 progress = System.currentTimeMillis());
220 progressBarSet = true;
224 if (!Platform.isJS())
226 * ignore in JavaScript -- can't just file existence - could load it?
231 if (!HttpUtils.startsWithHttpOrHttps(openFile))
233 if (!(new File(openFile)).exists())
235 addError("Can't find file '" + openFile + "'");
242 DataSourceType protocol = AppletFormatAdapter
243 .checkProtocol(openFile);
245 FileFormatI format = null;
248 format = new IdentifyFile().identify(openFile, protocol);
249 } catch (FileFormatException e1)
251 addError("Unknown file format for '" + openFile + "'");
257 // When to open a new AlignFrame
258 if (af == null || "true".equals(av.getSubVal("new"))
259 || a == Arg.OPEN || format == FileFormat.Jalview)
263 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
268 "Opening '" + openFile + "' in new alignment frame");
269 FileLoader fileLoader = new FileLoader(!headless);
270 boolean xception = false;
273 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
275 } catch (Throwable thr)
278 addError("Couldn't open '" + openFile + "' as " + format + " "
279 + thr.getLocalizedMessage()
280 + " (Enable debug for full stack trace)");
282 Console.debug("Exception when opening '" + openFile + "'", thr);
285 if (af == null && !xception)
287 addInfo("Ignoring '" + openFile
288 + "' - no alignment data found.");
294 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
295 null, "DEFAULT_COLOUR_PROT", "");
296 this.colourAlignFrame(af, colour);
298 // Change alignment frame title
299 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
304 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
308 String featuresfile = avm.getValueFromSubValOrArg(av,
310 if (featuresfile != null)
312 af.parseFeaturesFile(featuresfile,
313 AppletFormatAdapter.checkProtocol(featuresfile));
314 Jalview.testoutput(argParser, Arg.FEATURES,
315 "examples/testdata/plantfdx.features", featuresfile);
318 // Add annotations from file
319 String annotationsfile = avm.getValueFromSubValOrArg(av,
320 Arg.ANNOTATIONS, sv);
321 if (annotationsfile != null)
323 af.loadJalviewDataFile(annotationsfile, null, null, null);
324 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
325 "examples/testdata/plantfdx.annotations",
329 // Set or clear the sortbytree flag
330 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
334 af.getViewport().setSortByTree(true);
335 Jalview.testoutput(argParser, Arg.SORTBYTREE);
338 // Load tree from file
339 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
340 if (treefile != null)
344 NewickFile nf = new NewickFile(treefile,
345 AppletFormatAdapter.checkProtocol(treefile));
346 af.getViewport().setCurrentTree(
347 af.showNewickTree(nf, treefile).getTree());
348 Jalview.testoutput(argParser, Arg.TREE,
349 "examples/testdata/uniref50_test_tree", treefile);
350 } catch (IOException e)
352 addError("Couldn't add tree " + treefile, e);
357 // Show secondary structure annotations?
358 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
359 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
360 "STRUCT_FROM_PDB", true);
361 af.setAnnotationsVisibility(showSSAnnotations, true, false);
363 // Show sequence annotations?
364 boolean showAnnotations = avm.getFromSubValArgOrPref(
365 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
366 "SHOW_ANNOTATIONS", true);
367 af.setAnnotationsVisibility(showAnnotations, false, true);
369 // show temperature factor annotations?
370 if (avm.getBoolean(Arg.NOTEMPFAC))
372 // do this better (annotation types?)
373 List<String> hideThese = new ArrayList<>();
374 hideThese.add("Temperature Factor");
375 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
376 AlignmentUtils.showOrHideSequenceAnnotations(
377 af.getCurrentView().getAlignment(), hideThese, null,
381 // wrap alignment? do this last for formatting reasons
382 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
383 "WRAP_ALIGNMENT", false);
384 // af.setWrapFormat(wrap) is applied after structures are opened for
385 // annotation reasons
387 // store the AlignFrame for this id
390 // is it its own structure file?
391 if (format.isStructureFile())
393 StructureSelectionManager ssm = StructureSelectionManager
394 .getStructureSelectionManager(Desktop.instance);
395 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
396 ssm.computeMapping(false, new SequenceI[] { seq }, null,
397 openFile, DataSourceType.FILE, null, null, null, false);
403 "Opening '" + openFile + "' in existing alignment frame");
404 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
406 : DataSourceType.FILE;
407 FileLoader fileLoader = new FileLoader(!headless);
408 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
412 Console.debug("Command " + Arg.APPEND + " executed successfully!");
415 if (first) // first=true means nothing opened
419 Jalview.exit("Could not open any files in headless mode",
424 Console.info("No more files to open");
427 if (progressBarSet && desktop != null)
428 desktop.setProgressBar(null, progress);
432 // open the structure (from same PDB file or given PDBfile)
433 if (!avm.getBoolean(Arg.NOSTRUCTURE))
435 AlignFrame af = afMap.get(id);
436 if (avm.containsArg(Arg.STRUCTURE))
438 commandArgsProvided = true;
439 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
441 String val = av.getValue();
442 SubVals subVals = av.getSubVals();
443 int argIndex = av.getArgIndex();
444 SequenceI seq = getSpecifiedSequence(af, avm, av);
447 // Could not find sequence from subId, let's assume the first
448 // sequence in the alignframe
449 AlignmentI al = af.getCurrentView().getAlignment();
450 seq = al.getSequenceAt(0);
455 addWarn("Could not find sequence for argument "
456 + Arg.STRUCTURE.argString() + "=" + val);
459 String structureFilename = null;
460 File structureFile = null;
461 if (subVals.getContent() != null
462 && subVals.getContent().length() != 0)
464 structureFilename = subVals.getContent();
465 Console.debug("Using structure file (from argument) '"
466 + structureFilename + "'");
467 structureFile = new File(structureFilename);
469 /* THIS DOESN'T WORK */
470 else if (seq.getAllPDBEntries() != null
471 && seq.getAllPDBEntries().size() > 0)
473 structureFile = new File(
474 seq.getAllPDBEntries().elementAt(0).getFile());
475 if (structureFile != null)
477 Console.debug("Using structure file (from sequence) '"
478 + structureFile.getAbsolutePath() + "'");
480 structureFilename = structureFile.getAbsolutePath();
483 if (structureFilename == null || structureFile == null)
485 addWarn("Not provided structure file with '" + val + "'");
489 if (!structureFile.exists())
491 addWarn("Structure file '" + structureFile.getAbsoluteFile()
496 Console.debug("Using structure file "
497 + structureFile.getAbsolutePath());
499 argParser.setStructureFilename(structureFilename);
501 // open structure view
502 AlignmentPanel ap = af.alignPanel;
505 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
506 StructureViewer.ViewerType.JMOL.toString());
509 String structureFilepath = structureFile.getAbsolutePath();
511 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
512 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
513 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
514 subVals, null, null, null);
515 if (paeFilepath != null)
517 File paeFile = new File(paeFilepath);
521 paeFilepath = paeFile.getCanonicalPath();
522 } catch (IOException e)
524 paeFilepath = paeFile.getAbsolutePath();
525 addWarn("Problem with the PAE file path: '"
526 + paeFile.getPath() + "'");
530 // showing annotations from structure file or not
531 boolean ssFromStructure = avm.getFromSubValArgOrPref(
532 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
535 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
536 // reference annotations
537 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
538 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
539 subVals, null, null, null);
540 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
541 subVals, null, "ADD_TEMPFACT_ANN", false, true);
542 TFType tft = notempfac ? null : TFType.DEFAULT;
543 if (tftString != null && !notempfac)
545 // get kind of temperature factor annotation
548 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
549 Console.debug("Obtained Temperature Factor type of '" + tft
550 + "' for structure '" + structureFilepath + "'");
551 } catch (IllegalArgumentException e)
553 // Just an error message!
554 StringBuilder sb = new StringBuilder().append("Cannot set ")
555 .append(Arg.TEMPFAC.argString()).append(" to '")
557 .append("', ignoring. Valid values are: ");
558 Iterator<TFType> it = Arrays.stream(TFType.values())
562 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
566 addWarn(sb.toString());
570 String sViewerName = avm.getFromSubValArgOrPref(
571 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
572 subVals, null, null, "jmol");
573 ViewerType viewerType = ViewerType.getFromString(sViewerName);
575 // TODO use ssFromStructure
576 StructureViewer structureViewer = StructureChooser
577 .openStructureFileForSequence(null, null, ap, seq, false,
578 structureFilepath, tft, paeFilepath, false,
579 ssFromStructure, false, viewerType);
581 if (structureViewer == null)
583 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
585 addError("Failed to import and open structure view for file '"
586 + structureFile + "'.");
593 while (structureViewer.isBusy() && tries > 0)
596 if (structureViewer.isBusy())
600 "Waiting for viewer for " + structureFilepath);
603 if (tries == 0 && structureViewer.isBusy())
605 addWarn("Gave up waiting for structure viewer to load file '"
607 + "'. Something may have gone wrong.");
609 } catch (Exception x)
611 addError("Exception whilst waiting for structure viewer "
612 + structureFilepath, x);
616 // add StructureViewer to svMap list
619 svMap = new HashMap<>();
621 if (svMap.get(id) == null)
623 svMap.put(id, new ArrayList<>());
625 svMap.get(id).add(structureViewer);
628 "Successfully opened viewer for " + structureFilepath);
630 if (avm.containsArg(Arg.STRUCTUREIMAGE))
632 for (ArgValue structureImageArgValue : avm
633 .getArgValueList(Arg.STRUCTUREIMAGE))
635 String structureImageFilename = argParser.makeSubstitutions(
636 structureImageArgValue.getValue(), id, true);
637 if (structureViewer != null && structureImageFilename != null)
639 SubVals structureImageSubVals = null;
640 structureImageSubVals = structureImageArgValue.getSubVals();
641 File structureImageFile = new File(structureImageFilename);
642 String width = avm.getValueFromSubValOrArg(
643 structureImageArgValue, Arg.WIDTH,
644 structureImageSubVals);
645 String height = avm.getValueFromSubValOrArg(
646 structureImageArgValue, Arg.HEIGHT,
647 structureImageSubVals);
648 String scale = avm.getValueFromSubValOrArg(
649 structureImageArgValue, Arg.SCALE,
650 structureImageSubVals);
651 String renderer = avm.getValueFromSubValOrArg(
652 structureImageArgValue, Arg.TEXTRENDERER,
653 structureImageSubVals);
654 String typeS = avm.getValueFromSubValOrArg(
655 structureImageArgValue, Arg.TYPE,
656 structureImageSubVals);
657 if (typeS == null || typeS.length() == 0)
659 typeS = FileUtils.getExtension(structureImageFile);
664 imageType = Enum.valueOf(TYPE.class,
665 typeS.toUpperCase(Locale.ROOT));
666 } catch (IllegalArgumentException e)
668 addWarn("Do not know image format '" + typeS
670 imageType = TYPE.PNG;
672 BitmapImageSizing userBis = ImageMaker
673 .parseScaleWidthHeightStrings(scale, width, height);
675 String imageColour = avm.getValueFromSubValOrArg(
676 structureImageArgValue, Arg.IMAGECOLOUR,
677 structureImageSubVals);
678 ColourSchemeI originalColourScheme = this
679 .getColourScheme(af);
680 this.colourAlignFrame(af, imageColour);
682 List<String> extraCommands = new ArrayList<>();
683 // these don't actually do anything to the output image since we
685 // extraCommands.add("set antialiasImages on");
686 // extraCommands.add("set antialiasTranslucent on");
688 String bgcolour = avm.getValueFromSubValOrArg(
689 structureImageArgValue, Arg.BGCOLOUR,
690 structureImageSubVals);
691 if (bgcolour != null && bgcolour.length() > 0)
693 if (bgcolour.charAt(0) == '#')
695 bgcolour = "[x" + bgcolour.substring(1) + "]";
697 extraCommands.add("background " + bgcolour);
700 // TODO MAKE THIS VIEWER INDEPENDENT!!
701 switch (StructureViewer.getViewerType())
704 JalviewStructureDisplayI sview = structureViewer
705 .getJalviewStructureDisplay();
706 if (sview instanceof AppJmol)
708 AppJmol jmol = (AppJmol) sview;
711 boolean success = this.checksBeforeWritingToFile(avm,
712 subVals, false, structureImageFilename,
713 "structure image", isError);
720 "Rendering image to " + structureImageFile);
721 jmol.makePDBImage(structureImageFile, imageType,
722 renderer, userBis, extraCommands);
723 Console.debug("Finished Rendering image to "
724 + structureImageFile);
726 } catch (ImageOutputException ioexc)
728 addError("Unexpected error whilst exporting image to "
729 + structureImageFile, ioexc);
737 addWarn("Cannot export image for structure viewer "
738 + structureViewer.getViewerType() + " yet");
741 this.colourAlignFrame(af, originalColourScheme);
751 AlignFrame af = afMap.get(id);
754 af.setWrapFormat(wrap, true);
759 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
762 AlignFrame af = afMap.get(id);
763 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
764 .findAnnotation(PDBChain.class.getName().toString()))
766 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
767 af.alignPanel.av.getGlobalColourScheme(), 0);
768 acg.setSeqAssociated(true);
769 af.changeColour(acg);
770 Console.info("Changed colour " + acg.toString());
775 return theseArgsWereParsed && !isError;
778 protected void processGroovyScript(String id)
780 ArgValuesMap avm = argParser.getLinkedArgs(id);
781 AlignFrame af = afMap.get(id);
785 addWarn("Did not have an alignment window for id=" + id);
789 if (avm.containsArg(Arg.GROOVY))
791 String groovyscript = avm.getValue(Arg.GROOVY);
792 if (groovyscript != null)
794 // Execute the groovy script after we've done all the rendering stuff
795 // and before any images or figures are generated.
796 Console.info("Executing script " + groovyscript);
797 Jalview.getInstance().executeGroovyScript(groovyscript, af);
802 protected boolean processImages(String id)
804 ArgValuesMap avm = argParser.getLinkedArgs(id);
805 AlignFrame af = afMap.get(id);
809 addWarn("Did not have an alignment window for id=" + id);
813 Boolean isError = Boolean.valueOf(false);
814 if (avm.containsArg(Arg.IMAGE))
816 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
818 String val = imageAv.getValue();
819 SubVals imageSubVals = imageAv.getSubVals();
820 String fileName = imageSubVals.getContent();
821 File file = new File(fileName);
822 String name = af.getName();
823 String renderer = avm.getValueFromSubValOrArg(imageAv,
824 Arg.TEXTRENDERER, imageSubVals);
825 if (renderer == null)
827 String type = "png"; // default
829 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
831 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
833 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
835 BitmapImageSizing userBis = ImageMaker
836 .parseScaleWidthHeightStrings(scale, width, height);
838 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
839 if (type == null && fileName != null)
841 for (String ext : new String[] { "svg", "png", "html", "eps" })
843 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
849 // for moment we disable JSON export
850 Cache.setPropsAreReadOnly(true);
851 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
853 String imageColour = avm.getValueFromSubValOrArg(imageAv,
854 Arg.IMAGECOLOUR, imageSubVals);
855 ColourSchemeI originalColourScheme = this.getColourScheme(af);
856 this.colourAlignFrame(af, imageColour);
858 Console.info("Writing " + file);
860 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
861 false, fileName, "image", isError);
873 Console.debug("Outputting type '" + type + "' to " + fileName);
874 af.createSVG(file, renderer);
878 Console.debug("Outputting type '" + type + "' to " + fileName);
879 af.createPNG(file, null, userBis);
883 Console.debug("Outputting type '" + type + "' to " + fileName);
884 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
885 htmlSVG.exportHTML(fileName, renderer);
890 "Outputting BioJS MSA Viwer HTML file: " + fileName);
893 BioJsHTMLOutput.refreshVersionInfo(
894 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
895 } catch (URISyntaxException e)
899 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
900 bjs.exportHTML(fileName);
904 Console.debug("Outputting EPS file: " + fileName);
905 af.createEPS(file, renderer);
909 Console.debug("Outputting ImageMap file: " + fileName);
910 af.createImageMap(file, name);
914 addWarn(Arg.IMAGE.argString() + " type '" + type
915 + "' not known. Ignoring");
918 } catch (Exception ioex)
920 addError("Unexpected error during export to '" + fileName + "'",
925 this.colourAlignFrame(af, originalColourScheme);
931 protected boolean processOutput(String id)
933 ArgValuesMap avm = argParser.getLinkedArgs(id);
934 AlignFrame af = afMap.get(id);
938 addWarn("Did not have an alignment window for id=" + id);
942 Boolean isError = Boolean.valueOf(false);
944 if (avm.containsArg(Arg.OUTPUT))
946 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
948 String val = av.getValue();
949 SubVals subVals = av.getSubVals();
950 String fileName = subVals.getContent();
951 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
952 File file = new File(fileName);
954 String name = af.getName();
955 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
957 FileFormats ffs = FileFormats.getInstance();
958 List<String> validFormats = ffs.getWritableFormats(false);
960 FileFormatI ff = null;
961 if (format == null && fileName != null)
963 FORMAT: for (String fname : validFormats)
965 FileFormatI tff = ffs.forName(fname);
966 String[] extensions = tff.getExtensions().split(",");
967 for (String ext : extensions)
969 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
972 format = ff.getName();
978 if (ff == null && format != null)
980 ff = ffs.forName(format);
986 ff = FileFormat.Fasta;
990 StringBuilder validSB = new StringBuilder();
991 for (String f : validFormats)
993 if (validSB.length() > 0)
994 validSB.append(", ");
996 FileFormatI tff = ffs.forName(f);
997 validSB.append(" (");
998 validSB.append(tff.getExtensions());
1002 addError("No valid format specified for "
1003 + Arg.OUTPUT.argString() + ". Valid formats are "
1004 + validSB.toString() + ".");
1009 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1010 fileName, ff.getName(), isError);
1016 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1017 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1018 !Platform.isHeadless());
1020 Console.info("Writing " + fileName);
1022 af.saveAlignment(fileName, ff, stdout, backups);
1023 if (af.isSaveAlignmentSuccessful())
1025 Console.debug("Written alignment '" + name + "' in "
1026 + ff.getName() + " format to '" + file + "'");
1030 addError("Error writing file '" + file + "' in " + ff.getName()
1041 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1044 SubVals subVals = av.getSubVals();
1045 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1046 SequenceI seq = null;
1047 if (subVals == null && idAv == null)
1049 if (af == null || af.getCurrentView() == null)
1053 AlignmentI al = af.getCurrentView().getAlignment();
1058 if (subVals != null)
1060 if (subVals.has(Arg.SEQID.getName()))
1062 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1064 else if (-1 < subVals.getIndex()
1065 && subVals.getIndex() < al.getSequences().size())
1067 seq = al.getSequenceAt(subVals.getIndex());
1070 if (seq == null && idAv != null)
1072 seq = al.findName(idAv.getValue());
1077 public AlignFrame[] getAlignFrames()
1079 AlignFrame[] afs = null;
1082 afs = (AlignFrame[]) afMap.values().toArray();
1088 public List<StructureViewer> getStructureViewers()
1090 List<StructureViewer> svs = null;
1093 for (List<StructureViewer> svList : svMap.values())
1097 svs = new ArrayList<>();
1105 private void colourAlignFrame(AlignFrame af, String colour)
1107 // use string "none" to remove colour scheme
1108 if (colour != null && "" != colour)
1110 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1111 af.getViewport(), af.getViewport().getAlignment(), colour);
1112 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1114 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1118 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1119 colourAlignFrame(af, cs);
1124 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1126 // Note that cs == null removes colour scheme from af
1127 af.changeColour(cs);
1130 private ColourSchemeI getColourScheme(AlignFrame af)
1132 return af.getViewport().getGlobalColourScheme();
1135 private void addInfo(String errorMessage)
1137 Console.info(errorMessage);
1138 errors.add(errorMessage);
1141 private void addWarn(String errorMessage)
1143 Console.warn(errorMessage);
1144 errors.add(errorMessage);
1147 private void addError(String errorMessage)
1149 addError(errorMessage, null);
1152 private void addError(String errorMessage, Exception e)
1154 Console.error(errorMessage, e);
1155 errors.add(errorMessage);
1158 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1159 SubVals subVal, boolean includeBackups, String filename,
1160 String adjective, Boolean isError)
1162 File file = new File(filename);
1164 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1165 null, "OVERWRITE_OUTPUT", false);
1166 boolean stdout = false;
1167 boolean backups = false;
1170 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1171 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1172 // otherwise if headless assume false, if not headless use the user
1173 // preference with default true.
1174 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1175 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1176 !Platform.isHeadless());
1179 if (file.exists() && !(overwrite || backups || stdout))
1181 addWarn("Won't overwrite file '" + filename + "' without "
1182 + Arg.OVERWRITE.argString()
1183 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1188 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1189 "MKDIRS_OUTPUT", false);
1191 if (!FileUtils.checkParentDir(file, mkdirs))
1193 addError("Directory '"
1194 + FileUtils.getParentDir(file).getAbsolutePath()
1195 + "' does not exist for " + adjective + " file '" + filename
1197 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1205 public List<String> getErrors()
1210 public String errorsToString()
1212 StringBuilder sb = new StringBuilder();
1213 for (String error : errors)
1215 if (sb.length() > 0)
1217 sb.append("- " + error);
1219 return sb.toString();