2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
23 import jalview.api.AlignCalcWorkerI;
24 import jalview.api.AlignFrameI;
25 import jalview.api.AlignViewportI;
26 import jalview.api.JalviewApp;
27 import jalview.api.StructureSelectionManagerProvider;
28 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.ext.so.SequenceOntology;
35 import jalview.gui.AlignFrame;
36 import jalview.gui.AlignViewport;
37 import jalview.gui.AlignmentPanel;
38 import jalview.gui.CalculationChooser;
39 import jalview.gui.Desktop;
40 import jalview.gui.Preferences;
41 import jalview.gui.PromptUserConfig;
42 import jalview.gui.StructureViewer;
43 import jalview.io.AppletFormatAdapter;
44 import jalview.io.BioJsHTMLOutput;
45 import jalview.io.DataSourceType;
46 import jalview.io.FileFormat;
47 import jalview.io.FileFormatException;
48 import jalview.io.FileFormatI;
49 import jalview.io.FileFormats;
50 import jalview.io.FileLoader;
51 import jalview.io.HtmlSvgOutput;
52 import jalview.io.IdentifyFile;
53 import jalview.io.NewickFile;
54 import jalview.io.gff.SequenceOntologyFactory;
55 import jalview.javascript.JSFunctionExec;
56 import jalview.javascript.MouseOverStructureListener;
57 import jalview.renderer.seqfeatures.FeatureRenderer;
58 import jalview.schemes.ColourSchemeI;
59 import jalview.schemes.ColourSchemeProperty;
60 import jalview.structure.SelectionSource;
61 import jalview.structure.VamsasSource;
62 import jalview.util.MessageManager;
63 import jalview.util.Platform;
64 import jalview.ws.jws2.Jws2Discoverer;
66 import java.applet.AppletContext;
67 import java.io.BufferedReader;
69 import java.io.FileOutputStream;
70 import java.io.IOException;
71 import java.io.InputStreamReader;
72 import java.io.OutputStreamWriter;
73 import java.io.PrintWriter;
74 import java.net.MalformedURLException;
76 import java.net.URISyntaxException;
78 import java.security.AllPermission;
79 import java.security.CodeSource;
80 import java.security.PermissionCollection;
81 import java.security.Permissions;
82 import java.security.Policy;
83 import java.util.HashMap;
84 import java.util.Hashtable;
86 import java.util.Vector;
88 import javax.swing.LookAndFeel;
89 import javax.swing.UIManager;
91 import groovy.lang.Binding;
92 import groovy.util.GroovyScriptEngine;
93 import netscape.javascript.JSObject;
96 * Main class for Jalview Application <br>
98 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
101 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
102 * jalview.bin.Jalview jalview.bin.Jalview
104 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
105 * embellish '*' to e.g. '*.jar')
108 * @version $Revision$
110 public class Jalview implements ApplicationSingletonI, JalviewJSApi
113 public static Jalview getInstance()
115 return (Jalview) ApplicationSingletonProvider
116 .getInstance(Jalview.class);
125 Platform.getURLCommandArguments();
128 private boolean headless;
130 public static boolean isHeadlessMode()
132 return getInstance().headless;
135 private Desktop desktop;
137 private AlignFrame currentAlignFrame;
139 public boolean isJavaAppletTag;
141 public String appletResourcePath;
143 JalviewAppLoader appLoader;
145 protected JSFunctionExec jsFunctionExec;
147 private boolean noCalculation, noMenuBar, noStatus;
149 private boolean noAnnotation;
151 public boolean getStartCalculations()
153 return !noCalculation;
156 public boolean getAllowMenuBar()
161 public boolean getShowStatus()
166 public boolean getShowAnnotation()
168 return !noAnnotation;
171 public static AlignFrame getCurrentAlignFrame()
173 return getInstance().currentAlignFrame;
176 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
178 getInstance().currentAlignFrame = currentAlignFrame;
183 if (!Platform.isJS())
190 // grab all the rights we can for the JVM
191 Policy.setPolicy(new Policy()
194 public PermissionCollection getPermissions(CodeSource codesource)
196 Permissions perms = new Permissions();
197 perms.add(new AllPermission());
202 public void refresh()
210 * keep track of feature fetching tasks.
218 * TODO: generalise to track all jalview events to orchestrate batch
222 private int queued = 0;
224 private int running = 0;
226 public FeatureFetcher()
231 public void addFetcher(final AlignFrame af,
232 final Vector<String> dasSources)
234 final long id = System.currentTimeMillis();
236 final FeatureFetcher us = this;
237 new Thread(new Runnable()
249 af.setProgressBar(MessageManager
250 .getString("status.das_features_being_retrived"), id);
251 af.featureSettings_actionPerformed(null);
252 af.setProgressBar(null, id);
261 public synchronized boolean allFinished()
263 return queued == 0 && running == 0;
269 * main class for Jalview application
272 * open <em>filename</em>
274 public static void main(String[] args)
276 // Platform.startJavaLogging();
277 getInstance().doMain(args);
281 @SuppressWarnings("unused")
285 void doMain(String[] args)
288 boolean isJS = Platform.isJS();
291 Platform.setAppClass(this);
295 System.setSecurityManager(null);
299 .println("Java version: " + System.getProperty("java.version"));
300 System.out.println(System.getProperty("os.arch") + " "
301 + System.getProperty("os.name") + " "
302 + System.getProperty("os.version"));
304 ArgsParser aparser = new ArgsParser(args);
306 String usrPropsFile = aparser.getValue(ArgsParser.PROPS);
307 Cache.loadProperties(usrPropsFile);
309 if (aparser.contains(ArgsParser.NODISPLAY)
310 || aparser.contains(ArgsParser.NOGUI)
311 || aparser.contains(ArgsParser.HEADLESS)
312 || "true".equals(System.getProperty("java.awt.headless")))
319 isJavaAppletTag = aparser.isApplet();
322 Preferences.setAppletDefaults();
323 Cache.loadProperties(usrPropsFile); // again, because we
324 // might be changing defaults here?
327 "<Applet> found: " + aparser.getValue("Info.j2sAppletID"));
328 appletResourcePath = aparser.getValue("Info.resourcePath");
337 if (usrPropsFile != null)
340 "CMD [-props " + usrPropsFile + "] executed successfully!");
343 if (aparser.contains("help") || aparser.contains("h"))
352 final String jabawsUrl = aparser.getValue(ArgsParser.JABAWS);
353 if (jabawsUrl != null)
357 Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
359 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
360 } catch (MalformedURLException e)
363 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
368 // check for property setting
369 String defs = aparser.getValue(ArgsParser.SETPROP);
372 int p = defs.indexOf('=');
375 System.err.println("Ignoring invalid setprop argument : " + defs);
379 System.out.println("Executing setprop argument: " + defs);
382 Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
385 defs = aparser.getValue(ArgsParser.SETPROP);
387 System.setProperty("http.agent",
388 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
392 } catch (NoClassDefFoundError error)
394 error.printStackTrace();
395 System.out.println("\nEssential logging libraries not found."
396 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
404 if (!isJS && Platform.isWin())
406 UIManager.setLookAndFeel(
407 headless ? "javax.swing.plaf.metal.MetalLookAndFeel"
408 : UIManager.getSystemLookAndFeelClassName());
409 // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
411 } catch (Exception ex)
413 System.err.println("Unexpected Look and Feel Exception");
414 ex.printStackTrace();
416 if (Platform.isAMacAndNotJS())
419 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
421 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
423 System.setProperty("apple.laf.useScreenMenuBar", "true");
424 if (lookAndFeel != null)
428 UIManager.setLookAndFeel(lookAndFeel);
429 } catch (Throwable e)
432 "Failed to set QuaQua look and feel: " + e.toString());
435 if (lookAndFeel == null
436 || !(lookAndFeel.getClass().isAssignableFrom(
437 UIManager.getLookAndFeel().getClass()))
438 || !UIManager.getLookAndFeel().getClass().toString()
439 .toLowerCase().contains("quaqua"))
444 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
445 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
446 } catch (Throwable e)
449 "Failed to reset look and feel: " + e.toString());
455 * configure 'full' SO model if preferences say to,
456 * else use the default (SO Lite)
458 if (Cache.getDefault(Preferences.USE_FULL_SO, false))
460 SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
465 desktop = Desktop.getInstance();
466 desktop.setInBatchMode(true); // indicate we are starting up
467 desktop.setVisible(true);
476 desktop.startServiceDiscovery();
477 if (!aparser.contains(ArgsParser.NOUSAGESTATS))
479 startUsageStats(desktop);
483 System.err.println("CMD [-nousagestats] executed successfully!");
486 if (!aparser.contains(ArgsParser.NOQUESTIONNAIRE))
488 String url = aparser.getValue(ArgsParser.QUESTIONNAIRE);
491 // Start the desktop questionnaire prompter with the specified
493 Cache.log.debug("Starting questionnaire url at " + url);
494 desktop.checkForQuestionnaire(url);
495 System.out.println("CMD questionnaire[-" + url
496 + "] executed successfully!");
500 if (Cache.getProperty(Preferences.NOQUESTIONNAIRES) == null)
502 // Start the desktop questionnaire prompter with the specified
505 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
507 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
509 "Starting questionnaire with default url: " + defurl);
510 desktop.checkForQuestionnaire(defurl);
517 .println("CMD [-noquestionnaire] executed successfully!");
520 if (!aparser.contains(ArgsParser.NONEWS))
522 desktop.checkForNews();
525 BioJsHTMLOutput.updateBioJS();
529 parseArguments(aparser, true);
533 * Allow an outside entity to initiate the second half of argument parsing
537 * @return null is good
540 public Object parseArguments(String[] args)
545 ArgsParser aparser = new ArgsParser(args);
546 return parseArguments(aparser, false);
547 } catch (Throwable t)
559 private Object parseArguments(ArgsParser aparser, boolean isStartup)
561 boolean isJS = Platform.isJS();
563 Desktop desktop = (headless ? null : Desktop.getInstance());
564 // script to execute after all loading is
565 // completed one way or another
566 // extract groovy argument and execute if necessary
567 String groovyscript = (isJS ? null
568 : aparser.getValue(ArgsParser.GROOVY, true));
569 String file = aparser.getValue(ArgsParser.OPEN, true);
570 // BH this here to allow split frame; not working as of 5/17/2019
571 String file2 = aparser.getValue(ArgsParser.OPEN2, true);
572 String fileFormat = (isJavaAppletTag
573 ? aparser.getAppletValue("format", null)
575 FileFormatI format = null;
576 DataSourceType protocol = null;
578 if (file == null && desktop == null)
580 System.out.println("No files to open!");
583 boolean haveImport = checkStartVamas(aparser);
584 // Finally, deal with the remaining input data.
586 if (file == null && isJavaAppletTag)
588 // Maybe the sequences are added as parameters
589 StringBuffer data = new StringBuffer("PASTE");
591 while ((file = aparser.getAppletValue("sequence" + i, null)) != null)
593 data.append(file.toString() + "\n");
596 if (data.length() > 5)
598 file = data.toString();
609 desktop.setProgressBar(
611 .getString("status.processing_commandline_args"),
612 progress = System.currentTimeMillis());
617 * ignore in JavaScript -- can't just check file existence - could load
623 if (!file.startsWith("http://") && !file.startsWith("https://"))
624 // BH 2019 added https check for Java
626 if (!(new File(file)).exists())
628 System.out.println("Can't find " + file);
637 protocol = AppletFormatAdapter.checkProtocol(file);
641 format = (isJavaAppletTag && fileFormat != null
642 ? FileFormats.getInstance().forName(fileFormat)
646 format = new IdentifyFile().identify(file, protocol);
648 } catch (FileFormatException e1)
653 if (aparser.contains(ArgsParser.NOMENUBAR))
656 System.out.println("CMD [nomenu] executed successfully!");
659 if (aparser.contains(ArgsParser.NOSTATUS))
662 System.out.println("CMD [nostatus] executed successfully!");
665 if (aparser.contains(ArgsParser.NOANNOTATION)
666 || aparser.contains(ArgsParser.NOANNOTATION2))
669 System.out.println("CMD no-annotation executed successfully!");
671 if (aparser.contains(ArgsParser.NOCALCULATION))
673 noCalculation = true;
674 System.out.println("CMD [nocalculation] executed successfully!");
677 AlignFrame af = new FileLoader(!headless).loadFileWaitTillLoaded(file,
681 System.out.println("error");
686 .println("CMD [-open " + file + "] executed successfully!");
689 protocol = AppletFormatAdapter.checkProtocol(file2);
692 format = new IdentifyFile().identify(file2, protocol);
693 } catch (FileFormatException e1)
697 AlignFrame af2 = new FileLoader(!headless)
698 .loadFileWaitTillLoaded(file2, protocol, format);
701 System.out.println("error");
705 AlignViewport.openLinkedAlignmentAs(af,
706 af.getViewport().getAlignment(),
707 af2.getViewport().getAlignment(), "",
708 AlignViewport.SPLIT_FRAME);
710 "CMD [-open2 " + file2 + "] executed successfully!");
714 setCurrentAlignFrame(af);
716 // TODO: file2 How to implement file2 for the applet spit screen?
718 data = aparser.getValue(ArgsParser.COLOUR, true);
721 data.replaceAll("%20", " ");
723 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
724 af.getViewport(), af.getViewport().getAlignment(), data);
729 "CMD [-color " + data + "] executed successfully!");
734 // Must maintain ability to use the groups flag
735 data = aparser.getValue(ArgsParser.GROUPS, true);
738 af.parseFeaturesFile(data,
739 AppletFormatAdapter.checkProtocol(data));
740 // System.out.println("Added " + data);
742 "CMD groups[-" + data + "] executed successfully!");
744 data = aparser.getValue(ArgsParser.FEATURES, true);
747 af.parseFeaturesFile(data,
748 AppletFormatAdapter.checkProtocol(data));
749 // System.out.println("Added " + data);
751 "CMD [-features " + data + "] executed successfully!");
754 data = aparser.getValue(ArgsParser.ANNOTATIONS, true);
757 af.loadJalviewDataFile(data, null, null, null);
758 // System.out.println("Added " + data);
760 "CMD [-annotations " + data + "] executed successfully!");
763 if (aparser.contains(ArgsParser.SHOWOVERVIEW))
765 af.overviewMenuItem_actionPerformed(null);
766 System.out.println("CMD [showoverview] executed successfully!");
769 // set or clear the sortbytree flag.
770 if (aparser.contains(ArgsParser.SORTBYTREE))
772 af.getViewport().setSortByTree(true);
773 if (af.getViewport().getSortByTree())
775 System.out.println("CMD [-sortbytree] executed successfully!");
779 boolean doUpdateAnnotation = false;
782 * we do this earlier in JalviewJS because of a complication with
785 * For now, just fixing this in JalviewJS.
792 if (aparser.contains(ArgsParser.NOANNOTATION)
793 || aparser.contains(ArgsParser.NOANNOTATION2))
795 af.getViewport().setShowAnnotation(false);
796 if (!af.getViewport().isShowAnnotation())
798 doUpdateAnnotation = true;
800 .println("CMD no-annotation executed successfully!");
804 if (aparser.contains(ArgsParser.NOSORTBYTREE))
806 af.getViewport().setSortByTree(false);
807 if (!af.getViewport().getSortByTree())
809 doUpdateAnnotation = true;
811 .println("CMD [-nosortbytree] executed successfully!");
814 if (doUpdateAnnotation)
816 af.setMenusForViewport();
817 af.alignPanel.updateLayout();
819 data = aparser.getValue(ArgsParser.TREE, true);
825 "CMD [-tree " + data + "] executed successfully!");
826 NewickFile nf = new NewickFile(data,
827 AppletFormatAdapter.checkProtocol(data));
829 .setCurrentTree(af.showNewickTree(nf, data).getTree());
830 } catch (IOException ex)
832 System.err.println("Couldn't add tree " + data);
833 ex.printStackTrace(System.err);
836 // TODO - load PDB structure(s) to alignment JAL-629
837 // (associate with identical sequence in alignment, or a specified
841 loadAppletParams(aparser, af);
850 if (groovyscript != null)
852 // Execute the groovy script after we've done all the rendering
854 // and before any images or figures are generated.
855 System.out.println("Executing script " + groovyscript);
856 executeGroovyScript(groovyscript, af);
857 System.out.println("CMD groovy[" + groovyscript
858 + "] executed successfully!");
862 createOutputFiles(aparser, af, format);
863 while (aparser.getSize() > 0)
865 System.out.println("Unknown arg: " + aparser.nextValue());
869 AlignFrame startUpAlframe = null;
870 // We'll only open the default file if the desktop is visible.
872 // ////////////////////
874 if (!isJS && !headless && file == null && !haveImport
875 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
882 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
883 jalview.bin.Cache.getDefault("www.jalview.org",
884 "http://www.jalview.org")
885 + "/examples/exampleFile_2_7.jar");
887 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
889 // hardwire upgrade of the startup file
890 file.replace("_2_3.jar", "_2_7.jar");
891 // and remove the stale setting
892 jalview.bin.Cache.removeProperty("STARTUP_FILE");
895 protocol = DataSourceType.FILE;
897 if (file.indexOf("http:") > -1)
899 protocol = DataSourceType.URL;
902 if (file.endsWith(".jar"))
904 format = FileFormat.Jalview;
910 format = new IdentifyFile().identify(file, protocol);
911 } catch (FileFormatException e)
917 startUpAlframe = new FileLoader(!headless)
918 .loadFileWaitTillLoaded(file, protocol, format);
919 // extract groovy arguments before anything else.
922 // Once all other stuff is done, execute any groovy scripts (in order)
923 if (groovyscript != null)
925 if (Cache.groovyJarsPresent())
927 System.out.println("Executing script " + groovyscript);
928 executeGroovyScript(groovyscript, startUpAlframe);
933 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
937 // and finally, turn off batch mode indicator - if the desktop still exists
942 desktop.setProgressBar(null, progress);
944 desktop.setInBatchMode(false);
950 private boolean checkStartVamas(ArgsParser aparser)
952 String vamsasImport = aparser.getValue(ArgsParser.VDOC);
953 String vamsasSession = aparser.getValue(ArgsParser.VSESS);
954 if (vamsasImport == null && vamsasSession == null)
958 if (desktop == null || headless)
961 "Headless vamsas sessions not yet supported. Sorry.");
964 boolean haveImport = (vamsasImport != null);
967 // if we have a file, start a new session and import it.
968 boolean inSession = false;
971 DataSourceType viprotocol = AppletFormatAdapter
972 .checkProtocol(vamsasImport);
973 if (viprotocol == DataSourceType.FILE)
975 inSession = desktop.vamsasImport(new File(vamsasImport));
977 else if (viprotocol == DataSourceType.URL)
979 inSession = desktop.vamsasImport(new URL(vamsasImport));
982 } catch (Exception e)
984 System.err.println("Exeption when importing " + vamsasImport
985 + " as a vamsas document.");
990 System.err.println("Failed to import " + vamsasImport
991 + " as a vamsas document.");
995 System.out.println("Imported Successfully into new session "
996 + desktop.getVamsasApplication().getCurrentSession());
999 if (vamsasSession != null)
1001 if (vamsasImport != null)
1003 // close the newly imported session and import the Jalview specific
1004 // remnants into the new session later on.
1005 desktop.vamsasStop_actionPerformed(null);
1007 // now join the new session
1010 if (desktop.joinVamsasSession(vamsasSession))
1013 "Successfully joined vamsas session " + vamsasSession);
1017 System.err.println("WARNING: Failed to join vamsas session "
1020 } catch (Exception e)
1023 "ERROR: Failed to join vamsas session " + vamsasSession);
1024 e.printStackTrace();
1026 if (vamsasImport != null)
1028 // the Jalview specific remnants can now be imported into the new
1029 // session at the user's leisure.
1031 "Skipping Push for import of data into existing vamsas session.");
1037 // desktop.getVamsasApplication().push_update();
1044 * Writes an output file for each format (if any) specified in the
1045 * command-line arguments. Supported formats are currently
1054 * A format parameter should be followed by a parameter specifying the output
1055 * file name. {@code imgMap} parameters should follow those for the
1056 * corresponding alignment image output.
1062 private void createOutputFiles(ArgsParser aparser, AlignFrame af,
1065 String imageName = "unnamed.png";
1066 while (aparser.getSize() > 1)
1068 String outputFormat = aparser.nextValue();
1069 String file = aparser.nextValue();
1070 // System.out.println("format " + outputFormat);
1072 if (outputFormat.equalsIgnoreCase("png"))
1074 af.createPNG(new File(file));
1075 imageName = (new File(file)).getName();
1076 System.out.println("Creating PNG image: " + file);
1079 else if (outputFormat.equalsIgnoreCase("svg"))
1081 File imageFile = new File(file);
1082 imageName = imageFile.getName();
1083 af.createSVG(imageFile);
1084 System.out.println("Creating SVG image: " + file);
1087 else if (outputFormat.equalsIgnoreCase("html"))
1089 File imageFile = new File(file);
1090 imageName = imageFile.getName();
1091 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1092 htmlSVG.exportHTML(file);
1094 System.out.println("Creating HTML image: " + file);
1097 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
1101 System.err.println("The output html file must not be null");
1106 BioJsHTMLOutput.refreshVersionInfo(
1107 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1108 } catch (URISyntaxException e)
1110 e.printStackTrace();
1112 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1113 bjs.exportHTML(file);
1114 System.out.println("Creating BioJS MSA Viwer HTML file: " + file);
1117 else if (outputFormat.equalsIgnoreCase("imgMap"))
1119 af.createImageMap(new File(file), imageName);
1120 System.out.println("Creating image map: " + file);
1123 else if (outputFormat.equalsIgnoreCase("eps"))
1125 File outputFile = new File(file);
1127 "Creating EPS file: " + outputFile.getAbsolutePath());
1128 af.createEPS(outputFile);
1132 af.saveAlignment(file, format);
1133 if (af.isSaveAlignmentSuccessful())
1136 "Written alignment in " + format + " format to " + file);
1140 System.out.println("Error writing file " + file + " in " + format
1147 private static void showUsage()
1150 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1151 + "-nodisplay\tRun Jalview without User Interface.\n"
1152 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1153 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1154 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1155 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1156 + "-features FILE\tUse the given file to mark features on the alignment.\n"
1157 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1158 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1159 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1160 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1161 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1162 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1163 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1164 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1165 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1166 + "-png FILE\tCreate PNG image FILE from alignment.\n"
1167 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1168 + "-html FILE\tCreate HTML file from alignment.\n"
1169 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1170 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1171 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1172 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1173 + "-noquestionnaire\tTurn off questionnaire check.\n"
1174 + "-nonews\tTurn off check for Jalview news.\n"
1175 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1176 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1178 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1179 // after all other properties files have been read\n\t
1180 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1181 // passed in correctly)"
1182 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1183 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1185 // "-vdoc vamsas-document\tImport vamsas document into new
1186 // session or join existing session with same URN\n"
1187 // + "-vses vamsas-session\tJoin session with given URN\n"
1188 + "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed (if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
1189 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1192 private static void startUsageStats(final Desktop desktop)
1195 * start a User Config prompt asking if we can log usage statistics.
1197 PromptUserConfig prompter = new PromptUserConfig(
1198 Desktop.getDesktopPane(), "USAGESTATS",
1199 "Jalview Usage Statistics",
1200 "Do you want to help make Jalview better by enabling "
1201 + "the collection of usage statistics with Google Analytics ?"
1202 + "\n\n(you can enable or disable usage tracking in the preferences)",
1209 "Initialising googletracker for usage stats.");
1210 Cache.initGoogleTracker();
1211 Cache.log.debug("Tracking enabled.");
1218 Cache.log.debug("Not enabling Google Tracking.");
1221 desktop.addDialogThread(prompter);
1225 * Locate the given string as a file and pass it to the groovy interpreter.
1227 * @param groovyscript
1228 * the script to execute
1229 * @param jalviewContext
1230 * the Jalview Desktop object passed in to the groovy binding as the
1233 private void executeGroovyScript(String groovyscript, AlignFrame af)
1236 * for scripts contained in files
1243 if (groovyscript.trim().equals("STDIN"))
1245 // read from stdin into a tempfile and execute it
1248 tfile = File.createTempFile("jalview", "groovy");
1249 PrintWriter outfile = new PrintWriter(
1250 new OutputStreamWriter(new FileOutputStream(tfile)));
1251 BufferedReader br = new BufferedReader(
1252 new InputStreamReader(System.in));
1254 while ((line = br.readLine()) != null)
1256 outfile.write(line + "\n");
1262 } catch (Exception ex)
1264 System.err.println("Failed to read from STDIN into tempfile "
1265 + ((tfile == null) ? "(tempfile wasn't created)"
1266 : tfile.toString()));
1267 ex.printStackTrace();
1272 sfile = tfile.toURI().toURL();
1273 } catch (Exception x)
1276 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1278 x.printStackTrace();
1286 sfile = new URI(groovyscript).toURL();
1287 } catch (Exception x)
1289 tfile = new File(groovyscript);
1290 if (!tfile.exists())
1292 System.err.println("File '" + groovyscript + "' does not exist.");
1295 if (!tfile.canRead())
1297 System.err.println("File '" + groovyscript + "' cannot be read.");
1300 if (tfile.length() < 1)
1302 System.err.println("File '" + groovyscript + "' is empty.");
1307 sfile = tfile.getAbsoluteFile().toURI().toURL();
1308 } catch (Exception ex)
1310 System.err.println("Failed to create a file URL for "
1311 + tfile.getAbsoluteFile());
1318 Map<String, Object> vbinding = new HashMap<>();
1319 vbinding.put("Jalview", this);
1322 vbinding.put("currentAlFrame", af);
1324 Binding gbinding = new Binding(vbinding);
1325 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1326 gse.run(sfile.toString(), gbinding);
1327 if ("STDIN".equals(groovyscript))
1329 // delete temp file that we made -
1330 // only if it was successfully executed
1333 } catch (Exception e)
1335 System.err.println("Exception Whilst trying to execute file " + sfile
1336 + " as a groovy script.");
1337 e.printStackTrace(System.err);
1342 public AlignFrame[] getAlignFrames()
1344 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1345 : Desktop.getAlignFrames();
1350 * Quit method delegates to Desktop.quit - unless running in headless mode
1351 * when it just ends the JVM
1355 if (jsFunctionExec != null)
1357 jsFunctionExec.tidyUp();
1358 jsFunctionExec = null;
1361 if (desktop != null)
1372 * Get the SwingJS applet ID and combine that with the frameType
1375 * "alignment", "desktop", etc., or null
1378 public static String getAppID(String frameType)
1380 String id = Cache.getProperty("Info.j2sAppletID");
1385 return id + (frameType == null ? "" : "-" + frameType);
1389 * Handle all JalviewLite applet parameters
1394 private void loadAppletParams(ArgsParser aparser, AlignFrame af)
1396 JalviewApp app = new JalviewApp()
1401 // These are methods that are in JalviewLite that various classes call
1402 // but are not in JalviewLiteJsApi. Or, even if they are, other classes
1404 // them to JalviewLite directly. Some may not be necessary, but they have
1406 // be at least mentioned here, or the classes calling them should
1408 // JalviewLite itself.
1410 private boolean alignPDBStructures; // From JalviewLite; not implemented
1412 private Hashtable<String, Hashtable<String, String[]>> jsmessages;
1414 private Hashtable<String, int[]> jshashes;
1417 public String getParameter(String name)
1419 return aparser.getAppletValue(name, null);
1423 public boolean getDefaultParameter(String name, boolean def)
1426 return ((stn = getParameter(name)) == null ? def
1427 : "true".equalsIgnoreCase(stn));
1431 * Get the applet-like document base even though this is an application.
1434 public URL getDocumentBase()
1436 return Platform.getDocumentBase();
1440 * Get the applet-like code base even though this is an application.
1443 public URL getCodeBase()
1445 return Platform.getCodeBase();
1449 public AlignViewportI getViewport()
1451 return af.getViewport();
1459 public boolean parseFeaturesFile(String filename,
1460 DataSourceType protocol)
1462 return af.parseFeaturesFile(filename, protocol);
1470 public boolean loadScoreFile(String sScoreFile) throws IOException
1472 af.loadJalviewDataFile(sScoreFile, null, null, null);
1477 * annotations, jpredfile, jnetfile
1481 public void updateForAnnotations()
1483 af.updateForAnnotations();
1487 public void loadTree(NewickFile fin, String treeFile)
1490 // n/a -- already done by standard Jalview command line processing
1494 public void setAlignPdbStructures(boolean defaultParameter)
1496 alignPDBStructures = true;
1500 public void newStructureView(PDBEntry pdb, SequenceI[] seqs,
1501 String[] chains, DataSourceType protocol)
1503 StructureViewer.launchStructureViewer(af.alignPanel, pdb, seqs);
1507 public void setFeatureGroupState(String[] groups, boolean state)
1509 af.setFeatureGroupState(groups, state);
1513 public void alignedStructureView(PDBEntry[] pdb, SequenceI[][] seqs,
1514 String[][] chains, String[] protocols)
1517 "Jalview applet interface alignedStructureView not implemented");
1521 public void newFeatureSettings()
1524 "Jalview applet interface newFeatureSettings not implemented");
1527 private Vector<Runnable> jsExecQueue;
1530 public Vector<Runnable> getJsExecQueue(JSFunctionExec exec)
1532 jsFunctionExec = exec;
1533 return (jsExecQueue == null ? (jsExecQueue = new Vector<>())
1538 public AppletContext getAppletContext()
1540 // TODO Auto-generated method stub
1545 public boolean isJsfallbackEnabled()
1547 // TODO Auto-generated method stub
1552 public JSObject getJSObject()
1554 // TODO Auto-generated method stub
1559 public StructureSelectionManagerProvider getStructureSelectionManagerProvider()
1561 // TODO Q: what exactly is this? BH
1566 public void updateColoursFromMouseOver(Object source,
1567 MouseOverStructureListener mouseOverStructureListener)
1569 // TODO Auto-generated method stub
1574 public Object[] getSelectionForListener(SequenceGroup seqsel,
1575 ColumnSelection colsel, HiddenColumns hidden,
1576 SelectionSource source, Object alignFrame)
1578 return appLoader.getSelectionForListener(getCurrentAlignFrame(),
1579 seqsel, colsel, hidden, source, alignFrame);
1583 public String arrayToSeparatorList(String[] array)
1585 return appLoader.arrayToSeparatorList(array);
1589 public Hashtable<String, int[]> getJSHashes()
1591 return (jshashes == null ? (jshashes = new Hashtable<>())
1596 public Hashtable<String, Hashtable<String, String[]>> getJSMessages()
1598 return (jsmessages == null ? (jsmessages = new Hashtable<>())
1603 public Object getFrameForSource(VamsasSource source)
1608 if (source instanceof jalview.gui.AlignViewport
1609 && source == (af = getCurrentAlignFrame()).getViewport())
1611 // should be valid if it just generated an event!
1614 // TODO: ensure that if '_af' is specified along with a handler
1615 // function, then only events from that alignFrame are sent to that
1622 public FeatureRenderer getNewFeatureRenderer(AlignViewportI vp)
1624 return new jalview.gui.FeatureRenderer((AlignmentPanel) vp);
1629 appLoader = new JalviewAppLoader(true);
1630 appLoader.load(app);
1635 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
1638 public String getSelectedSequences()
1640 return getSelectedSequencesFrom(getCurrentAlignFrame());
1645 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
1648 public String getSelectedSequences(String sep)
1650 return getSelectedSequencesFrom(getCurrentAlignFrame(), sep);
1655 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
1659 public String getSelectedSequencesFrom(AlignFrameI alf)
1663 alf = getCurrentAlignFrame();
1665 return getSelectedSequencesFrom(alf, null);
1670 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
1671 * .AlignFrame, java.lang.String)
1674 public String getSelectedSequencesFrom(AlignFrameI alf, String sep)
1678 alf = getCurrentAlignFrame();
1680 return appLoader.getSelectedSequencesFrom(alf, sep);
1685 * @see jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
1686 * .AlignFrame, java.lang.String)
1689 public void highlight(String sequenceId, String position,
1690 String alignedPosition)
1692 highlightIn(null, sequenceId, position,
1697 public void highlightIn(AlignFrameI alf, String sequenceId,
1698 String position, String alignedPosition)
1702 alf = getCurrentAlignFrame();
1704 appLoader.highlightIn(alf, sequenceId, position, alignedPosition);
1708 public void select(String sequenceIds, String columns)
1710 selectIn(getCurrentAlignFrame(), sequenceIds, columns, null);
1714 public void select(String sequenceIds, String columns, String sep)
1716 selectIn(null, sequenceIds, columns, sep);
1720 public void selectIn(AlignFrameI alf, String sequenceIds, String columns)
1722 selectIn(alf, sequenceIds, columns, null);
1726 public void selectIn(AlignFrameI alf, String sequenceIds, String columns,
1731 alf = getCurrentAlignFrame();
1733 appLoader.selectIn(alf, sequenceIds, columns, sep);
1737 public String getSelectedSequencesAsAlignment(String format,
1740 return getSelectedSequencesAsAlignmentFrom(null,
1745 public String getSelectedSequencesAsAlignmentFrom(AlignFrameI alf,
1746 String format, String sep)
1750 alf = getCurrentAlignFrame();
1752 return appLoader.getSelectedSequencesAsAlignmentFrom(alf, format, sep);
1756 public String getAlignmentOrder()
1758 return getAlignmentFrom(getCurrentAlignFrame(), null);
1762 public String getAlignmentOrderFrom(AlignFrameI alf)
1764 return getAlignmentFrom(alf, null);
1768 public String getAlignmentOrderFrom(AlignFrameI alf, String sep)
1772 alf = getCurrentAlignFrame();
1774 return appLoader.getAlignmentOrderFrom(alf, sep);
1778 public String orderBy(String order, String undoName)
1780 return orderBy(order, undoName, null);
1784 public String orderBy(String order, String undoName, String sep)
1786 return orderAlignmentBy(getCurrentAlignFrame(), order, undoName, sep);
1790 public String orderAlignmentBy(AlignFrameI alf, String order,
1791 String undoName, String sep)
1795 alf = getCurrentAlignFrame();
1797 return appLoader.orderAlignmentBy(alf, order, undoName, sep);
1801 public String getAlignment(String format)
1803 return getAlignmentFrom(null, format, null);
1807 public String getAlignmentFrom(AlignFrameI alf, String format)
1809 return getAlignmentFrom(alf, format, null);
1813 public String getAlignment(String format, String suffix)
1815 return getAlignmentFrom(getCurrentAlignFrame(), format, suffix);
1819 public String getAlignmentFrom(AlignFrameI alf, String format,
1822 return appLoader.getAlignmentFrom(alf, format, suffix);
1826 public void loadAnnotation(String annotation)
1828 loadAnnotationFrom(getCurrentAlignFrame(), annotation);
1832 public void loadAnnotationFrom(AlignFrameI alf, String annotation)
1836 alf = getCurrentAlignFrame();
1838 appLoader.loadAnnotationFrom(alf, annotation);
1842 public void loadFeatures(String features, boolean autoenabledisplay)
1844 loadFeaturesFrom(currentAlignFrame, features, autoenabledisplay);
1848 public boolean loadFeaturesFrom(AlignFrameI alf, String features,
1849 boolean autoenabledisplay)
1853 alf = getCurrentAlignFrame();
1855 return appLoader.loadFeaturesFrom(alf, features, autoenabledisplay);
1859 public String getFeatures(String format)
1861 return getFeaturesFrom(null, format);
1865 public String getFeaturesFrom(AlignFrameI alf, String format)
1869 alf = getCurrentAlignFrame();
1871 return appLoader.getFeaturesFrom(alf, format);
1875 public String getAnnotation()
1877 return getAnnotationFrom(null);
1881 public String getAnnotationFrom(AlignFrameI alf)
1885 alf = getCurrentAlignFrame();
1887 return appLoader.getAnnotationFrom(alf);
1891 public AlignFrameI newView()
1893 return newViewFrom(null, null);
1897 public AlignFrameI newView(String name)
1899 return newViewFrom(null, name);
1903 public AlignFrameI newViewFrom(AlignFrameI alf)
1905 return newViewFrom(alf, null);
1909 public AlignFrameI newViewFrom(AlignFrameI alf, String name)
1913 alf = getCurrentAlignFrame();
1915 return appLoader.newViewFrom(alf, name);
1919 public AlignFrameI loadAlignment(String text, String title)
1921 return appLoader.loadAlignment(text, AlignFrame.DEFAULT_WIDTH,
1922 AlignFrame.DEFAULT_HEIGHT, title);
1926 public boolean addPdbFile(AlignFrameI alFrame, String sequenceId,
1927 String pdbEntryString, String pdbFile)
1929 if (alFrame == null)
1931 alFrame = getCurrentAlignFrame();
1933 return appLoader.addPdbFile(alFrame, sequenceId, pdbEntryString,
1938 public void scrollViewToIn(AlignFrameI alf, String topRow,
1939 String leftHandColumn)
1943 alf = getCurrentAlignFrame();
1945 appLoader.scrollViewToIn(alf, topRow, leftHandColumn);
1949 public void scrollViewToRowIn(AlignFrameI alf, String topRow)
1953 alf = getCurrentAlignFrame();
1955 appLoader.scrollViewToRowIn(alf, topRow);
1959 public void scrollViewToColumnIn(AlignFrameI alf, String leftHandColumn)
1963 alf = getCurrentAlignFrame();
1965 appLoader.scrollViewToColumnIn(alf, leftHandColumn);
1969 public String getFeatureGroups()
1971 return getFeatureGroupsOn(null);
1975 public String getFeatureGroupsOn(AlignFrameI alf)
1979 alf = getCurrentAlignFrame();
1981 return appLoader.getFeatureGroupsOn(alf);
1985 public String getFeatureGroupsOfState(boolean visible)
1987 return getFeatureGroupsOfStateOn(null, visible);
1991 public String getFeatureGroupsOfStateOn(AlignFrameI alf, boolean visible)
1995 alf = getCurrentAlignFrame();
1997 return appLoader.getFeatureGroupsOfStateOn(alf, visible);
2001 public void setFeatureGroupState(String groups, boolean state)
2002 { // JalviewLite API
2003 setFeatureGroupStateOn(null, groups, state);
2007 public void setFeatureGroupStateOn(AlignFrameI alf, String groups,
2012 alf = getCurrentAlignFrame();
2014 appLoader.setFeatureGroupStateOn(alf, groups, state);
2018 public String getSeparator()
2020 return appLoader.getSeparator();
2024 public void setSeparator(String separator)
2026 appLoader.setSeparator(separator);
2030 public String getJsMessage(String messageclass, String viewId)
2032 // see http://www.jalview.org/examples/jalviewLiteJs.html
2037 * Open a new Tree panel on the desktop statically. Params are standard (not
2038 * set by Groovy). No dialog is opened.
2043 * @return null, or the string "label.you_need_at_least_n_sequences" if number
2044 * of sequences selected is inappropriate
2047 public Object openTreePanel(AlignFrame af, String treeType,
2052 af = getCurrentAlignFrame();
2054 return CalculationChooser.openTreePanel(af, treeType, modelName, null);
2058 * public static method for JalviewJS API to open a PCAPanel without
2059 * necessarily using a dialog.
2063 * @return the PCAPanel, or the string "label.you_need_at_least_n_sequences"
2064 * if number of sequences selected is inappropriate
2067 public Object openPcaPanel(AlignFrame af, String modelName)
2071 af = getCurrentAlignFrame();
2073 return CalculationChooser.openPcaPanel(af, modelName, null);
2077 public String getSelectedSequencesAsAlignment(String format,
2080 return getSelectedSequencesAsAlignmentFrom(null,
2085 public String getSelectedSequencesAsAlignmentFrom(AlignFrameI alf,
2086 String format, boolean suffix)
2090 alf = getCurrentAlignFrame();
2092 return appLoader.getSelectedSequencesAsAlignmentFrom(alf, format,
2097 public String arrayToSeparatorList(String[] array)
2099 return appLoader.arrayToSeparatorList(array);
2103 public String[] separatorListToArray(String list)
2105 return appLoader.separatorListToArray(list);
2108 //// probably not needed in JalviewJS -- From when Jmol and Jalview did not
2109 //// have a direct connection?
2112 public void setMouseoverListener(String listener)
2114 // TODO Auto-generated method stub
2119 public void setMouseoverListener(AlignFrameI af, String listener)
2121 // TODO Auto-generated method stub
2126 public void setSelectionListener(String listener)
2128 // TODO Auto-generated method stub
2133 public void setSelectionListener(AlignFrameI af, String listener)
2135 // TODO Auto-generated method stub
2140 public void setStructureListener(String listener, String modelSet)
2142 // TODO Auto-generated method stub
2147 public void removeJavascriptListener(AlignFrameI af, String listener)
2149 // TODO Auto-generated method stub
2154 public void mouseOverStructure(String pdbResNum, String chain,
2157 // TODO Auto-generated method stub
2162 public void showOverview()
2164 currentAlignFrame.overviewMenuItem_actionPerformed(null);
2167 public void notifyWorker(AlignCalcWorkerI worker, String status)
2169 // System.out.println("Jalview worker " + worker.getClass().getSimpleName()