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.ArgParser.Position;
21 import jalview.bin.argparser.ArgValue;
22 import jalview.bin.argparser.ArgValuesMap;
23 import jalview.bin.argparser.SubVals;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.SequenceI;
26 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
27 import jalview.gui.AlignFrame;
28 import jalview.gui.AlignmentPanel;
29 import jalview.gui.AppJmol;
30 import jalview.gui.Desktop;
31 import jalview.gui.Preferences;
32 import jalview.gui.StructureChooser;
33 import jalview.gui.StructureViewer;
34 import jalview.gui.StructureViewer.ViewerType;
35 import jalview.io.AppletFormatAdapter;
36 import jalview.io.BackupFiles;
37 import jalview.io.BioJsHTMLOutput;
38 import jalview.io.DataSourceType;
39 import jalview.io.FileFormat;
40 import jalview.io.FileFormatException;
41 import jalview.io.FileFormatI;
42 import jalview.io.FileFormats;
43 import jalview.io.FileLoader;
44 import jalview.io.HtmlSvgOutput;
45 import jalview.io.IdentifyFile;
46 import jalview.io.NewickFile;
47 import jalview.io.exceptions.ImageOutputException;
48 import jalview.schemes.ColourSchemeI;
49 import jalview.schemes.ColourSchemeProperty;
50 import jalview.structure.StructureImportSettings.TFType;
51 import jalview.structure.StructureSelectionManager;
52 import jalview.util.FileUtils;
53 import jalview.util.HttpUtils;
54 import jalview.util.ImageMaker;
55 import jalview.util.ImageMaker.TYPE;
56 import jalview.util.MessageManager;
57 import jalview.util.Platform;
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);
146 StringBuilder sb = new StringBuilder();
147 for (String error : errors)
149 sb.append("- " + error);
152 if (Platform.isHeadless())
154 Console.debug("All errors from command line argument commands:\n"
159 // scrollable dialog box
163 if (argParser.getBoolean(Arg.QUIT))
165 Jalview.getInstance().exit(
166 "Exiting due to " + Arg.QUIT.argString() + " argument.",
170 // carry on with jalview.bin.Jalview
171 argsWereParsed = theseArgsWereParsed;
172 return argsWereParsed;
175 public boolean commandArgsProvided()
177 return commandArgsProvided;
180 public boolean argsWereParsed()
182 return argsWereParsed;
185 protected boolean processLinked(String id)
187 boolean theseArgsWereParsed = false;
188 ArgValuesMap avm = argParser.getLinkedArgs(id);
194 boolean isError = false;
196 // set wrap scope here so it can be applied after structures are opened
197 boolean wrap = false;
199 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
201 commandArgsProvided = true;
204 boolean first = true;
205 boolean progressBarSet = false;
207 // Combine the APPEND and OPEN files into one list, along with whether it
208 // was APPEND or OPEN
209 List<ArgValue> openAvList = new ArrayList<>();
210 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
211 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
212 // sort avlist based on av.getArgIndex()
213 Collections.sort(openAvList);
214 for (ArgValue av : openAvList)
217 SubVals sv = av.getSubVals();
218 String openFile = av.getValue();
219 if (openFile == null)
222 theseArgsWereParsed = true;
226 if (!headless && desktop != null)
228 desktop.setProgressBar(
229 MessageManager.getString(
230 "status.processing_commandline_args"),
231 progress = System.currentTimeMillis());
232 progressBarSet = true;
236 if (!Platform.isJS())
238 * ignore in JavaScript -- can't just file existence - could load it?
243 if (!HttpUtils.startsWithHttpOrHttps(openFile))
245 if (!(new File(openFile)).exists())
247 addError("Can't find file '" + openFile + "'");
254 DataSourceType protocol = AppletFormatAdapter
255 .checkProtocol(openFile);
257 FileFormatI format = null;
260 format = new IdentifyFile().identify(openFile, protocol);
261 } catch (FileFormatException e1)
263 addError("Unknown file format for '" + openFile + "'");
269 // When to open a new AlignFrame
270 if (af == null || "true".equals(av.getSubVal("new"))
271 || a == Arg.OPEN || format == FileFormat.Jalview)
275 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
280 "Opening '" + openFile + "' in new alignment frame");
281 FileLoader fileLoader = new FileLoader(!headless);
282 boolean xception = false;
285 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
287 } catch (Throwable thr)
290 addError("Couldn't open '" + openFile + "' as " + format + " "
291 + thr.getLocalizedMessage()
292 + " (Enable debug for full stack trace)");
294 Console.debug("Exception when opening '" + openFile + "'", thr);
297 if (af == null && !xception)
299 addInfo("Ignoring '" + openFile
300 + "' - no alignment data found.");
306 String colour = ArgParser.getFromSubValArgOrPref(avm, av,
307 Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
310 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
311 af.getViewport(), af.getViewport().getAlignment(),
314 if (cs == null && !"None".equals(colour))
316 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
322 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
325 // Change alignment frame title
326 String title = ArgParser.getFromSubValArgOrPref(avm, av,
327 Arg.TITLE, sv, null, null, null);
331 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
335 String featuresfile = ArgParser.getValueFromSubValOrArg(avm, av,
337 if (featuresfile != null)
339 af.parseFeaturesFile(featuresfile,
340 AppletFormatAdapter.checkProtocol(featuresfile));
341 Jalview.testoutput(argParser, Arg.FEATURES,
342 "examples/testdata/plantfdx.features", featuresfile);
345 // Add annotations from file
346 String annotationsfile = ArgParser.getValueFromSubValOrArg(avm,
347 av, Arg.ANNOTATIONS, sv);
348 if (annotationsfile != null)
350 af.loadJalviewDataFile(annotationsfile, null, null, null);
351 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
352 "examples/testdata/plantfdx.annotations",
356 // Set or clear the sortbytree flag
357 boolean sortbytree = ArgParser.getBoolFromSubValOrArg(avm,
361 af.getViewport().setSortByTree(true);
362 Jalview.testoutput(argParser, Arg.SORTBYTREE);
365 // Load tree from file
366 String treefile = ArgParser.getValueFromSubValOrArg(avm, av,
368 if (treefile != null)
372 NewickFile nf = new NewickFile(treefile,
373 AppletFormatAdapter.checkProtocol(treefile));
374 af.getViewport().setCurrentTree(
375 af.showNewickTree(nf, treefile).getTree());
376 Jalview.testoutput(argParser, Arg.TREE,
377 "examples/testdata/uniref50_test_tree", treefile);
378 } catch (IOException e)
380 addError("Couldn't add tree " + treefile, e);
385 // Show secondary structure annotations?
386 boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
387 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
388 "STRUCT_FROM_PDB", true);
389 af.setAnnotationsVisibility(showSSAnnotations, true, false);
391 // Show sequence annotations?
392 boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
393 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
394 "SHOW_ANNOTATIONS", true);
395 af.setAnnotationsVisibility(showAnnotations, false, true);
397 // show temperature factor annotations?
398 if (avm.getBoolean(Arg.NOTEMPFAC))
400 // do this better (annotation types?)
401 List<String> hideThese = new ArrayList<>();
402 hideThese.add("Temperature Factor");
403 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
404 AlignmentUtils.showOrHideSequenceAnnotations(
405 af.getCurrentView().getAlignment(), hideThese, null,
409 // wrap alignment? do this last for formatting reasons
410 wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv, null,
411 "WRAP_ALIGNMENT", false);
412 // af.setWrapFormat(wrap) is applied after structures are opened for
413 // annotation reasons
415 // store the AlignFrame for this id
418 // is it its own structure file?
419 if (format.isStructureFile())
421 StructureSelectionManager ssm = StructureSelectionManager
422 .getStructureSelectionManager(Desktop.instance);
423 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
424 ssm.computeMapping(false, new SequenceI[] { seq }, null,
425 openFile, DataSourceType.FILE, null, null, null, false);
431 "Opening '" + openFile + "' in existing alignment frame");
432 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
434 : DataSourceType.FILE;
435 FileLoader fileLoader = new FileLoader(!headless);
436 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
440 Console.debug("Command " + Arg.APPEND + " executed successfully!");
443 if (first) // first=true means nothing opened
447 Jalview.exit("Could not open any files in headless mode",
452 Console.info("No more files to open");
455 if (progressBarSet && desktop != null)
456 desktop.setProgressBar(null, progress);
460 // open the structure (from same PDB file or given PDBfile)
461 if (!avm.getBoolean(Arg.NOSTRUCTURE))
463 AlignFrame af = afMap.get(id);
464 if (avm.containsArg(Arg.STRUCTURE))
466 commandArgsProvided = true;
467 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
469 String val = av.getValue();
470 SubVals subVals = av.getSubVals();
471 SequenceI seq = getSpecifiedSequence(af, avm, av);
474 // Could not find sequence from subId, let's assume the first
475 // sequence in the alignframe
476 AlignmentI al = af.getCurrentView().getAlignment();
477 seq = al.getSequenceAt(0);
482 addWarn("Could not find sequence for argument "
483 + Arg.STRUCTURE.argString() + "=" + val);
486 File structureFile = null;
487 if (subVals.getContent() != null
488 && subVals.getContent().length() != 0)
490 structureFile = new File(subVals.getContent());
491 Console.debug("Using structure file (from argument) '"
492 + structureFile.getAbsolutePath() + "'");
496 * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
497 * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
498 * selectedSequence, true, Desktop.instance);
500 * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
501 * SequenceI[] { selectedSequence });
504 /* THIS DOESN'T WORK */
505 else if (seq.getAllPDBEntries() != null
506 && seq.getAllPDBEntries().size() > 0)
508 structureFile = new File(
509 seq.getAllPDBEntries().elementAt(0).getFile());
510 Console.debug("Using structure file (from sequence) '"
511 + structureFile.getAbsolutePath() + "'");
514 if (structureFile == null)
516 addWarn("Not provided structure file with '" + val + "'");
520 if (!structureFile.exists())
522 addWarn("Structure file '" + structureFile.getAbsoluteFile()
527 Console.debug("Using structure file "
528 + structureFile.getAbsolutePath());
530 // open structure view
531 AlignmentPanel ap = af.alignPanel;
534 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
535 StructureViewer.ViewerType.JMOL.toString());
538 String structureFilepath = structureFile.getAbsolutePath();
540 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
541 String paeFilepath = ArgParser
542 .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
543 Arg.PAEMATRIX, Position.AFTER, av, subVals, null,
545 if (paeFilepath != null)
547 File paeFile = new File(paeFilepath);
551 paeFilepath = paeFile.getCanonicalPath();
552 } catch (IOException e)
554 paeFilepath = paeFile.getAbsolutePath();
555 addWarn("Problem with the PAE file path: '"
556 + paeFile.getPath() + "'");
560 // showing annotations from structure file or not
561 boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
562 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
565 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
566 // reference annotations
567 String tftString = ArgParser
568 .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
569 Arg.TEMPFAC, Position.AFTER, av, subVals, null,
571 boolean notempfac = ArgParser.getFromSubValArgOrPref(avm,
572 Arg.NOTEMPFAC, subVals, null, "ADD_TEMPFACT_ANN", false,
574 TFType tft = notempfac ? null : TFType.DEFAULT;
575 if (tftString != null && !notempfac)
577 // get kind of temperature factor annotation
580 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
581 Console.debug("Obtained Temperature Factor type of '" + tft
582 + "' for structure '" + structureFilepath + "'");
583 } catch (IllegalArgumentException e)
585 // Just an error message!
586 StringBuilder sb = new StringBuilder().append("Cannot set ")
587 .append(Arg.TEMPFAC.argString()).append(" to '")
589 .append("', ignoring. Valid values are: ");
590 Iterator<TFType> it = Arrays.stream(TFType.values())
594 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
598 addWarn(sb.toString());
602 String sViewer = ArgParser.getFromSubValArgOrPref(avm,
603 Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals, null,
605 ViewerType viewerType = ViewerType.getFromString(sViewer);
607 // TODO use ssFromStructure
608 StructureViewer sv = StructureChooser
609 .openStructureFileForSequence(null, null, ap, seq, false,
610 structureFilepath, tft, paeFilepath, false,
611 ssFromStructure, false, viewerType);
615 addError("Failed to import and open structure view for file '"
616 + structureFile + "'.");
622 while (sv.isBusy() && tries > 0)
629 "Waiting for viewer for " + structureFilepath);
632 if (tries == 0 && sv.isBusy())
634 addWarn("Gave up waiting for structure viewer to load file '"
636 + "'. Something may have gone wrong.");
638 } catch (Exception x)
640 addError("Exception whilst waiting for structure viewer "
641 + structureFilepath, x);
645 // add StructureViewer to svMap list
648 svMap = new HashMap<>();
650 if (svMap.get(id) == null)
652 svMap.put(id, new ArrayList<>());
654 svMap.get(id).add(sv);
657 "Successfully opened viewer for " + structureFilepath);
658 String structureImageFilename = ArgParser.getValueFromSubValOrArg(
659 avm, av, Arg.STRUCTUREIMAGE, subVals);
660 if (sv != null && structureImageFilename != null)
662 ArgValue siAv = avm.getClosestNextArgValueOfArg(av,
665 if (structureImageFilename.equals(siAv.getValue()))
667 sisv = siAv.getSubVals();
669 File structureImageFile = new File(structureImageFilename);
670 String width = ArgParser.getValueFromSubValOrArg(avm, av,
671 Arg.STRUCTUREIMAGEWIDTH, sisv);
672 String height = ArgParser.getValueFromSubValOrArg(avm, av,
673 Arg.STRUCTUREIMAGEHEIGHT, sisv);
674 String scale = ArgParser.getValueFromSubValOrArg(avm, av,
675 Arg.STRUCTUREIMAGESCALE, sisv);
676 String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
677 Arg.STRUCTUREIMAGETEXTRENDERER, sisv);
678 String typeS = ArgParser.getValueFromSubValOrArg(avm, av,
679 Arg.STRUCTUREIMAGETYPE, sisv);
680 if (typeS == null || typeS.length() == 0)
682 typeS = FileUtils.getExtension(structureImageFile);
687 imageType = Enum.valueOf(TYPE.class,
688 typeS.toUpperCase(Locale.ROOT));
689 } catch (IllegalArgumentException e)
691 addWarn("Do not know image format '" + typeS
693 imageType = TYPE.PNG;
695 BitmapImageSizing userBis = ImageMaker
696 .parseScaleWidthHeightStrings(scale, width, height);
697 // TODO MAKE THIS VIEWER INDEPENDENT!!
698 switch (StructureViewer.getViewerType())
701 JalviewStructureDisplayI sview = sv
702 .getJalviewStructureDisplay();
703 if (sview instanceof AppJmol)
705 AppJmol jmol = (AppJmol) sview;
708 whatNext wn = this.checksBeforeWritingToFile(avm, subVals,
709 false, structureImageFilename, "structure image");
710 if (wn == whatNext.ERROR)
715 else if (wn == whatNext.CONTINUE)
720 Console.debug("Rendering image to " + structureImageFile);
721 jmol.makePDBImage(structureImageFile, imageType, renderer,
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 + sv.getViewerType() + " yet");
748 AlignFrame af = afMap.get(id);
751 af.setWrapFormat(wrap, true);
756 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
759 AlignFrame af = afMap.get(id);
760 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
761 .findAnnotation(PDBChain.class.getName().toString()))
763 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
764 af.alignPanel.av.getGlobalColourScheme(), 0);
765 acg.setSeqAssociated(true);
766 af.changeColour(acg);
767 Console.info("Changed colour " + acg.toString());
772 return theseArgsWereParsed && !isError;
775 protected void processGroovyScript(String id)
777 ArgValuesMap avm = argParser.getLinkedArgs(id);
778 AlignFrame af = afMap.get(id);
782 addWarn("Did not have an alignment window for id=" + id);
786 if (avm.containsArg(Arg.GROOVY))
788 String groovyscript = avm.getValue(Arg.GROOVY);
789 if (groovyscript != null)
791 // Execute the groovy script after we've done all the rendering stuff
792 // and before any images or figures are generated.
793 Console.info("Executing script " + groovyscript);
794 Jalview.getInstance().executeGroovyScript(groovyscript, af);
799 protected boolean processImages(String id)
801 ArgValuesMap avm = argParser.getLinkedArgs(id);
802 AlignFrame af = afMap.get(id);
806 addWarn("Did not have an alignment window for id=" + id);
810 boolean isError = false;
811 if (avm.containsArg(Arg.IMAGE))
813 for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
815 String val = av.getValue();
816 SubVals subVal = av.getSubVals();
817 String fileName = subVal.getContent();
818 File file = new File(fileName);
819 String name = af.getName();
820 String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
821 Arg.TEXTRENDERER, subVal);
822 if (renderer == null)
824 String type = "png"; // default
826 String scale = ArgParser.getValueFromSubValOrArg(avm, av, Arg.SCALE,
828 String width = ArgParser.getValueFromSubValOrArg(avm, av, Arg.WIDTH,
830 String height = ArgParser.getValueFromSubValOrArg(avm, av,
832 BitmapImageSizing userBis = ImageMaker
833 .parseScaleWidthHeightStrings(scale, width, height);
835 type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
836 if (type == null && fileName != null)
838 for (String ext : new String[] { "svg", "png", "html", "eps" })
840 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
846 // for moment we disable JSON export
847 Cache.setPropsAreReadOnly(true);
848 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
850 Console.info("Writing " + file);
852 whatNext wn = this.checksBeforeWritingToFile(avm, subVal, false,
854 if (wn == whatNext.ERROR)
859 else if (wn == whatNext.CONTINUE)
870 Console.debug("Outputting type '" + type + "' to " + fileName);
871 af.createSVG(file, renderer);
875 Console.debug("Outputting type '" + type + "' to " + fileName);
876 af.createPNG(file, null, userBis);
880 Console.debug("Outputting type '" + type + "' to " + fileName);
881 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
882 htmlSVG.exportHTML(fileName, renderer);
887 "Outputting BioJS MSA Viwer HTML file: " + fileName);
890 BioJsHTMLOutput.refreshVersionInfo(
891 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
892 } catch (URISyntaxException e)
896 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
897 bjs.exportHTML(fileName);
901 Console.debug("Outputting EPS file: " + fileName);
902 af.createEPS(file, renderer);
906 Console.debug("Outputting ImageMap file: " + fileName);
907 af.createImageMap(file, name);
911 addWarn(Arg.IMAGE.argString() + " type '" + type
912 + "' not known. Ignoring");
915 } catch (Exception ioex)
917 addError("Unexpected error during export to '" + fileName + "'",
926 protected boolean processOutput(String id)
928 ArgValuesMap avm = argParser.getLinkedArgs(id);
929 AlignFrame af = afMap.get(id);
933 addWarn("Did not have an alignment window for id=" + id);
937 boolean isError = false;
939 if (avm.containsArg(Arg.OUTPUT))
941 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
943 String val = av.getValue();
944 SubVals subVals = av.getSubVals();
945 String fileName = subVals.getContent();
946 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
947 File file = new File(fileName);
949 String name = af.getName();
950 String format = ArgParser.getValueFromSubValOrArg(avm, av,
951 Arg.FORMAT, subVals);
952 FileFormats ffs = FileFormats.getInstance();
953 List<String> validFormats = ffs.getWritableFormats(false);
955 FileFormatI ff = null;
956 if (format == null && fileName != null)
958 FORMAT: for (String fname : validFormats)
960 FileFormatI tff = ffs.forName(fname);
961 String[] extensions = tff.getExtensions().split(",");
962 for (String ext : extensions)
964 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
967 format = ff.getName();
973 if (ff == null && format != null)
975 ff = ffs.forName(format);
981 ff = FileFormat.Fasta;
985 StringBuilder validSB = new StringBuilder();
986 for (String f : validFormats)
988 if (validSB.length() > 0)
989 validSB.append(", ");
991 FileFormatI tff = ffs.forName(f);
992 validSB.append(" (");
993 validSB.append(tff.getExtensions());
997 addError("No valid format specified for "
998 + Arg.OUTPUT.argString() + ". Valid formats are "
999 + validSB.toString() + ".");
1004 whatNext wn = this.checksBeforeWritingToFile(avm, subVals, true,
1005 fileName, ff.getName());
1006 if (wn == whatNext.ERROR)
1011 else if (wn == whatNext.CONTINUE)
1016 boolean backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS,
1018 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1019 !Platform.isHeadless());
1021 Console.info("Writing " + fileName);
1023 af.saveAlignment(fileName, ff, stdout, backups);
1024 if (af.isSaveAlignmentSuccessful())
1026 Console.debug("Written alignment '" + name + "' in "
1027 + ff.getName() + " format to '" + file + "'");
1031 addError("Error writing file '" + file + "' in " + ff.getName()
1042 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1045 SubVals subVals = av.getSubVals();
1046 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID);
1047 SequenceI seq = null;
1048 if (subVals == null && idAv == null)
1050 if (af == null || af.getCurrentView() == null)
1054 AlignmentI al = af.getCurrentView().getAlignment();
1059 if (subVals != null)
1061 if (subVals.has(Arg.SEQID.getName()))
1063 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1065 else if (-1 < subVals.getIndex()
1066 && subVals.getIndex() < al.getSequences().size())
1068 seq = al.getSequenceAt(subVals.getIndex());
1071 if (seq == null && idAv != null)
1073 seq = al.findName(idAv.getValue());
1078 public AlignFrame[] getAlignFrames()
1080 AlignFrame[] afs = null;
1083 afs = (AlignFrame[]) afMap.values().toArray();
1089 public List<StructureViewer> getStructureViewers()
1091 List<StructureViewer> svs = null;
1094 for (List<StructureViewer> svList : svMap.values())
1098 svs = new ArrayList<>();
1106 private void addInfo(String errorMessage)
1108 Console.info(errorMessage);
1109 errors.add(errorMessage);
1112 private void addWarn(String errorMessage)
1114 Console.warn(errorMessage);
1115 errors.add(errorMessage);
1118 private void addError(String errorMessage)
1120 addError(errorMessage, null);
1123 private void addError(String errorMessage, Exception e)
1125 Console.error(errorMessage, e);
1126 errors.add(errorMessage);
1129 private enum whatNext
1131 OKAY, CONTINUE, ERROR;
1134 private whatNext checksBeforeWritingToFile(ArgValuesMap avm,
1135 SubVals subVal, boolean includeBackups, String filename,
1138 File file = new File(filename);
1140 boolean overwrite = ArgParser.getFromSubValArgOrPref(avm, Arg.OVERWRITE,
1141 subVal, null, "OVERWRITE_OUTPUT", false);
1142 boolean stdout = false;
1143 boolean backups = false;
1146 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1147 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1148 // otherwise if headless assume false, if not headless use the user
1149 // preference with default true.
1150 backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS, subVal,
1151 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1152 !Platform.isHeadless());
1155 if (file.exists() && !(overwrite || backups || stdout))
1157 addWarn("Won't overwrite file '" + filename + "' without "
1158 + Arg.OVERWRITE.argString()
1159 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1161 return whatNext.CONTINUE;
1164 boolean mkdirs = ArgParser.getFromSubValArgOrPref(avm, Arg.MKDIRS,
1165 subVal, null, "MKDIRS_OUTPUT", false);
1167 if (!FileUtils.checkParentDir(file, mkdirs))
1169 addError("Directory '"
1170 + FileUtils.getParentDir(file).getAbsolutePath()
1171 + "' does not exist for " + adjective + " file '" + filename
1173 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1174 return whatNext.ERROR;
1177 return whatNext.OKAY;