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.ext.so.SequenceOntology;
24 import jalview.gui.AlignFrame;
25 import jalview.gui.Desktop;
26 import jalview.gui.PromptUserConfig;
27 import jalview.io.AppletFormatAdapter;
28 import jalview.io.BioJsHTMLOutput;
29 import jalview.io.DataSourceType;
30 import jalview.io.FileFormat;
31 import jalview.io.FileFormatException;
32 import jalview.io.FileFormatI;
33 import jalview.io.FileLoader;
34 import jalview.io.HtmlSvgOutput;
35 import jalview.io.IdentifyFile;
36 import jalview.io.NewickFile;
37 import jalview.io.gff.SequenceOntologyFactory;
38 import jalview.schemes.ColourSchemeI;
39 import jalview.schemes.ColourSchemeProperty;
40 import jalview.util.MessageManager;
41 import jalview.util.Platform;
42 import jalview.ws.jws2.Jws2Discoverer;
44 import java.io.BufferedReader;
46 import java.io.FileOutputStream;
47 import java.io.IOException;
48 import java.io.InputStreamReader;
49 import java.io.OutputStreamWriter;
50 import java.io.PrintStream;
51 import java.io.PrintWriter;
52 import java.net.MalformedURLException;
54 import java.net.URISyntaxException;
56 import java.security.AllPermission;
57 import java.security.CodeSource;
58 import java.security.PermissionCollection;
59 import java.security.Permissions;
60 import java.security.Policy;
61 import java.util.HashMap;
63 import java.util.Vector;
65 import javax.swing.LookAndFeel;
66 import javax.swing.UIManager;
68 import com.threerings.getdown.util.LaunchUtil;
70 import groovy.lang.Binding;
71 import groovy.util.GroovyScriptEngine;
74 * Main class for Jalview Application <br>
76 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
79 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
80 * jalview.bin.Jalview jalview.bin.Jalview
82 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
83 * embellish '*' to e.g. '*.jar')
91 * singleton instance of this class
93 private static Jalview instance;
95 private Desktop desktop;
97 public static AlignFrame currentAlignFrame;
101 // grab all the rights we can the JVM
102 Policy.setPolicy(new Policy()
105 public PermissionCollection getPermissions(CodeSource codesource)
107 Permissions perms = new Permissions();
108 perms.add(new AllPermission());
113 public void refresh()
120 * keep track of feature fetching tasks.
128 * TODO: generalise to track all jalview events to orchestrate batch processing
132 private int queued = 0;
134 private int running = 0;
136 public FeatureFetcher()
141 public void addFetcher(final AlignFrame af,
142 final Vector<String> dasSources)
144 final long id = System.currentTimeMillis();
146 final FeatureFetcher us = this;
147 new Thread(new Runnable()
159 af.setProgressBar(MessageManager
160 .getString("status.das_features_being_retrived"), id);
161 af.featureSettings_actionPerformed(null);
162 af.setProgressBar(null, id);
171 public synchronized boolean allFinished()
173 return queued == 0 && running == 0;
178 public static Jalview getInstance()
184 * main class for Jalview application
187 * open <em>filename</em>
189 public static void main(String[] args)
191 instance = new Jalview();
192 instance.doMain(args);
198 void doMain(String[] args)
200 System.setSecurityManager(null);
202 ArgsParser aparser = new ArgsParser(args);
203 // set stdout and stderr to file if launched by getdown
204 String appdirString = System.getProperty("getdownappdir");
205 if (appdirString != null)
208 String logFilename = aparser.getValue("out");
209 String parent = appdirString;
210 if (logFilename == null)
212 logFilename = "output.log";
216 if (logFilename.startsWith(File.separator))
221 File logFile = new File(parent, logFilename);
222 if (logFile.exists())
228 PrintStream logOut = new PrintStream(new FileOutputStream(logFile),
230 System.setOut(logOut);
231 System.setErr(logOut);
233 } catch (IOException ioe)
235 System.err.println("Failed to open debug log [path="
236 + logFile.getAbsolutePath() + ", exception=" + ioe + "]");
238 // if we've redirected our log output, note where to
241 System.out.println("Logging to '" + logFile + "'.");
247 .println("Java version: " + System.getProperty("java.version"));
248 System.out.println(System.getProperty("os.arch") + " "
249 + System.getProperty("os.name") + " "
250 + System.getProperty("os.version"));
251 // report Jalview version
252 Cache.loadBuildProperties(true);
254 boolean headless = false;
256 if (aparser.contains("help") || aparser.contains("h"))
261 if (aparser.contains("nodisplay") || aparser.contains("nogui")
262 || aparser.contains("headless"))
264 System.setProperty("java.awt.headless", "true");
267 String usrPropsFile = aparser.getValue("props");
268 Cache.loadProperties(usrPropsFile); // must do this before
269 if (usrPropsFile != null)
272 "CMD [-props " + usrPropsFile + "] executed successfully!");
277 final String jabawsUrl = aparser.getValue("jabaws");
278 if (jabawsUrl != null)
282 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
284 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
285 } catch (MalformedURLException e)
288 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
292 String defs = aparser.getValue("setprop");
295 int p = defs.indexOf('=');
298 System.err.println("Ignoring invalid setprop argument : " + defs);
302 System.out.println("Executing setprop argument: " + defs);
303 // DISABLED FOR SECURITY REASONS
304 // TODO: add a property to allow properties to be overriden by cli args
305 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
307 defs = aparser.getValue("setprop");
309 if (System.getProperty("java.awt.headless") != null
310 && System.getProperty("java.awt.headless").equals("true"))
314 System.setProperty("http.agent",
315 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
319 } catch (NoClassDefFoundError error)
321 error.printStackTrace();
322 System.out.println("\nEssential logging libraries not found."
323 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
331 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
332 } catch (Exception ex)
334 System.err.println("Unexpected Look and Feel Exception");
335 ex.printStackTrace();
337 if (Platform.isAMac())
340 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
342 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
344 System.setProperty("apple.laf.useScreenMenuBar", "true");
345 if (lookAndFeel != null)
349 UIManager.setLookAndFeel(lookAndFeel);
350 } catch (Throwable e)
353 "Failed to set QuaQua look and feel: " + e.toString());
356 if (lookAndFeel == null
357 || !(lookAndFeel.getClass().isAssignableFrom(
358 UIManager.getLookAndFeel().getClass()))
359 || !UIManager.getLookAndFeel().getClass().toString()
360 .toLowerCase().contains("quaqua"))
365 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
366 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
367 } catch (Throwable e)
370 "Failed to reset look and feel: " + e.toString());
376 * configure 'full' SO model if preferences say to, else use the default (SO
379 if (Cache.getDefault("USE_FULL_SO", true))
381 SequenceOntologyFactory.setInstance(new SequenceOntology());
386 desktop = new Desktop();
387 desktop.setInBatchMode(true); // indicate we are starting up
391 JalviewTaskbar.setTaskbar(this);
392 } catch (Exception e)
394 System.out.println("Cannot set Taskbar");
395 // e.printStackTrace();
396 } catch (Throwable t)
398 System.out.println("Cannot set Taskbar");
399 // t.printStackTrace();
402 desktop.setVisible(true);
403 desktop.startServiceDiscovery();
404 if (!aparser.contains("nousagestats"))
406 startUsageStats(desktop);
410 System.err.println("CMD [-nousagestats] executed successfully!");
413 if (!aparser.contains("noquestionnaire"))
415 String url = aparser.getValue("questionnaire");
418 // Start the desktop questionnaire prompter with the specified
420 Cache.log.debug("Starting questionnaire url at " + url);
421 desktop.checkForQuestionnaire(url);
423 "CMD questionnaire[-" + url + "] executed successfully!");
427 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
429 // Start the desktop questionnaire prompter with the specified
432 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
434 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
436 "Starting questionnaire with default url: " + defurl);
437 desktop.checkForQuestionnaire(defurl);
443 System.err.println("CMD [-noquestionnaire] executed successfully!");
446 if (!aparser.contains("nonews"))
448 desktop.checkForNews();
451 BioJsHTMLOutput.updateBioJS();
454 // Move any new getdown-launcher-new.jar into place over old
455 // getdown-launcher.jar
456 // String appdirString = System.getProperty("getdownappdir");
457 if (appdirString != null && appdirString.length() > 0)
459 final File appdir = new File(appdirString);
465 LaunchUtil.upgradeGetdown(
466 new File(appdir, "getdown-launcher-old.jar"),
467 new File(appdir, "getdown-launcher.jar"),
468 new File(appdir, "getdown-launcher-new.jar"));
473 String file = null, data = null;
474 FileFormatI format = null;
475 DataSourceType protocol = null;
476 FileLoader fileLoader = new FileLoader(!headless);
478 String groovyscript = null; // script to execute after all loading is
479 // completed one way or another
480 // extract groovy argument and execute if necessary
481 groovyscript = aparser.getValue("groovy", true);
482 file = aparser.getValue("open", true);
484 if (file == null && desktop == null)
486 System.out.println("No files to open!");
490 // Finally, deal with the remaining input data.
495 desktop.setProgressBar(
497 .getString("status.processing_commandline_args"),
498 progress = System.currentTimeMillis());
500 System.out.println("CMD [-open " + file + "] executed successfully!");
502 if (!file.startsWith("http://"))
504 if (!(new File(file)).exists())
506 System.out.println("Can't find " + file);
514 protocol = AppletFormatAdapter.checkProtocol(file);
518 format = new IdentifyFile().identify(file, protocol);
519 } catch (FileFormatException e1)
524 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
528 System.out.println("error");
532 setCurrentAlignFrame(af);
533 data = aparser.getValue("colour", true);
536 data.replaceAll("%20", " ");
538 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
539 af.getViewport(), af.getViewport().getAlignment(), data);
544 "CMD [-color " + data + "] executed successfully!");
549 // Must maintain ability to use the groups flag
550 data = aparser.getValue("groups", true);
553 af.parseFeaturesFile(data,
554 AppletFormatAdapter.checkProtocol(data));
555 // System.out.println("Added " + data);
557 "CMD groups[-" + data + "] executed successfully!");
559 data = aparser.getValue("features", true);
562 af.parseFeaturesFile(data,
563 AppletFormatAdapter.checkProtocol(data));
564 // System.out.println("Added " + data);
566 "CMD [-features " + data + "] executed successfully!");
569 data = aparser.getValue("annotations", true);
572 af.loadJalviewDataFile(data, null, null, null);
573 // System.out.println("Added " + data);
575 "CMD [-annotations " + data + "] executed successfully!");
577 // set or clear the sortbytree flag.
578 if (aparser.contains("sortbytree"))
580 af.getViewport().setSortByTree(true);
581 if (af.getViewport().getSortByTree())
583 System.out.println("CMD [-sortbytree] executed successfully!");
586 if (aparser.contains("no-annotation"))
588 af.getViewport().setShowAnnotation(false);
589 if (!af.getViewport().isShowAnnotation())
591 System.out.println("CMD no-annotation executed successfully!");
594 if (aparser.contains("nosortbytree"))
596 af.getViewport().setSortByTree(false);
597 if (!af.getViewport().getSortByTree())
600 .println("CMD [-nosortbytree] executed successfully!");
603 data = aparser.getValue("tree", true);
609 "CMD [-tree " + data + "] executed successfully!");
610 NewickFile nf = new NewickFile(data,
611 AppletFormatAdapter.checkProtocol(data));
613 .setCurrentTree(af.showNewickTree(nf, data).getTree());
614 } catch (IOException ex)
616 System.err.println("Couldn't add tree " + data);
617 ex.printStackTrace(System.err);
620 // TODO - load PDB structure(s) to alignment JAL-629
621 // (associate with identical sequence in alignment, or a specified
623 if (groovyscript != null)
625 // Execute the groovy script after we've done all the rendering stuff
626 // and before any images or figures are generated.
627 System.out.println("Executing script " + groovyscript);
628 executeGroovyScript(groovyscript, af);
629 System.out.println("CMD groovy[" + groovyscript
630 + "] executed successfully!");
633 String imageName = "unnamed.png";
634 while (aparser.getSize() > 1)
636 String outputFormat = aparser.nextValue();
637 file = aparser.nextValue();
639 if (outputFormat.equalsIgnoreCase("png"))
641 af.createPNG(new File(file));
642 imageName = (new File(file)).getName();
643 System.out.println("Creating PNG image: " + file);
646 else if (outputFormat.equalsIgnoreCase("svg"))
648 File imageFile = new File(file);
649 imageName = imageFile.getName();
650 af.createSVG(imageFile);
651 System.out.println("Creating SVG image: " + file);
654 else if (outputFormat.equalsIgnoreCase("html"))
656 File imageFile = new File(file);
657 imageName = imageFile.getName();
658 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
659 htmlSVG.exportHTML(file);
661 System.out.println("Creating HTML image: " + file);
664 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
668 System.err.println("The output html file must not be null");
673 BioJsHTMLOutput.refreshVersionInfo(
674 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
675 } catch (URISyntaxException e)
679 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
680 bjs.exportHTML(file);
682 .println("Creating BioJS MSA Viwer HTML file: " + file);
685 else if (outputFormat.equalsIgnoreCase("imgMap"))
687 af.createImageMap(new File(file), imageName);
688 System.out.println("Creating image map: " + file);
691 else if (outputFormat.equalsIgnoreCase("eps"))
693 File outputFile = new File(file);
695 "Creating EPS file: " + outputFile.getAbsolutePath());
696 af.createEPS(outputFile);
700 if (af.saveAlignment(file, format))
702 System.out.println("Written alignment in " + format
703 + " format to " + file);
707 System.out.println("Error writing file " + file + " in "
708 + format + " format!!");
713 while (aparser.getSize() > 0)
715 System.out.println("Unknown arg: " + aparser.nextValue());
719 AlignFrame startUpAlframe = null;
720 // We'll only open the default file if the desktop is visible.
722 // ////////////////////
724 if (!headless && file == null
725 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
727 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
728 jalview.bin.Cache.getDefault("www.jalview.org",
729 "http://www.jalview.org")
730 + "/examples/exampleFile_2_7.jar");
732 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
734 // hardwire upgrade of the startup file
735 file.replace("_2_3.jar", "_2_7.jar");
736 // and remove the stale setting
737 jalview.bin.Cache.removeProperty("STARTUP_FILE");
740 protocol = DataSourceType.FILE;
742 if (file.indexOf("http:") > -1)
744 protocol = DataSourceType.URL;
747 if (file.endsWith(".jar"))
749 format = FileFormat.Jalview;
755 format = new IdentifyFile().identify(file, protocol);
756 } catch (FileFormatException e)
762 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
764 // extract groovy arguments before anything else.
767 // Once all other stuff is done, execute any groovy scripts (in order)
768 if (groovyscript != null)
770 if (Cache.groovyJarsPresent())
772 System.out.println("Executing script " + groovyscript);
773 executeGroovyScript(groovyscript, startUpAlframe);
778 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
782 // and finally, turn off batch mode indicator - if the desktop still exists
787 desktop.setProgressBar(null, progress);
789 desktop.setInBatchMode(false);
793 private static void showUsage()
796 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
797 + "-nodisplay\tRun Jalview without User Interface.\n"
798 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
799 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
800 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
801 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
802 + "-features FILE\tUse the given file to mark features on the alignment.\n"
803 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
804 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
805 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
806 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
807 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
808 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
809 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
810 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
811 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
812 + "-png FILE\tCreate PNG image FILE from alignment.\n"
813 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
814 + "-html FILE\tCreate HTML file from alignment.\n"
815 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
816 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
817 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
818 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
819 + "-noquestionnaire\tTurn off questionnaire check.\n"
820 + "-nonews\tTurn off check for Jalview news.\n"
821 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
822 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
824 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
825 // after all other properties files have been read\n\t
826 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
827 // passed in correctly)"
828 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
829 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
830 + "-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"
831 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
834 private static void startUsageStats(final Desktop desktop)
837 * start a User Config prompt asking if we can log usage statistics.
839 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
840 "USAGESTATS", "Jalview Usage Statistics",
841 "Do you want to help make Jalview better by enabling "
842 + "the collection of usage statistics with Google Analytics ?"
843 + "\n\n(you can enable or disable usage tracking in the preferences)",
850 "Initialising googletracker for usage stats.");
851 Cache.initGoogleTracker();
852 Cache.log.debug("Tracking enabled.");
859 Cache.log.debug("Not enabling Google Tracking.");
862 desktop.addDialogThread(prompter);
866 * Locate the given string as a file and pass it to the groovy interpreter.
868 * @param groovyscript
869 * the script to execute
870 * @param jalviewContext
871 * the Jalview Desktop object passed in to the groovy
872 * binding as the 'Jalview' object.
874 private void executeGroovyScript(String groovyscript, AlignFrame af)
877 * for scripts contained in files
884 if (groovyscript.trim().equals("STDIN"))
886 // read from stdin into a tempfile and execute it
889 tfile = File.createTempFile("jalview", "groovy");
890 PrintWriter outfile = new PrintWriter(
891 new OutputStreamWriter(new FileOutputStream(tfile)));
892 BufferedReader br = new BufferedReader(
893 new InputStreamReader(System.in));
895 while ((line = br.readLine()) != null)
897 outfile.write(line + "\n");
903 } catch (Exception ex)
905 System.err.println("Failed to read from STDIN into tempfile "
906 + ((tfile == null) ? "(tempfile wasn't created)"
907 : tfile.toString()));
908 ex.printStackTrace();
913 sfile = tfile.toURI().toURL();
914 } catch (Exception x)
917 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
927 sfile = new URI(groovyscript).toURL();
928 } catch (Exception x)
930 tfile = new File(groovyscript);
933 System.err.println("File '" + groovyscript + "' does not exist.");
936 if (!tfile.canRead())
938 System.err.println("File '" + groovyscript + "' cannot be read.");
941 if (tfile.length() < 1)
943 System.err.println("File '" + groovyscript + "' is empty.");
948 sfile = tfile.getAbsoluteFile().toURI().toURL();
949 } catch (Exception ex)
951 System.err.println("Failed to create a file URL for "
952 + tfile.getAbsoluteFile());
959 Map<String, java.lang.Object> vbinding = new HashMap<>();
960 vbinding.put("Jalview", this);
963 vbinding.put("currentAlFrame", af);
965 Binding gbinding = new Binding(vbinding);
966 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
967 gse.run(sfile.toString(), gbinding);
968 if ("STDIN".equals(groovyscript))
970 // delete temp file that we made -
971 // only if it was successfully executed
974 } catch (Exception e)
976 System.err.println("Exception Whilst trying to execute file " + sfile
977 + " as a groovy script.");
978 e.printStackTrace(System.err);
983 public static boolean isHeadlessMode()
985 String isheadless = System.getProperty("java.awt.headless");
986 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
993 public AlignFrame[] getAlignFrames()
995 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
996 : Desktop.getAlignFrames();
1001 * Quit method delegates to Desktop.quit - unless running in headless mode when
1002 * it just ends the JVM
1006 if (desktop != null)
1016 public static AlignFrame getCurrentAlignFrame()
1018 return Jalview.currentAlignFrame;
1021 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1023 Jalview.currentAlignFrame = currentAlignFrame;