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.ImageMaker;
59 import jalview.util.ImageMaker.TYPE;
60 import jalview.util.MessageManager;
61 import jalview.util.Platform;
62 import jalview.util.StringUtils;
63 import jalview.util.imagemaker.BitmapImageSizing;
69 private boolean headless;
71 private ArgParser argParser;
73 private Map<String, AlignFrame> afMap;
75 private Map<String, List<StructureViewer>> svMap;
77 private boolean commandArgsProvided = false;
79 private boolean argsWereParsed = false;
81 private List<String> errors = new ArrayList<>();
83 public Commands(ArgParser argparser, boolean headless)
85 this(Desktop.instance, argparser, headless);
88 public Commands(Desktop d, ArgParser argparser, boolean h)
90 argParser = argparser;
93 afMap = new HashMap<>();
96 protected boolean processArgs()
98 if (argParser == null)
103 boolean theseArgsWereParsed = false;
105 if (argParser != null && argParser.getLinkedIds() != null)
107 for (String id : argParser.getLinkedIds())
109 ArgValuesMap avm = argParser.getLinkedArgs(id);
110 theseArgsWereParsed = true;
111 boolean processLinkedOkay = processLinked(id);
112 theseArgsWereParsed &= processLinkedOkay;
114 processGroovyScript(id);
116 // wait around until alignFrame isn't busy
117 AlignFrame af = afMap.get(id);
118 while (af != null && af.getViewport().isCalcInProgress())
123 } catch (Exception q)
129 theseArgsWereParsed &= processImages(id);
131 if (processLinkedOkay)
133 theseArgsWereParsed &= processOutput(id);
137 if (avm.getBoolean(Arg.CLOSE))
142 af.closeMenuItem_actionPerformed(true);
150 // report errors - if any
151 String errorsRaised = errorsToString();
152 if (errorsRaised.trim().length() > 0)
155 "The following errors and warnings occurred whilst processing files:\n"
158 // gui errors reported in Jalview
160 if (argParser.getBoolean(Arg.QUIT))
162 Jalview.getInstance().exit(
163 "Exiting due to " + Arg.QUIT.argString() + " argument.",
167 // carry on with jalview.bin.Jalview
168 argsWereParsed = theseArgsWereParsed;
169 return argsWereParsed;
172 public boolean commandArgsProvided()
174 return commandArgsProvided;
177 public boolean argsWereParsed()
179 return argsWereParsed;
182 protected boolean processLinked(String id)
184 boolean theseArgsWereParsed = false;
185 ArgValuesMap avm = argParser.getLinkedArgs(id);
191 Boolean isError = Boolean.valueOf(false);
193 // set wrap scope here so it can be applied after structures are opened
194 boolean wrap = false;
196 if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
198 commandArgsProvided = true;
199 final long progress = System.currentTimeMillis();
201 boolean first = true;
202 boolean progressBarSet = false;
204 // Combine the APPEND and OPEN files into one list, along with whether it
205 // was APPEND or OPEN
206 List<ArgValue> openAvList = new ArrayList<>();
207 openAvList.addAll(avm.getArgValueList(Arg.OPEN));
208 openAvList.addAll(avm.getArgValueList(Arg.APPEND));
209 // sort avlist based on av.getArgIndex()
210 Collections.sort(openAvList);
211 for (ArgValue av : openAvList)
214 SubVals sv = av.getSubVals();
215 String openFile = av.getValue();
216 if (openFile == null)
219 theseArgsWereParsed = true;
223 if (!headless && desktop != null)
225 SwingUtilities.invokeLater(new Runnable()
230 desktop.setProgressBar(
231 MessageManager.getString(
232 "status.processing_commandline_args"),
237 progressBarSet = true;
241 if (!Platform.isJS())
243 * ignore in JavaScript -- can't just file existence - could load it?
248 if (!HttpUtils.startsWithHttpOrHttps(openFile))
250 if (!(new File(openFile)).exists())
252 addError("Can't find file '" + openFile + "'");
259 DataSourceType protocol = AppletFormatAdapter
260 .checkProtocol(openFile);
262 FileFormatI format = null;
265 format = new IdentifyFile().identify(openFile, protocol);
266 } catch (FileFormatException e1)
268 addError("Unknown file format for '" + openFile + "'");
274 // When to open a new AlignFrame
275 if (af == null || "true".equals(av.getSubVal("new"))
276 || a == Arg.OPEN || format == FileFormat.Jalview)
280 Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
285 "Opening '" + openFile + "' in new alignment frame");
286 FileLoader fileLoader = new FileLoader(!headless);
287 boolean xception = false;
290 af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
292 } catch (Throwable thr)
295 addError("Couldn't open '" + openFile + "' as " + format + " "
296 + thr.getLocalizedMessage()
297 + " (Enable debug for full stack trace)");
299 Console.debug("Exception when opening '" + openFile + "'", thr);
302 if (af == null && !xception)
304 addInfo("Ignoring '" + openFile
305 + "' - no alignment data found.");
311 String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
312 null, "DEFAULT_COLOUR_PROT", "");
313 this.colourAlignFrame(af, colour);
315 // Change alignment frame title
316 String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
321 Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
325 String featuresfile = avm.getValueFromSubValOrArg(av,
327 if (featuresfile != null)
329 af.parseFeaturesFile(featuresfile,
330 AppletFormatAdapter.checkProtocol(featuresfile));
331 Jalview.testoutput(argParser, Arg.FEATURES,
332 "examples/testdata/plantfdx.features", featuresfile);
335 // Add annotations from file
336 String annotationsfile = avm.getValueFromSubValOrArg(av,
337 Arg.ANNOTATIONS, sv);
338 if (annotationsfile != null)
340 af.loadJalviewDataFile(annotationsfile, null, null, null);
341 Jalview.testoutput(argParser, Arg.ANNOTATIONS,
342 "examples/testdata/plantfdx.annotations",
346 // Set or clear the sortbytree flag
347 boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
351 af.getViewport().setSortByTree(true);
352 Jalview.testoutput(argParser, Arg.SORTBYTREE);
355 // Load tree from file
356 String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
357 if (treefile != null)
361 NewickFile nf = new NewickFile(treefile,
362 AppletFormatAdapter.checkProtocol(treefile));
363 af.getViewport().setCurrentTree(
364 af.showNewickTree(nf, treefile).getTree());
365 Jalview.testoutput(argParser, Arg.TREE,
366 "examples/testdata/uniref50_test_tree", treefile);
367 } catch (IOException e)
369 addError("Couldn't add tree " + treefile, e);
374 // Show secondary structure annotations?
375 boolean showSSAnnotations = avm.getFromSubValArgOrPref(
376 Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
377 "STRUCT_FROM_PDB", true);
379 // Show sequence annotations?
380 boolean showAnnotations = avm.getFromSubValArgOrPref(
381 Arg.SHOWANNOTATIONS, av.getSubVals(), null,
382 "SHOW_ANNOTATIONS", true);
384 boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
385 final AlignFrame _af = af;
386 // many of jalview's format/layout methods are only thread safe on the
387 // swingworker thread.
388 // all these methods should be on the alignViewController so it can
389 // coordinate such details
392 SwingUtilities.invokeAndWait(new Runnable()
398 _af.setAnnotationsVisibility(showSSAnnotations, true,
401 _af.setAnnotationsVisibility(showAnnotations, false, true);
403 // show temperature factor annotations?
406 // do this better (annotation types?)
407 List<String> hideThese = new ArrayList<>();
408 hideThese.add("Temperature Factor");
409 hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
410 AlignmentUtils.showOrHideSequenceAnnotations(
411 _af.getCurrentView().getAlignment(), hideThese,
416 } catch (Exception x)
419 "Unexpected exception adjusting annotation row visibility.",
423 // wrap alignment? do this last for formatting reasons
424 wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
425 "WRAP_ALIGNMENT", false);
426 // af.setWrapFormat(wrap) is applied after structures are opened for
427 // annotation reasons
429 // store the AlignFrame for this id
432 // is it its own structure file?
433 if (format.isStructureFile())
435 StructureSelectionManager ssm = StructureSelectionManager
436 .getStructureSelectionManager(Desktop.instance);
437 SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
438 ssm.computeMapping(false, new SequenceI[] { seq }, null,
439 openFile, DataSourceType.FILE, null, null, null, false);
445 "Opening '" + openFile + "' in existing alignment frame");
447 DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
449 : DataSourceType.FILE;
451 FileLoader fileLoader = new FileLoader(!headless);
452 fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
456 Console.debug("Command " + Arg.APPEND + " executed successfully!");
459 if (first) // first=true means nothing opened
463 Jalview.exit("Could not open any files in headless mode",
468 Console.info("No more files to open");
471 if (progressBarSet && desktop != null)
472 desktop.setProgressBar(null, progress);
476 // open the structure (from same PDB file or given PDBfile)
477 if (!avm.getBoolean(Arg.NOSTRUCTURE))
480 AlignFrame af = afMap.get(id);
481 if (avm.containsArg(Arg.STRUCTURE))
483 commandArgsProvided = true;
486 ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
488 argParser.setStructureFilename(null);
489 String val = av.getValue();
490 SubVals subVals = av.getSubVals();
491 int argIndex = av.getArgIndex();
492 SequenceI seq = getSpecifiedSequence(af, avm, av);
495 // Could not find sequence from subId, let's assume the first
496 // sequence in the alignframe
497 AlignmentI al = af.getCurrentView().getAlignment();
498 seq = al.getSequenceAt(0);
503 addWarn("Could not find sequence for argument "
504 + Arg.STRUCTURE.argString() + "=" + val);
507 String structureFilename = null;
508 File structureFile = null;
509 if (subVals.getContent() != null
510 && subVals.getContent().length() != 0)
512 structureFilename = subVals.getContent();
513 Console.debug("Using structure file (from argument) '"
514 + structureFilename + "'");
515 structureFile = new File(structureFilename);
517 /* THIS DOESN'T WORK */
518 else if (seq.getAllPDBEntries() != null
519 && seq.getAllPDBEntries().size() > 0)
521 structureFile = new File(
522 seq.getAllPDBEntries().elementAt(0).getFile());
523 if (structureFile != null)
525 Console.debug("Using structure file (from sequence) '"
526 + structureFile.getAbsolutePath() + "'");
528 structureFilename = structureFile.getAbsolutePath();
531 if (structureFilename == null || structureFile == null)
533 addWarn("Not provided structure file with '" + val + "'");
537 if (!structureFile.exists())
539 addWarn("Structure file '" + structureFile.getAbsoluteFile()
544 Console.debug("Using structure file "
545 + structureFile.getAbsolutePath());
547 argParser.setStructureFilename(structureFilename);
549 // open structure view
550 AlignmentPanel ap = af.alignPanel;
553 Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
554 StructureViewer.ViewerType.JMOL.toString());
557 String structureFilepath = structureFile.getAbsolutePath();
559 // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
560 String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
561 argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
562 subVals, null, null, null);
563 if (paeFilepath != null)
565 File paeFile = new File(paeFilepath);
569 paeFilepath = paeFile.getCanonicalPath();
570 } catch (IOException e)
572 paeFilepath = paeFile.getAbsolutePath();
573 addWarn("Problem with the PAE file path: '"
574 + paeFile.getPath() + "'");
578 // showing annotations from structure file or not
579 boolean ssFromStructure = avm.getFromSubValArgOrPref(
580 Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
583 // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
584 // reference annotations
585 String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
586 argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
587 subVals, null, null, null);
588 boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
589 subVals, null, "ADD_TEMPFACT_ANN", false, true);
590 TFType tft = notempfac ? null : TFType.DEFAULT;
591 if (tftString != null && !notempfac)
593 // get kind of temperature factor annotation
596 tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
597 Console.debug("Obtained Temperature Factor type of '" + tft
598 + "' for structure '" + structureFilepath + "'");
599 } catch (IllegalArgumentException e)
601 // Just an error message!
602 StringBuilder sb = new StringBuilder().append("Cannot set ")
603 .append(Arg.TEMPFAC.argString()).append(" to '")
605 .append("', ignoring. Valid values are: ");
606 Iterator<TFType> it = Arrays.stream(TFType.values())
610 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
614 addWarn(sb.toString());
618 String sViewerName = avm.getFromSubValArgOrPref(
619 Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
620 subVals, null, null, "jmol");
621 ViewerType viewerType = ViewerType.getFromString(sViewerName);
623 // TODO use ssFromStructure
624 StructureViewer structureViewer = StructureChooser
625 .openStructureFileForSequence(null, null, ap, seq, false,
626 structureFilepath, tft, paeFilepath, false,
627 ssFromStructure, false, viewerType);
629 if (structureViewer == null)
631 if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
633 addError("Failed to import and open structure view for file '"
634 + structureFile + "'.");
641 while (structureViewer.isBusy() && tries > 0)
644 if (structureViewer.isBusy())
648 "Waiting for viewer for " + structureFilepath);
651 if (tries == 0 && structureViewer.isBusy())
653 addWarn("Gave up waiting for structure viewer to load file '"
655 + "'. Something may have gone wrong.");
657 } catch (Exception x)
659 addError("Exception whilst waiting for structure viewer "
660 + structureFilepath, x);
664 // add StructureViewer to svMap list
667 svMap = new HashMap<>();
669 if (svMap.get(id) == null)
671 svMap.put(id, new ArrayList<>());
673 svMap.get(id).add(structureViewer);
676 "Successfully opened viewer for " + structureFilepath);
678 if (avm.containsArg(Arg.STRUCTUREIMAGE))
680 for (ArgValue structureImageArgValue : avm
681 .getArgValueList(Arg.STRUCTUREIMAGE))
683 String structureImageFilename = argParser.makeSubstitutions(
684 structureImageArgValue.getValue(), id, true);
685 if (structureViewer != null && structureImageFilename != null)
687 SubVals structureImageSubVals = null;
688 structureImageSubVals = structureImageArgValue.getSubVals();
689 File structureImageFile = new File(structureImageFilename);
690 String width = avm.getValueFromSubValOrArg(
691 structureImageArgValue, Arg.WIDTH,
692 structureImageSubVals);
693 String height = avm.getValueFromSubValOrArg(
694 structureImageArgValue, Arg.HEIGHT,
695 structureImageSubVals);
696 String scale = avm.getValueFromSubValOrArg(
697 structureImageArgValue, Arg.SCALE,
698 structureImageSubVals);
699 String renderer = avm.getValueFromSubValOrArg(
700 structureImageArgValue, Arg.TEXTRENDERER,
701 structureImageSubVals);
702 String typeS = avm.getValueFromSubValOrArg(
703 structureImageArgValue, Arg.TYPE,
704 structureImageSubVals);
705 if (typeS == null || typeS.length() == 0)
707 typeS = FileUtils.getExtension(structureImageFile);
712 imageType = Enum.valueOf(TYPE.class,
713 typeS.toUpperCase(Locale.ROOT));
714 } catch (IllegalArgumentException e)
716 addWarn("Do not know image format '" + typeS
718 imageType = TYPE.PNG;
720 BitmapImageSizing userBis = ImageMaker
721 .parseScaleWidthHeightStrings(scale, width, height);
724 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
725 if (viewerType != ViewerType.JMOL)
727 addWarn("Cannot export image for structure viewer "
728 + viewerType.name() + " yet");
733 // Apply the temporary colourscheme to the linked alignment
734 // TODO: enhance for multiple linked alignments.
736 String imageColour = avm.getValueFromSubValOrArg(
737 structureImageArgValue, Arg.IMAGECOLOUR,
738 structureImageSubVals);
739 ColourSchemeI originalColourScheme = this
740 .getColourScheme(af);
741 this.colourAlignFrame(af, imageColour);
744 // custom image background colour
746 String bgcolourstring = avm.getValueFromSubValOrArg(
747 structureImageArgValue, Arg.BGCOLOUR,
748 structureImageSubVals);
749 Color bgcolour = null;
750 if (bgcolourstring != null && bgcolourstring.length() > 0)
752 bgcolour = ColorUtils.parseColourString(bgcolourstring);
753 if (bgcolour == null)
756 "Background colour string '" + bgcolourstring
757 + "' not recognised -- using default");
761 JalviewStructureDisplayI sview = structureViewer
762 .getJalviewStructureDisplay();
764 File sessionToRestore = null;
766 List<StructureCommandI> extraCommands = new ArrayList<>();
768 if (extraCommands.size() > 0 || bgcolour != null)
772 sessionToRestore = sview.saveSession();
773 } catch (Throwable t)
776 "Unable to save temporary session file before custom structure view export operation.");
783 if (bgcolour != null)
785 sview.getBinding().setBackgroundColour(bgcolour);
788 sview.getBinding().executeCommands(extraCommands, false,
789 "Executing Custom Commands");
791 // and export the view as an image
792 boolean success = this.checksBeforeWritingToFile(avm,
793 subVals, false, structureImageFilename,
794 "structure image", isError);
800 Console.debug("Rendering image to " + structureImageFile);
802 // TODO - extend StructureViewer / Binding with makePDBImage so
803 // we can do this with every viewer
808 // We don't expect class cast exception
809 AppJmol jmol = (AppJmol) sview;
810 jmol.makePDBImage(structureImageFile, imageType, renderer,
812 Console.info("Exported structure image to "
813 + structureImageFile);
815 // RESTORE SESSION AFTER EXPORT IF NEED BE
816 if (sessionToRestore != null)
819 "Restoring session from " + sessionToRestore);
821 sview.getBinding().restoreSession(
822 sessionToRestore.getAbsolutePath());
825 } catch (ImageOutputException ioexec)
828 "Unexpected error when restoring structure viewer session after custom view operations.");
835 this.colourAlignFrame(af, originalColourScheme);
836 } catch (Exception t)
839 "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
846 argParser.setStructureFilename(null);
854 AlignFrame af = afMap.get(id);
857 af.setWrapFormat(wrap, true);
862 boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
865 AlignFrame af = afMap.get(id);
866 for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
867 .findAnnotation(PDBChain.class.getName().toString()))
869 AnnotationColourGradient acg = new AnnotationColourGradient(aa,
870 af.alignPanel.av.getGlobalColourScheme(), 0);
871 acg.setSeqAssociated(true);
872 af.changeColour(acg);
873 Console.info("Changed colour " + acg.toString());
878 return theseArgsWereParsed && !isError;
881 protected void processGroovyScript(String id)
883 ArgValuesMap avm = argParser.getLinkedArgs(id);
884 AlignFrame af = afMap.get(id);
886 if (avm != null && !avm.containsArg(Arg.GROOVY))
894 addWarn("Groovy script does not have an alignment window. Proceeding with caution!");
897 if (avm.containsArg(Arg.GROOVY))
899 for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
901 String groovyscript = groovyAv.getValue();
902 if (groovyscript != null)
904 // Execute the groovy script after we've done all the rendering stuff
905 // and before any images or figures are generated.
906 Console.info("Executing script " + groovyscript);
907 Jalview.getInstance().executeGroovyScript(groovyscript, af);
913 protected boolean processImages(String id)
915 ArgValuesMap avm = argParser.getLinkedArgs(id);
916 AlignFrame af = afMap.get(id);
918 if (avm != null && !avm.containsArg(Arg.IMAGE))
926 addWarn("Do not have an alignment window to create image from (id="
927 + id + "). Not proceeding.");
931 Boolean isError = Boolean.valueOf(false);
932 if (avm.containsArg(Arg.IMAGE))
934 for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
936 String val = imageAv.getValue();
937 SubVals imageSubVals = imageAv.getSubVals();
938 String fileName = imageSubVals.getContent();
939 File file = new File(fileName);
940 String name = af.getName();
941 String renderer = avm.getValueFromSubValOrArg(imageAv,
942 Arg.TEXTRENDERER, imageSubVals);
943 if (renderer == null)
945 String type = "png"; // default
947 String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
949 String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
951 String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
953 BitmapImageSizing userBis = ImageMaker
954 .parseScaleWidthHeightStrings(scale, width, height);
956 type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
957 if (type == null && fileName != null)
959 for (String ext : new String[] { "svg", "png", "html", "eps" })
961 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
967 // for moment we disable JSON export
968 Cache.setPropsAreReadOnly(true);
969 Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
971 String imageColour = avm.getValueFromSubValOrArg(imageAv,
972 Arg.IMAGECOLOUR, imageSubVals);
973 ColourSchemeI originalColourScheme = this.getColourScheme(af);
974 this.colourAlignFrame(af, imageColour);
976 Console.info("Writing " + file);
978 boolean success = checksBeforeWritingToFile(avm, imageSubVals,
979 false, fileName, "image", isError);
991 Console.debug("Outputting type '" + type + "' to " + fileName);
992 af.createSVG(file, renderer);
996 Console.debug("Outputting type '" + type + "' to " + fileName);
997 af.createPNG(file, null, userBis);
1001 Console.debug("Outputting type '" + type + "' to " + fileName);
1002 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1003 htmlSVG.exportHTML(fileName, renderer);
1008 "Outputting BioJS MSA Viwer HTML file: " + fileName);
1011 BioJsHTMLOutput.refreshVersionInfo(
1012 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1013 } catch (URISyntaxException e)
1015 e.printStackTrace();
1017 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1018 bjs.exportHTML(fileName);
1022 Console.debug("Outputting EPS file: " + fileName);
1023 af.createEPS(file, renderer);
1027 Console.debug("Outputting ImageMap file: " + fileName);
1028 af.createImageMap(file, name);
1032 addWarn(Arg.IMAGE.argString() + " type '" + type
1033 + "' not known. Ignoring");
1036 } catch (Exception ioex)
1038 addError("Unexpected error during export to '" + fileName + "'",
1043 this.colourAlignFrame(af, originalColourScheme);
1049 protected boolean processOutput(String id)
1051 ArgValuesMap avm = argParser.getLinkedArgs(id);
1052 AlignFrame af = afMap.get(id);
1054 if (avm != null && !avm.containsArg(Arg.OUTPUT))
1062 addWarn("Do not have an alignment window (id=" + id
1063 + "). Not proceeding.");
1067 Boolean isError = Boolean.valueOf(false);
1069 if (avm.containsArg(Arg.OUTPUT))
1071 for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1073 String val = av.getValue();
1074 SubVals subVals = av.getSubVals();
1075 String fileName = subVals.getContent();
1076 boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1077 File file = new File(fileName);
1079 String name = af.getName();
1080 String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1082 FileFormats ffs = FileFormats.getInstance();
1083 List<String> validFormats = ffs.getWritableFormats(false);
1085 FileFormatI ff = null;
1086 if (format == null && fileName != null)
1088 FORMAT: for (String fname : validFormats)
1090 FileFormatI tff = ffs.forName(fname);
1091 String[] extensions = tff.getExtensions().split(",");
1092 for (String ext : extensions)
1094 if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1097 format = ff.getName();
1103 if (ff == null && format != null)
1105 ff = ffs.forName(format);
1111 ff = FileFormat.Fasta;
1115 StringBuilder validSB = new StringBuilder();
1116 for (String f : validFormats)
1118 if (validSB.length() > 0)
1119 validSB.append(", ");
1121 FileFormatI tff = ffs.forName(f);
1122 validSB.append(" (");
1123 validSB.append(tff.getExtensions());
1124 validSB.append(")");
1127 addError("No valid format specified for "
1128 + Arg.OUTPUT.argString() + ". Valid formats are "
1129 + validSB.toString() + ".");
1134 boolean success = checksBeforeWritingToFile(avm, subVals, true,
1135 fileName, ff.getName(), isError);
1141 boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1142 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1143 !Platform.isHeadless());
1145 Console.info("Writing " + fileName);
1147 af.saveAlignment(fileName, ff, stdout, backups);
1148 if (af.isSaveAlignmentSuccessful())
1150 Console.debug("Written alignment '" + name + "' in "
1151 + ff.getName() + " format to '" + file + "'");
1155 addError("Error writing file '" + file + "' in " + ff.getName()
1166 private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1169 SubVals subVals = av.getSubVals();
1170 ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1171 SequenceI seq = null;
1172 if (subVals == null && idAv == null)
1174 if (af == null || af.getCurrentView() == null)
1178 AlignmentI al = af.getCurrentView().getAlignment();
1183 if (subVals != null)
1185 if (subVals.has(Arg.SEQID.getName()))
1187 seq = al.findName(subVals.get(Arg.SEQID.getName()));
1189 else if (-1 < subVals.getIndex()
1190 && subVals.getIndex() < al.getSequences().size())
1192 seq = al.getSequenceAt(subVals.getIndex());
1195 if (seq == null && idAv != null)
1197 seq = al.findName(idAv.getValue());
1202 public AlignFrame[] getAlignFrames()
1204 AlignFrame[] afs = null;
1207 afs = (AlignFrame[]) afMap.values().toArray();
1213 public List<StructureViewer> getStructureViewers()
1215 List<StructureViewer> svs = null;
1218 for (List<StructureViewer> svList : svMap.values())
1222 svs = new ArrayList<>();
1230 private void colourAlignFrame(AlignFrame af, String colour)
1232 // use string "none" to remove colour scheme
1233 if (colour != null && "" != colour)
1235 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1236 af.getViewport(), af.getViewport().getAlignment(), colour);
1237 if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1239 addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1243 Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1244 colourAlignFrame(af, cs);
1249 private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1251 // Note that cs == null removes colour scheme from af
1252 af.changeColour(cs);
1255 private ColourSchemeI getColourScheme(AlignFrame af)
1257 return af.getViewport().getGlobalColourScheme();
1260 private void addInfo(String errorMessage)
1262 Console.info(errorMessage);
1263 errors.add(errorMessage);
1266 private void addWarn(String errorMessage)
1268 Console.warn(errorMessage);
1269 errors.add(errorMessage);
1272 private void addError(String errorMessage)
1274 addError(errorMessage, null);
1277 private void addError(String errorMessage, Exception e)
1279 Console.error(errorMessage, e);
1280 errors.add(errorMessage);
1283 private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1284 SubVals subVal, boolean includeBackups, String filename,
1285 String adjective, Boolean isError)
1287 File file = new File(filename);
1289 boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1290 null, "OVERWRITE_OUTPUT", false);
1291 boolean stdout = false;
1292 boolean backups = false;
1295 stdout = ArgParser.STDOUTFILENAME.equals(filename);
1296 // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1297 // otherwise if headless assume false, if not headless use the user
1298 // preference with default true.
1299 backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1300 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1301 !Platform.isHeadless());
1304 if (file.exists() && !(overwrite || backups || stdout))
1306 addWarn("Won't overwrite file '" + filename + "' without "
1307 + Arg.OVERWRITE.argString()
1308 + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1313 boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1314 "MKDIRS_OUTPUT", false);
1316 if (!FileUtils.checkParentDir(file, mkdirs))
1318 addError("Directory '"
1319 + FileUtils.getParentDir(file).getAbsolutePath()
1320 + "' does not exist for " + adjective + " file '" + filename
1322 + (mkdirs ? "" : " Try using " + Arg.MKDIRS.argString()));
1330 public List<String> getErrors()
1335 public String errorsToString()
1337 StringBuilder sb = new StringBuilder();
1338 for (String error : errors)
1340 if (sb.length() > 0)
1342 sb.append("- " + error);
1344 return sb.toString();