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);
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 = ArgParser.getFromSubValArgOrPref(avm, av,
295 Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
298 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
299 af.getViewport(), af.getViewport().getAlignment(),
302 if (cs == null && !"None".equals(colour))
304 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
310 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
313 // Change alignment frame title
314 String title = ArgParser.getFromSubValArgOrPref(avm, av,
315 Arg.TITLE, sv, null, null, null);
319 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
323 String featuresfile = ArgParser.getValueFromSubValOrArg(avm, av,
325 if (featuresfile != null)
327 af.parseFeaturesFile(featuresfile,
328 AppletFormatAdapter.checkProtocol(featuresfile));
329 Jalview.testoutput(argParser, Arg.FEATURES,
330 "examples/testdata/plantfdx.features", featuresfile);
333 // Add annotations from file
334 String annotationsfile = ArgParser.getValueFromSubValOrArg(avm,
335 av, Arg.ANNOTATIONS, sv);
336 if (annotationsfile != null)
338 af.loadJalviewDataFile(annotationsfile, null, null, null);
339 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
340 "examples/testdata/plantfdx.annotations",
344 // Set or clear the sortbytree flag
345 boolean sortbytree = ArgParser.getBoolFromSubValOrArg(avm,
349 af.getViewport().setSortByTree(true);
350 Jalview.testoutput(argParser, Arg.SORTBYTREE);
353 // Load tree from file
354 String treefile = ArgParser.getValueFromSubValOrArg(avm, av,
356 if (treefile != null)
360 NewickFile nf = new NewickFile(treefile,
361 AppletFormatAdapter.checkProtocol(treefile));
362 af.getViewport().setCurrentTree(
363 af.showNewickTree(nf, treefile).getTree());
364 Jalview.testoutput(argParser, Arg.TREE,
365 "examples/testdata/uniref50_test_tree", treefile);
366 } catch (IOException e)
368 addError("Couldn't add tree " + treefile, e);
373 // Show secondary structure annotations?
374 boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
375 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
376 "STRUCT_FROM_PDB", true);
377 af.setAnnotationsVisibility(showSSAnnotations, true, false);
379 // Show sequence annotations?
380 boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
381 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
382 "SHOW_ANNOTATIONS", true);
383 af.setAnnotationsVisibility(showAnnotations, false, true);
385 // show temperature factor annotations?
386 if (avm.getBoolean(Arg.NOTEMPFAC))
388 // do this better (annotation types?)
389 List<String> hideThese = new ArrayList<>();
390 hideThese.add("Temperature Factor");
391 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
392 AlignmentUtils.showOrHideSequenceAnnotations(
393 af.getCurrentView().getAlignment(), hideThese, null,
397 // wrap alignment? do this last for formatting reasons
398 wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv, null,
399 "WRAP_ALIGNMENT", false);
400 // af.setWrapFormat(wrap) is applied after structures are opened for
401 // annotation reasons
403 // store the AlignFrame for this id
406 // is it its own structure file?
407 if (format.isStructureFile())
409 StructureSelectionManager ssm = StructureSelectionManager
410 .getStructureSelectionManager(Desktop.instance);
411 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
412 ssm.computeMapping(false, new SequenceI[] { seq }, null,
413 openFile, DataSourceType.FILE, null, null, null, false);
419 "Opening '" + openFile + "' in existing alignment frame");
420 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
422 : DataSourceType.FILE;
423 FileLoader fileLoader = new FileLoader(!headless);
424 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
428 Console.debug("Command " + Arg.APPEND + " executed successfully!");
431 if (first) // first=true means nothing opened
435 Jalview.exit("Could not open any files in headless mode",
440 Console.info("No more files to open");
443 if (progressBarSet && desktop != null)
444 desktop.setProgressBar(null, progress);
448 // open the structure (from same PDB file or given PDBfile)
449 if (!avm.getBoolean(Arg.NOSTRUCTURE))
451 AlignFrame af = afMap.get(id);
452 if (avm.containsArg(Arg.STRUCTURE))
454 commandArgsProvided = true;
455 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
457 String val = av.getValue();
458 SubVals subVals = av.getSubVals();
459 SequenceI seq = getSpecifiedSequence(af, avm, av);
462 // Could not find sequence from subId, let's assume the first
463 // sequence in the alignframe
464 AlignmentI al = af.getCurrentView().getAlignment();
465 seq = al.getSequenceAt(0);
470 addWarn("Could not find sequence for argument "
471 + Arg.STRUCTURE.argString() + "=" + val);
474 File structureFile = null;
475 if (subVals.getContent() != null
476 && subVals.getContent().length() != 0)
478 structureFile = new File(subVals.getContent());
479 Console.debug("Using structure file (from argument) '"
480 + structureFile.getAbsolutePath() + "'");
484 * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
485 * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
486 * selectedSequence, true, Desktop.instance);
488 * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
489 * SequenceI[] { selectedSequence });
492 /* THIS DOESN'T WORK */
493 else if (seq.getAllPDBEntries() != null
494 && seq.getAllPDBEntries().size() > 0)
496 structureFile = new File(
497 seq.getAllPDBEntries().elementAt(0).getFile());
498 Console.debug("Using structure file (from sequence) '"
499 + structureFile.getAbsolutePath() + "'");
502 if (structureFile == null)
504 addWarn("Not provided structure file with '" + val + "'");
508 if (!structureFile.exists())
510 addWarn("Structure file '" + structureFile.getAbsoluteFile()
515 Console.debug("Using structure file "
516 + structureFile.getAbsolutePath());
518 // open structure view
519 AlignmentPanel ap = af.alignPanel;
522 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
523 StructureViewer.ViewerType.JMOL.toString());
526 String structureFilepath = structureFile.getAbsolutePath();
528 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
529 String paeFilepath = ArgParser
530 .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
531 Arg.PAEMATRIX, Position.AFTER, av, subVals, null,
533 if (paeFilepath != null)
535 File paeFile = new File(paeFilepath);
539 paeFilepath = paeFile.getCanonicalPath();
540 } catch (IOException e)
542 paeFilepath = paeFile.getAbsolutePath();
543 addWarn("Problem with the PAE file path: '"
544 + paeFile.getPath() + "'");
548 // showing annotations from structure file or not
549 boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
550 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
553 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
554 // reference annotations
555 String tftString = ArgParser
556 .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
557 Arg.TEMPFAC, Position.AFTER, av, subVals, null,
559 boolean notempfac = ArgParser.getFromSubValArgOrPref(avm,
560 Arg.NOTEMPFAC, subVals, null, "ADD_TEMPFACT_ANN", false,
562 TFType tft = notempfac ? null : TFType.DEFAULT;
563 if (tftString != null && !notempfac)
565 // get kind of temperature factor annotation
568 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
569 Console.debug("Obtained Temperature Factor type of '" + tft
570 + "' for structure '" + structureFilepath + "'");
571 } catch (IllegalArgumentException e)
573 // Just an error message!
574 StringBuilder sb = new StringBuilder().append("Cannot set ")
575 .append(Arg.TEMPFAC.argString()).append(" to '")
577 .append("', ignoring. Valid values are: ");
578 Iterator<TFType> it = Arrays.stream(TFType.values())
582 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
586 addWarn(sb.toString());
590 String sViewer = ArgParser.getFromSubValArgOrPref(avm,
591 Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals, null,
593 ViewerType viewerType = ViewerType.getFromString(sViewer);
595 // TODO use ssFromStructure
596 StructureViewer sv = StructureChooser
597 .openStructureFileForSequence(null, null, ap, seq, false,
598 structureFilepath, tft, paeFilepath, false,
599 ssFromStructure, false, viewerType);
603 addError("Failed to import and open structure view for file '"
604 + structureFile + "'.");
610 while (sv.isBusy() && tries > 0)
617 "Waiting for viewer for " + structureFilepath);
620 if (tries == 0 && sv.isBusy())
622 addWarn("Gave up waiting for structure viewer to load file '"
624 + "'. Something may have gone wrong.");
626 } catch (Exception x)
628 addError("Exception whilst waiting for structure viewer "
629 + structureFilepath, x);
633 // add StructureViewer to svMap list
636 svMap = new HashMap<>();
638 if (svMap.get(id) == null)
640 svMap.put(id, new ArrayList<>());
642 svMap.get(id).add(sv);
645 "Successfully opened viewer for " + structureFilepath);
646 String structureImageFilename = ArgParser.getValueFromSubValOrArg(
647 avm, av, Arg.STRUCTUREIMAGE, subVals);
648 if (sv != null && structureImageFilename != null)
650 ArgValue siAv = avm.getClosestNextArgValueOfArg(av,
653 if (structureImageFilename.equals(siAv.getValue()))
655 sisv = siAv.getSubVals();
657 File structureImageFile = new File(structureImageFilename);
658 String width = ArgParser.getValueFromSubValOrArg(avm, av,
659 Arg.STRUCTUREIMAGEWIDTH, sisv);
660 String height = ArgParser.getValueFromSubValOrArg(avm, av,
661 Arg.STRUCTUREIMAGEHEIGHT, sisv);
662 String scale = ArgParser.getValueFromSubValOrArg(avm, av,
663 Arg.STRUCTUREIMAGESCALE, sisv);
664 String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
665 Arg.STRUCTUREIMAGETEXTRENDERER, sisv);
666 String typeS = ArgParser.getValueFromSubValOrArg(avm, av,
667 Arg.STRUCTUREIMAGETYPE, sisv);
668 if (typeS == null || typeS.length() == 0)
670 typeS = FileUtils.getExtension(structureImageFile);
675 imageType = Enum.valueOf(TYPE.class,
676 typeS.toUpperCase(Locale.ROOT));
677 } catch (IllegalArgumentException e)
679 addWarn("Do not know image format '" + typeS
681 imageType = TYPE.PNG;
683 BitmapImageSizing userBis = ImageMaker
684 .parseScaleWidthHeightStrings(scale, width, height);
685 // TODO MAKE THIS VIEWER INDEPENDENT!!
686 switch (StructureViewer.getViewerType())
689 JalviewStructureDisplayI sview = sv
690 .getJalviewStructureDisplay();
691 if (sview instanceof AppJmol)
693 AppJmol jmol = (AppJmol) sview;
696 boolean success = this.checksBeforeWritingToFile(avm,
697 subVals, false, structureImageFilename,
698 "structure image", isError);
704 Console.debug("Rendering image to " + structureImageFile);
705 jmol.makePDBImage(structureImageFile, imageType, renderer,
707 Console.debug("Finished Rendering image to "
708 + structureImageFile);
710 } catch (ImageOutputException ioexc)
712 addError("Unexpected error whilst exporting image to "
713 + structureImageFile, ioexc);
721 addWarn("Cannot export image for structure viewer "
722 + sv.getViewerType() + " yet");
732 AlignFrame af = afMap.get(id);
735 af.setWrapFormat(wrap, true);
740 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
743 AlignFrame af = afMap.get(id);
744 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
745 .findAnnotation(PDBChain.class.getName().toString()))
747 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
748 af.alignPanel.av.getGlobalColourScheme(), 0);
749 acg.setSeqAssociated(true);
750 af.changeColour(acg);
751 Console.info("Changed colour " + acg.toString());
756 return theseArgsWereParsed && !isError;
759 protected void processGroovyScript(String id)
761 ArgValuesMap avm = argParser.getLinkedArgs(id);
762 AlignFrame af = afMap.get(id);
766 addWarn("Did not have an alignment window for id=" + id);
770 if (avm.containsArg(Arg.GROOVY))
772 String groovyscript = avm.getValue(Arg.GROOVY);
773 if (groovyscript != null)
775 // Execute the groovy script after we've done all the rendering stuff
776 // and before any images or figures are generated.
777 Console.info("Executing script " + groovyscript);
778 Jalview.getInstance().executeGroovyScript(groovyscript, af);
783 protected boolean processImages(String id)
785 ArgValuesMap avm = argParser.getLinkedArgs(id);
786 AlignFrame af = afMap.get(id);
790 addWarn("Did not have an alignment window for id=" + id);
794 Boolean isError = Boolean.valueOf(false);
795 if (avm.containsArg(Arg.IMAGE))
797 for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
799 String val = av.getValue();
800 SubVals subVal = av.getSubVals();
801 String fileName = subVal.getContent();
802 File file = new File(fileName);
803 String name = af.getName();
804 String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
805 Arg.TEXTRENDERER, subVal);
806 if (renderer == null)
808 String type = "png"; // default
810 String scale = ArgParser.getValueFromSubValOrArg(avm, av, Arg.SCALE,
812 String width = ArgParser.getValueFromSubValOrArg(avm, av, Arg.WIDTH,
814 String height = ArgParser.getValueFromSubValOrArg(avm, av,
816 BitmapImageSizing userBis = ImageMaker
817 .parseScaleWidthHeightStrings(scale, width, height);
819 type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
820 if (type == null && fileName != null)
822 for (String ext : new String[] { "svg", "png", "html", "eps" })
824 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
830 // for moment we disable JSON export
831 Cache.setPropsAreReadOnly(true);
832 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
834 Console.info("Writing " + file);
836 boolean success = checksBeforeWritingToFile(avm, subVal, false,
837 fileName, "image", isError);
849 Console.debug("Outputting type '" + type + "' to " + fileName);
850 af.createSVG(file, renderer);
854 Console.debug("Outputting type '" + type + "' to " + fileName);
855 af.createPNG(file, null, userBis);
859 Console.debug("Outputting type '" + type + "' to " + fileName);
860 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
861 htmlSVG.exportHTML(fileName, renderer);
866 "Outputting BioJS MSA Viwer HTML file: " + fileName);
869 BioJsHTMLOutput.refreshVersionInfo(
870 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
871 } catch (URISyntaxException e)
875 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
876 bjs.exportHTML(fileName);
880 Console.debug("Outputting EPS file: " + fileName);
881 af.createEPS(file, renderer);
885 Console.debug("Outputting ImageMap file: " + fileName);
886 af.createImageMap(file, name);
890 addWarn(Arg.IMAGE.argString() + " type '" + type
891 + "' not known. Ignoring");
894 } catch (Exception ioex)
896 addError("Unexpected error during export to '" + fileName + "'",
905 protected boolean processOutput(String id)
907 ArgValuesMap avm = argParser.getLinkedArgs(id);
908 AlignFrame af = afMap.get(id);
912 addWarn("Did not have an alignment window for id=" + id);
916 Boolean isError = Boolean.valueOf(false);
918 if (avm.containsArg(Arg.OUTPUT))
920 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
922 String val = av.getValue();
923 SubVals subVals = av.getSubVals();
924 String fileName = subVals.getContent();
925 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
926 File file = new File(fileName);
928 String name = af.getName();
929 String format = ArgParser.getValueFromSubValOrArg(avm, av,
930 Arg.FORMAT, subVals);
931 FileFormats ffs = FileFormats.getInstance();
932 List<String> validFormats = ffs.getWritableFormats(false);
934 FileFormatI ff = null;
935 if (format == null && fileName != null)
937 FORMAT: for (String fname : validFormats)
939 FileFormatI tff = ffs.forName(fname);
940 String[] extensions = tff.getExtensions().split(",");
941 for (String ext : extensions)
943 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
946 format = ff.getName();
952 if (ff == null && format != null)
954 ff = ffs.forName(format);
960 ff = FileFormat.Fasta;
964 StringBuilder validSB = new StringBuilder();
965 for (String f : validFormats)
967 if (validSB.length() > 0)
968 validSB.append(", ");
970 FileFormatI tff = ffs.forName(f);
971 validSB.append(" (");
972 validSB.append(tff.getExtensions());
976 addError("No valid format specified for "
977 + Arg.OUTPUT.argString() + ". Valid formats are "
978 + validSB.toString() + ".");
983 boolean success = checksBeforeWritingToFile(avm, subVals, true,
984 fileName, ff.getName(), isError);
990 boolean backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS,
992 Platform.isHeadless() ? null : BackupFiles.ENABLED,
993 !Platform.isHeadless());
995 Console.info("Writing " + fileName);
997 af.saveAlignment(fileName, ff, stdout, backups);
998 if (af.isSaveAlignmentSuccessful())
1000 Console.debug("Written alignment '" + name + "' in "
1001 + ff.getName() + " format to '" + file + "'");
1005 addError("Error writing file '" + file + "' in " + ff.getName()
1016 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1019 SubVals subVals = av.getSubVals();
1020 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID);
1021 SequenceI seq = null;
1022 if (subVals == null && idAv == null)
1024 if (af == null || af.getCurrentView() == null)
1028 AlignmentI al = af.getCurrentView().getAlignment();
1033 if (subVals != null)
1035 if (subVals.has(Arg.SEQID.getName()))
1037 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1039 else if (-1 < subVals.getIndex()
1040 && subVals.getIndex() < al.getSequences().size())
1042 seq = al.getSequenceAt(subVals.getIndex());
1045 if (seq == null && idAv != null)
1047 seq = al.findName(idAv.getValue());
1052 public AlignFrame[] getAlignFrames()
1054 AlignFrame[] afs = null;
1057 afs = (AlignFrame[]) afMap.values().toArray();
1063 public List<StructureViewer> getStructureViewers()
1065 List<StructureViewer> svs = null;
1068 for (List<StructureViewer> svList : svMap.values())
1072 svs = new ArrayList<>();
1080 private void addInfo(String errorMessage)
1082 Console.info(errorMessage);
1083 errors.add(errorMessage);
1086 private void addWarn(String errorMessage)
1088 Console.warn(errorMessage);
1089 errors.add(errorMessage);
1092 private void addError(String errorMessage)
1094 addError(errorMessage, null);
1097 private void addError(String errorMessage, Exception e)
1099 Console.error(errorMessage, e);
1100 errors.add(errorMessage);
1103 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1104 SubVals subVal, boolean includeBackups, String filename,
1105 String adjective, Boolean isError)
1107 File file = new File(filename);
1109 boolean overwrite = ArgParser.getFromSubValArgOrPref(avm, Arg.OVERWRITE,
1110 subVal, null, "OVERWRITE_OUTPUT", false);
1111 boolean stdout = false;
1112 boolean backups = false;
1115 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1116 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1117 // otherwise if headless assume false, if not headless use the user
1118 // preference with default true.
1119 backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS, subVal,
1120 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1121 !Platform.isHeadless());
1124 if (file.exists() && !(overwrite || backups || stdout))
1126 addWarn("Won't overwrite file '" + filename + "' without "
1127 + Arg.OVERWRITE.argString()
1128 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1133 boolean mkdirs = ArgParser.getFromSubValArgOrPref(avm, Arg.MKDIRS,
1134 subVal, null, "MKDIRS_OUTPUT", false);
1136 if (!FileUtils.checkParentDir(file, mkdirs))
1138 addError("Directory '"
1139 + FileUtils.getParentDir(file).getAbsolutePath()
1140 + "' does not exist for " + adjective + " file '" + filename
1142 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1150 public List<String> getErrors()
1155 public String errorsToString()
1157 StringBuilder sb = new StringBuilder();
1158 for (String error : errors)
1160 if (sb.length() > 0)
1162 sb.append("- " + error);
1164 return sb.toString();