5 import java.io.IOException;
6 import java.net.URISyntaxException;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Locale;
16 import javax.swing.SwingUtilities;
18 import jalview.analysis.AlignmentUtils;
19 import jalview.api.structures.JalviewStructureDisplayI;
20 import jalview.bin.Jalview.ExitCode;
21 import jalview.bin.argparser.Arg;
22 import jalview.bin.argparser.ArgParser;
23 import jalview.bin.argparser.ArgValue;
24 import jalview.bin.argparser.ArgValuesMap;
25 import jalview.bin.argparser.SubVals;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceI;
28 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.AlignmentPanel;
31 import jalview.gui.AppJmol;
32 import jalview.gui.Desktop;
33 import jalview.gui.Preferences;
34 import jalview.gui.StructureChooser;
35 import jalview.gui.StructureViewer;
36 import jalview.gui.StructureViewer.ViewerType;
37 import jalview.io.AppletFormatAdapter;
38 import jalview.io.BackupFiles;
39 import jalview.io.BioJsHTMLOutput;
40 import jalview.io.DataSourceType;
41 import jalview.io.FileFormat;
42 import jalview.io.FileFormatException;
43 import jalview.io.FileFormatI;
44 import jalview.io.FileFormats;
45 import jalview.io.FileLoader;
46 import jalview.io.HtmlSvgOutput;
47 import jalview.io.IdentifyFile;
48 import jalview.io.NewickFile;
49 import jalview.io.exceptions.ImageOutputException;
50 import jalview.schemes.ColourSchemeI;
51 import jalview.schemes.ColourSchemeProperty;
52 import jalview.structure.StructureCommandI;
53 import jalview.structure.StructureImportSettings.TFType;
54 import jalview.structure.StructureSelectionManager;
55 import jalview.util.ColorUtils;
56 import jalview.util.FileUtils;
57 import jalview.util.HttpUtils;
58 import jalview.util.IdUtils;
59 import jalview.util.IdUtils.IdType;
60 import jalview.util.ImageMaker;
61 import jalview.util.ImageMaker.TYPE;
62 import jalview.util.MessageManager;
63 import jalview.util.Platform;
64 import jalview.util.StringUtils;
65 import jalview.util.imagemaker.BitmapImageSizing;
71 private boolean headless;
73 private ArgParser argParser;
75 private Map<String, AlignFrame> afMap;
77 private Map<String, List<StructureViewer>> svMap;
79 private boolean commandArgsProvided = false;
81 private boolean argsWereParsed = false;
83 private List<String> errors = new ArrayList<>();
85 public Commands(ArgParser argparser, boolean headless)
87 this(Desktop.instance, argparser, headless);
90 public Commands(Desktop d, ArgParser argparser, boolean h)
92 argParser = argparser;
95 afMap = new HashMap<>();
98 protected boolean processArgs()
100 if (argParser == null)
105 boolean theseArgsWereParsed = false;
107 if (argParser != null && argParser.getLinkedIds() != null)
109 for (String id : argParser.getLinkedIds())
111 ArgValuesMap avm = argParser.getLinkedArgs(id);
112 theseArgsWereParsed = true;
113 boolean processLinkedOkay = processLinked(id);
114 theseArgsWereParsed &= processLinkedOkay;
116 processGroovyScript(id);
118 // wait around until alignFrame isn't busy
119 AlignFrame af = afMap.get(id);
120 while (af != null && af.getViewport().isCalcInProgress())
125 } catch (Exception q)
131 theseArgsWereParsed &= processImages(id);
133 if (processLinkedOkay)
135 theseArgsWereParsed &= processOutput(id);
139 if (avm.getBoolean(Arg.CLOSE))
144 af.closeMenuItem_actionPerformed(true);
152 // report errors - if any
153 String errorsRaised = errorsToString();
154 if (errorsRaised.trim().length() > 0)
157 "The following errors and warnings occurred whilst processing files:\n"
160 // gui errors reported in Jalview
162 if (argParser.getBoolean(Arg.QUIT))
164 Jalview.getInstance().exit(
165 "Exiting due to " + Arg.QUIT.argString() + " argument.",
169 // carry on with jalview.bin.Jalview
170 argsWereParsed = theseArgsWereParsed;
171 return argsWereParsed;
174 public boolean commandArgsProvided()
176 return commandArgsProvided;
179 public boolean argsWereParsed()
181 return argsWereParsed;
184 protected boolean processLinked(String id)
186 boolean theseArgsWereParsed = false;
187 ArgValuesMap avm = argParser.getLinkedArgs(id);
193 Boolean isError = Boolean.valueOf(false);
195 // set wrap scope here so it can be applied after structures are opened
196 boolean wrap = false;
198 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
200 commandArgsProvided = true;
203 boolean first = true;
204 boolean progressBarSet = false;
206 // Combine the APPEND and OPEN files into one list, along with whether it
207 // was APPEND or OPEN
208 List<ArgValue> openAvList = new ArrayList<>();
209 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
210 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
211 // sort avlist based on av.getArgIndex()
212 Collections.sort(openAvList);
213 for (ArgValue av : openAvList)
216 SubVals sv = av.getSubVals();
217 String openFile = av.getValue();
218 if (openFile == null)
221 theseArgsWereParsed = true;
225 if (!headless && desktop != null)
227 desktop.setProgressBar(
228 MessageManager.getString(
229 "status.processing_commandline_args"),
230 progress = IdUtils.newId(IdType.PROGRESS));
231 progressBarSet = true;
235 if (!Platform.isJS())
237 * ignore in JavaScript -- can't just file existence - could load it?
242 if (!HttpUtils.startsWithHttpOrHttps(openFile))
244 if (!(new File(openFile)).exists())
246 addError("Can't find file '" + openFile + "'");
253 DataSourceType protocol = AppletFormatAdapter
254 .checkProtocol(openFile);
256 FileFormatI format = null;
259 format = new IdentifyFile().identify(openFile, protocol);
260 } catch (FileFormatException e1)
262 addError("Unknown file format for '" + openFile + "'");
268 // When to open a new AlignFrame
269 if (af == null || "true".equals(av.getSubVal("new"))
270 || a == Arg.OPEN || format == FileFormat.Jalview)
274 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
279 "Opening '" + openFile + "' in new alignment frame");
280 FileLoader fileLoader = new FileLoader(!headless);
281 boolean xception = false;
284 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
286 } catch (Throwable thr)
289 addError("Couldn't open '" + openFile + "' as " + format + " "
290 + thr.getLocalizedMessage()
291 + " (Enable debug for full stack trace)");
293 Console.debug("Exception when opening '" + openFile + "'", thr);
296 if (af == null && !xception)
298 addInfo("Ignoring '" + openFile
299 + "' - no alignment data found.");
305 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
306 null, "DEFAULT_COLOUR_PROT", "");
307 this.colourAlignFrame(af, colour);
309 // Change alignment frame title
310 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
315 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
319 String featuresfile = avm.getValueFromSubValOrArg(av,
321 if (featuresfile != null)
323 af.parseFeaturesFile(featuresfile,
324 AppletFormatAdapter.checkProtocol(featuresfile));
325 Jalview.testoutput(argParser, Arg.FEATURES,
326 "examples/testdata/plantfdx.features", featuresfile);
329 // Add annotations from file
330 String annotationsfile = avm.getValueFromSubValOrArg(av,
331 Arg.ANNOTATIONS, sv);
332 if (annotationsfile != null)
334 af.loadJalviewDataFile(annotationsfile, null, null, null);
335 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
336 "examples/testdata/plantfdx.annotations",
340 // Set or clear the sortbytree flag
341 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
345 af.getViewport().setSortByTree(true);
346 Jalview.testoutput(argParser, Arg.SORTBYTREE);
349 // Load tree from file
350 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
351 if (treefile != null)
355 NewickFile nf = new NewickFile(treefile,
356 AppletFormatAdapter.checkProtocol(treefile));
357 af.getViewport().setCurrentTree(
358 af.showNewickTree(nf, treefile).getTree());
359 Jalview.testoutput(argParser, Arg.TREE,
360 "examples/testdata/uniref50_test_tree", treefile);
361 } catch (IOException e)
363 addError("Couldn't add tree " + treefile, e);
368 // Show secondary structure annotations?
369 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
370 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
371 "STRUCT_FROM_PDB", true);
373 // Show sequence annotations?
374 boolean showAnnotations = avm.getFromSubValArgOrPref(
375 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
376 "SHOW_ANNOTATIONS", true);
378 boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
379 final AlignFrame _af = af;
380 // many of jalview's format/layout methods are only thread safe on the
381 // swingworker thread.
382 // all these methods should be on the alignViewController so it can
383 // coordinate such details
386 SwingUtilities.invokeAndWait(new Runnable()
391 _af.setAnnotationsVisibility(showSSAnnotations, true,
394 _af.setAnnotationsVisibility(showAnnotations, false, true);
396 // show temperature factor annotations?
399 // do this better (annotation types?)
400 List<String> hideThese = new ArrayList<>();
401 hideThese.add("Temperature Factor");
402 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
403 AlignmentUtils.showOrHideSequenceAnnotations(
404 _af.getCurrentView().getAlignment(), hideThese,
409 } catch (Exception x)
412 "Unexpected exception adjusting annotation row visibility.",
416 // wrap alignment? do this last for formatting reasons
417 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
418 "WRAP_ALIGNMENT", false);
419 // af.setWrapFormat(wrap) is applied after structures are opened for
420 // annotation reasons
422 // store the AlignFrame for this id
425 // is it its own structure file?
426 if (format.isStructureFile())
428 StructureSelectionManager ssm = StructureSelectionManager
429 .getStructureSelectionManager(Desktop.instance);
430 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
431 ssm.computeMapping(false, new SequenceI[] { seq }, null,
432 openFile, DataSourceType.FILE, null, null, null, false);
438 "Opening '" + openFile + "' in existing alignment frame");
439 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
441 : DataSourceType.FILE;
442 FileLoader fileLoader = new FileLoader(!headless);
443 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
447 Console.debug("Command " + Arg.APPEND + " executed successfully!");
450 if (first) // first=true means nothing opened
454 Jalview.exit("Could not open any files in headless mode",
459 Console.info("No more files to open");
462 if (progressBarSet && desktop != null)
464 desktop.setProgressBar(null, progress);
468 // open the structure (from same PDB file or given PDBfile)
469 if (!avm.getBoolean(Arg.NOSTRUCTURE))
471 AlignFrame af = afMap.get(id);
472 if (avm.containsArg(Arg.STRUCTURE))
474 commandArgsProvided = true;
475 for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
477 argParser.setStructureFilename(null);
478 String val = av.getValue();
479 SubVals subVals = av.getSubVals();
480 int argIndex = av.getArgIndex();
481 SequenceI seq = getSpecifiedSequence(af, avm, av);
484 // Could not find sequence from subId, let's assume the first
485 // sequence in the alignframe
486 AlignmentI al = af.getCurrentView().getAlignment();
487 seq = al.getSequenceAt(0);
492 addWarn("Could not find sequence for argument "
493 + Arg.STRUCTURE.argString() + "=" + val);
496 String structureFilename = null;
497 File structureFile = null;
498 if (subVals.getContent() != null
499 && subVals.getContent().length() != 0)
501 structureFilename = subVals.getContent();
502 Console.debug("Using structure file (from argument) '"
503 + structureFilename + "'");
504 structureFile = new File(structureFilename);
506 /* THIS DOESN'T WORK */
507 else if (seq.getAllPDBEntries() != null
508 && seq.getAllPDBEntries().size() > 0)
510 structureFile = new File(
511 seq.getAllPDBEntries().elementAt(0).getFile());
512 if (structureFile != null)
514 Console.debug("Using structure file (from sequence) '"
515 + structureFile.getAbsolutePath() + "'");
517 structureFilename = structureFile.getAbsolutePath();
520 if (structureFilename == null || structureFile == null)
522 addWarn("Not provided structure file with '" + val + "'");
526 if (!structureFile.exists())
528 addWarn("Structure file '" + structureFile.getAbsoluteFile()
533 Console.debug("Using structure file "
534 + structureFile.getAbsolutePath());
536 argParser.setStructureFilename(structureFilename);
538 // open structure view
539 AlignmentPanel ap = af.alignPanel;
542 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
543 StructureViewer.ViewerType.JMOL.toString());
546 String structureFilepath = structureFile.getAbsolutePath();
548 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
549 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
550 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
551 subVals, null, null, null);
552 if (paeFilepath != null)
554 File paeFile = new File(paeFilepath);
558 paeFilepath = paeFile.getCanonicalPath();
559 } catch (IOException e)
561 paeFilepath = paeFile.getAbsolutePath();
562 addWarn("Problem with the PAE file path: '"
563 + paeFile.getPath() + "'");
567 // showing annotations from structure file or not
568 boolean ssFromStructure = avm.getFromSubValArgOrPref(
569 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
572 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
573 // reference annotations
574 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
575 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
576 subVals, null, null, null);
577 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
578 subVals, null, "ADD_TEMPFACT_ANN", false, true);
579 TFType tft = notempfac ? null : TFType.DEFAULT;
580 if (tftString != null && !notempfac)
582 // get kind of temperature factor annotation
585 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
586 Console.debug("Obtained Temperature Factor type of '" + tft
587 + "' for structure '" + structureFilepath + "'");
588 } catch (IllegalArgumentException e)
590 // Just an error message!
591 StringBuilder sb = new StringBuilder().append("Cannot set ")
592 .append(Arg.TEMPFAC.argString()).append(" to '")
594 .append("', ignoring. Valid values are: ");
595 Iterator<TFType> it = Arrays.stream(TFType.values())
599 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
603 addWarn(sb.toString());
607 String sViewerName = avm.getFromSubValArgOrPref(
608 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
609 subVals, null, null, "jmol");
610 ViewerType viewerType = ViewerType.getFromString(sViewerName);
612 // TODO use ssFromStructure
613 StructureViewer structureViewer = StructureChooser
614 .openStructureFileForSequence(null, null, ap, seq, false,
615 structureFilepath, tft, paeFilepath, false,
616 ssFromStructure, false, viewerType);
618 if (structureViewer == null)
620 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
622 addError("Failed to import and open structure view for file '"
623 + structureFile + "'.");
630 while (structureViewer.isBusy() && tries > 0)
633 if (structureViewer.isBusy())
637 "Waiting for viewer for " + structureFilepath);
640 if (tries == 0 && structureViewer.isBusy())
642 addWarn("Gave up waiting for structure viewer to load file '"
644 + "'. Something may have gone wrong.");
646 } catch (Exception x)
648 addError("Exception whilst waiting for structure viewer "
649 + structureFilepath, x);
653 // add StructureViewer to svMap list
656 svMap = new HashMap<>();
658 if (svMap.get(id) == null)
660 svMap.put(id, new ArrayList<>());
662 svMap.get(id).add(structureViewer);
665 "Successfully opened viewer for " + structureFilepath);
667 if (avm.containsArg(Arg.STRUCTUREIMAGE))
669 for (ArgValue structureImageArgValue : avm
670 .getArgValueList(Arg.STRUCTUREIMAGE))
672 String structureImageFilename = argParser.makeSubstitutions(
673 structureImageArgValue.getValue(), id, true);
674 if (structureViewer != null && structureImageFilename != null)
676 SubVals structureImageSubVals = null;
677 structureImageSubVals = structureImageArgValue.getSubVals();
678 File structureImageFile = new File(structureImageFilename);
679 String width = avm.getValueFromSubValOrArg(
680 structureImageArgValue, Arg.WIDTH,
681 structureImageSubVals);
682 String height = avm.getValueFromSubValOrArg(
683 structureImageArgValue, Arg.HEIGHT,
684 structureImageSubVals);
685 String scale = avm.getValueFromSubValOrArg(
686 structureImageArgValue, Arg.SCALE,
687 structureImageSubVals);
688 String renderer = avm.getValueFromSubValOrArg(
689 structureImageArgValue, Arg.TEXTRENDERER,
690 structureImageSubVals);
691 String typeS = avm.getValueFromSubValOrArg(
692 structureImageArgValue, Arg.TYPE,
693 structureImageSubVals);
694 if (typeS == null || typeS.length() == 0)
696 typeS = FileUtils.getExtension(structureImageFile);
701 imageType = Enum.valueOf(TYPE.class,
702 typeS.toUpperCase(Locale.ROOT));
703 } catch (IllegalArgumentException e)
705 addWarn("Do not know image format '" + typeS
707 imageType = TYPE.PNG;
709 BitmapImageSizing userBis = ImageMaker
710 .parseScaleWidthHeightStrings(scale, width, height);
713 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
714 if (viewerType != ViewerType.JMOL)
716 addWarn("Cannot export image for structure viewer "
717 + viewerType.name() + " yet");
722 // Apply the temporary colourscheme to the linked alignment
723 // TODO: enhance for multiple linked alignments.
725 String imageColour = avm.getValueFromSubValOrArg(
726 structureImageArgValue, Arg.IMAGECOLOUR,
727 structureImageSubVals);
728 ColourSchemeI originalColourScheme = this
729 .getColourScheme(af);
730 this.colourAlignFrame(af, imageColour);
733 // custom image background colour
735 String bgcolourstring = avm.getValueFromSubValOrArg(
736 structureImageArgValue, Arg.BGCOLOUR,
737 structureImageSubVals);
738 Color bgcolour = null;
739 if (bgcolourstring != null && bgcolourstring.length() > 0)
741 bgcolour = ColorUtils.parseColourString(bgcolourstring);
742 if (bgcolour == null)
745 "Background colour string '" + bgcolourstring
746 + "' not recognised -- using default");
750 JalviewStructureDisplayI sview = structureViewer
751 .getJalviewStructureDisplay();
753 File sessionToRestore = null;
755 List<StructureCommandI> extraCommands = new ArrayList<>();
757 if (extraCommands.size() > 0 || bgcolour != null)
761 sessionToRestore = sview.saveSession();
762 } catch (Throwable t)
765 "Unable to save temporary session file before custom structure view export operation.");
772 if (bgcolour != null)
774 sview.getBinding().setBackgroundColour(bgcolour);
777 sview.getBinding().executeCommands(extraCommands, false,
778 "Executing Custom Commands");
780 // and export the view as an image
781 boolean success = this.checksBeforeWritingToFile(avm,
782 subVals, false, structureImageFilename,
783 "structure image", isError);
789 Console.debug("Rendering image to " + structureImageFile);
791 // TODO - extend StructureViewer / Binding with makePDBImage so
792 // we can do this with every viewer
797 // We don't expect class cast exception
798 AppJmol jmol = (AppJmol) sview;
799 jmol.makePDBImage(structureImageFile, imageType, renderer,
801 Console.info("Exported structure image to "
802 + structureImageFile);
804 // RESTORE SESSION AFTER EXPORT IF NEED BE
805 if (sessionToRestore != null)
808 "Restoring session from " + sessionToRestore);
810 sview.getBinding().restoreSession(
811 sessionToRestore.getAbsolutePath());
814 } catch (ImageOutputException ioexec)
817 "Unexpected error when restoring structure viewer session after custom view operations.");
824 this.colourAlignFrame(af, originalColourScheme);
825 } catch (Exception t)
828 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
835 argParser.setStructureFilename(null);
842 AlignFrame af = afMap.get(id);
845 af.setWrapFormat(wrap, true);
850 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
853 AlignFrame af = afMap.get(id);
854 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
855 .findAnnotation(PDBChain.class.getName().toString()))
857 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
858 af.alignPanel.av.getGlobalColourScheme(), 0);
859 acg.setSeqAssociated(true);
860 af.changeColour(acg);
861 Console.info("Changed colour " + acg.toString());
866 return theseArgsWereParsed && !isError;
869 protected void processGroovyScript(String id)
871 ArgValuesMap avm = argParser.getLinkedArgs(id);
872 AlignFrame af = afMap.get(id);
874 if (avm != null && !avm.containsArg(Arg.GROOVY))
882 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
885 if (avm.containsArg(Arg.GROOVY))
887 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
889 String groovyscript = groovyAv.getValue();
890 if (groovyscript != null)
892 // Execute the groovy script after we've done all the rendering stuff
893 // and before any images or figures are generated.
894 Console.info("Executing script " + groovyscript);
895 Jalview.getInstance().executeGroovyScript(groovyscript, af);
901 protected boolean processImages(String id)
903 ArgValuesMap avm = argParser.getLinkedArgs(id);
904 AlignFrame af = afMap.get(id);
906 if (avm != null && !avm.containsArg(Arg.IMAGE))
914 addWarn("Do not have an alignment window to create image from (id="
915 + id + "). Not proceeding.");
919 Boolean isError = Boolean.valueOf(false);
920 if (avm.containsArg(Arg.IMAGE))
922 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
924 String val = imageAv.getValue();
925 SubVals imageSubVals = imageAv.getSubVals();
926 String fileName = imageSubVals.getContent();
927 File file = new File(fileName);
928 String name = af.getName();
929 String renderer = avm.getValueFromSubValOrArg(imageAv,
930 Arg.TEXTRENDERER, imageSubVals);
931 if (renderer == null)
933 String type = "png"; // default
935 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
937 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
939 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
941 BitmapImageSizing userBis = ImageMaker
942 .parseScaleWidthHeightStrings(scale, width, height);
944 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
945 if (type == null && fileName != null)
947 for (String ext : new String[] { "svg", "png", "html", "eps" })
949 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
955 // for moment we disable JSON export
956 Cache.setPropsAreReadOnly(true);
957 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
959 String imageColour = avm.getValueFromSubValOrArg(imageAv,
960 Arg.IMAGECOLOUR, imageSubVals);
961 ColourSchemeI originalColourScheme = this.getColourScheme(af);
962 this.colourAlignFrame(af, imageColour);
964 Console.info("Writing " + file);
966 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
967 false, fileName, "image", isError);
979 Console.debug("Outputting type '" + type + "' to " + fileName);
980 af.createSVG(file, renderer);
984 Console.debug("Outputting type '" + type + "' to " + fileName);
985 af.createPNG(file, null, userBis);
989 Console.debug("Outputting type '" + type + "' to " + fileName);
990 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
991 htmlSVG.exportHTML(fileName, renderer);
996 "Outputting BioJS MSA Viwer HTML file: " + fileName);
999 BioJsHTMLOutput.refreshVersionInfo(
1000 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1001 } catch (URISyntaxException e)
1003 e.printStackTrace();
1005 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1006 bjs.exportHTML(fileName);
1010 Console.debug("Outputting EPS file: " + fileName);
1011 af.createEPS(file, renderer);
1015 Console.debug("Outputting ImageMap file: " + fileName);
1016 af.createImageMap(file, name);
1020 addWarn(Arg.IMAGE.argString() + " type '" + type
1021 + "' not known. Ignoring");
1024 } catch (Exception ioex)
1026 addError("Unexpected error during export to '" + fileName + "'",
1031 this.colourAlignFrame(af, originalColourScheme);
1037 protected boolean processOutput(String id)
1039 ArgValuesMap avm = argParser.getLinkedArgs(id);
1040 AlignFrame af = afMap.get(id);
1042 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1050 addWarn("Do not have an alignment window (id=" + id
1051 + "). Not proceeding.");
1055 Boolean isError = Boolean.valueOf(false);
1057 if (avm.containsArg(Arg.OUTPUT))
1059 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1061 String val = av.getValue();
1062 SubVals subVals = av.getSubVals();
1063 String fileName = subVals.getContent();
1064 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1065 File file = new File(fileName);
1067 String name = af.getName();
1068 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1070 FileFormats ffs = FileFormats.getInstance();
1071 List<String> validFormats = ffs.getWritableFormats(false);
1073 FileFormatI ff = null;
1074 if (format == null && fileName != null)
1076 FORMAT: for (String fname : validFormats)
1078 FileFormatI tff = ffs.forName(fname);
1079 String[] extensions = tff.getExtensions().split(",");
1080 for (String ext : extensions)
1082 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1085 format = ff.getName();
1091 if (ff == null && format != null)
1093 ff = ffs.forName(format);
1099 ff = FileFormat.Fasta;
1103 StringBuilder validSB = new StringBuilder();
1104 for (String f : validFormats)
1106 if (validSB.length() > 0)
1107 validSB.append(", ");
1109 FileFormatI tff = ffs.forName(f);
1110 validSB.append(" (");
1111 validSB.append(tff.getExtensions());
1112 validSB.append(")");
1115 addError("No valid format specified for "
1116 + Arg.OUTPUT.argString() + ". Valid formats are "
1117 + validSB.toString() + ".");
1122 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1123 fileName, ff.getName(), isError);
1129 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1130 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1131 !Platform.isHeadless());
1133 Console.info("Writing " + fileName);
1135 af.saveAlignment(fileName, ff, stdout, backups);
1136 if (af.isSaveAlignmentSuccessful())
1138 Console.debug("Written alignment '" + name + "' in "
1139 + ff.getName() + " format to '" + file + "'");
1143 addError("Error writing file '" + file + "' in " + ff.getName()
1154 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1157 SubVals subVals = av.getSubVals();
1158 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1159 SequenceI seq = null;
1160 if (subVals == null && idAv == null)
1162 if (af == null || af.getCurrentView() == null)
1166 AlignmentI al = af.getCurrentView().getAlignment();
1171 if (subVals != null)
1173 if (subVals.has(Arg.SEQID.getName()))
1175 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1177 else if (-1 < subVals.getIndex()
1178 && subVals.getIndex() < al.getSequences().size())
1180 seq = al.getSequenceAt(subVals.getIndex());
1183 if (seq == null && idAv != null)
1185 seq = al.findName(idAv.getValue());
1190 public AlignFrame[] getAlignFrames()
1192 AlignFrame[] afs = null;
1195 afs = (AlignFrame[]) afMap.values().toArray();
1201 public List<StructureViewer> getStructureViewers()
1203 List<StructureViewer> svs = null;
1206 for (List<StructureViewer> svList : svMap.values())
1210 svs = new ArrayList<>();
1218 private void colourAlignFrame(AlignFrame af, String colour)
1220 // use string "none" to remove colour scheme
1221 if (colour != null && "" != colour)
1223 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1224 af.getViewport(), af.getViewport().getAlignment(), colour);
1225 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1227 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1231 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1232 colourAlignFrame(af, cs);
1237 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1239 // Note that cs == null removes colour scheme from af
1240 af.changeColour(cs);
1243 private ColourSchemeI getColourScheme(AlignFrame af)
1245 return af.getViewport().getGlobalColourScheme();
1248 private void addInfo(String errorMessage)
1250 Console.info(errorMessage);
1251 errors.add(errorMessage);
1254 private void addWarn(String errorMessage)
1256 Console.warn(errorMessage);
1257 errors.add(errorMessage);
1260 private void addError(String errorMessage)
1262 addError(errorMessage, null);
1265 private void addError(String errorMessage, Exception e)
1267 Console.error(errorMessage, e);
1268 errors.add(errorMessage);
1271 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1272 SubVals subVal, boolean includeBackups, String filename,
1273 String adjective, Boolean isError)
1275 File file = new File(filename);
1277 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1278 null, "OVERWRITE_OUTPUT", false);
1279 boolean stdout = false;
1280 boolean backups = false;
1283 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1284 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1285 // otherwise if headless assume false, if not headless use the user
1286 // preference with default true.
1287 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1288 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1289 !Platform.isHeadless());
1292 if (file.exists() && !(overwrite || backups || stdout))
1294 addWarn("Won't overwrite file '" + filename + "' without "
1295 + Arg.OVERWRITE.argString()
1296 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1301 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1302 "MKDIRS_OUTPUT", false);
1304 if (!FileUtils.checkParentDir(file, mkdirs))
1306 addError("Directory '"
1307 + FileUtils.getParentDir(file).getAbsolutePath()
1308 + "' does not exist for " + adjective + " file '" + filename
1310 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1318 public List<String> getErrors()
1323 public String errorsToString()
1325 StringBuilder sb = new StringBuilder();
1326 for (String error : errors)
1328 if (sb.length() > 0)
1330 sb.append("- " + error);
1332 return sb.toString();