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 // set stdout and stderr to file if launched by getdown
203 String appdirString = System.getProperty("getdownappdir");
204 if (appdirString != null)
206 String logFilename = "output.log";
207 File logFile = new File(appdirString, logFilename);
208 if (logFile.exists())
214 PrintStream logOut = new PrintStream(new FileOutputStream(logFile),
216 System.setOut(logOut);
217 System.setErr(logOut);
219 } catch (IOException ioe)
221 System.err.println("Failed to open debug log [path="
222 + logFile.getAbsolutePath() + ", exception=" + ioe + "]");
224 // if we've redirected our log output, note where to
227 System.out.println("Logging to '" + logFile + "'.");
233 .println("Java version: " + System.getProperty("java.version"));
234 System.out.println(System.getProperty("os.arch") + " "
235 + System.getProperty("os.name") + " "
236 + System.getProperty("os.version"));
237 // report Jalview version
238 Cache.loadBuildProperties(true);
240 ArgsParser aparser = new ArgsParser(args);
241 boolean headless = false;
243 if (aparser.contains("help") || aparser.contains("h"))
248 if (aparser.contains("nodisplay") || aparser.contains("nogui")
249 || aparser.contains("headless"))
251 System.setProperty("java.awt.headless", "true");
254 String usrPropsFile = aparser.getValue("props");
255 Cache.loadProperties(usrPropsFile); // must do this before
256 if (usrPropsFile != null)
259 "CMD [-props " + usrPropsFile + "] executed successfully!");
264 final String jabawsUrl = aparser.getValue("jabaws");
265 if (jabawsUrl != null)
269 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
271 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
272 } catch (MalformedURLException e)
275 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
279 String defs = aparser.getValue("setprop");
282 int p = defs.indexOf('=');
285 System.err.println("Ignoring invalid setprop argument : " + defs);
289 System.out.println("Executing setprop argument: " + defs);
290 // DISABLED FOR SECURITY REASONS
291 // TODO: add a property to allow properties to be overriden by cli args
292 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
294 defs = aparser.getValue("setprop");
296 if (System.getProperty("java.awt.headless") != null
297 && System.getProperty("java.awt.headless").equals("true"))
301 System.setProperty("http.agent",
302 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
306 } catch (NoClassDefFoundError error)
308 error.printStackTrace();
309 System.out.println("\nEssential logging libraries not found."
310 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
318 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
319 } catch (Exception ex)
321 System.err.println("Unexpected Look and Feel Exception");
322 ex.printStackTrace();
324 if (Platform.isAMac())
327 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
329 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
331 System.setProperty("apple.laf.useScreenMenuBar", "true");
332 if (lookAndFeel != null)
336 UIManager.setLookAndFeel(lookAndFeel);
337 } catch (Throwable e)
340 "Failed to set QuaQua look and feel: " + e.toString());
343 if (lookAndFeel == null
344 || !(lookAndFeel.getClass().isAssignableFrom(
345 UIManager.getLookAndFeel().getClass()))
346 || !UIManager.getLookAndFeel().getClass().toString()
347 .toLowerCase().contains("quaqua"))
352 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
353 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
354 } catch (Throwable e)
357 "Failed to reset look and feel: " + e.toString());
363 * configure 'full' SO model if preferences say to, else use the default (SO
366 if (Cache.getDefault("USE_FULL_SO", true))
368 SequenceOntologyFactory.setInstance(new SequenceOntology());
373 desktop = new Desktop();
374 desktop.setInBatchMode(true); // indicate we are starting up
378 JalviewTaskbar.setTaskbar(this);
379 } catch (Exception e)
381 System.out.println("Cannot set Taskbar");
382 // e.printStackTrace();
383 } catch (Throwable t)
385 System.out.println("Cannot set Taskbar");
386 // t.printStackTrace();
389 desktop.setVisible(true);
390 desktop.startServiceDiscovery();
391 if (!aparser.contains("nousagestats"))
393 startUsageStats(desktop);
397 System.err.println("CMD [-nousagestats] executed successfully!");
400 if (!aparser.contains("noquestionnaire"))
402 String url = aparser.getValue("questionnaire");
405 // Start the desktop questionnaire prompter with the specified
407 Cache.log.debug("Starting questionnaire url at " + url);
408 desktop.checkForQuestionnaire(url);
410 "CMD questionnaire[-" + url + "] executed successfully!");
414 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
416 // Start the desktop questionnaire prompter with the specified
419 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
421 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
423 "Starting questionnaire with default url: " + defurl);
424 desktop.checkForQuestionnaire(defurl);
430 System.err.println("CMD [-noquestionnaire] executed successfully!");
433 if (!aparser.contains("nonews"))
435 desktop.checkForNews();
438 BioJsHTMLOutput.updateBioJS();
441 // Move any new getdown-launcher-new.jar into place over old
442 // getdown-launcher.jar
443 // String appdirString = System.getProperty("getdownappdir");
444 if (appdirString != null && appdirString.length() > 0)
446 final File appdir = new File(appdirString);
452 LaunchUtil.upgradeGetdown(
453 new File(appdir, "getdown-launcher-old.jar"),
454 new File(appdir, "getdown-launcher.jar"),
455 new File(appdir, "getdown-launcher-new.jar"));
460 String file = null, data = null;
461 FileFormatI format = null;
462 DataSourceType protocol = null;
463 FileLoader fileLoader = new FileLoader(!headless);
465 String groovyscript = null; // script to execute after all loading is
466 // completed one way or another
467 // extract groovy argument and execute if necessary
468 groovyscript = aparser.getValue("groovy", true);
469 file = aparser.getValue("open", true);
471 if (file == null && desktop == null)
473 System.out.println("No files to open!");
477 // Finally, deal with the remaining input data.
482 desktop.setProgressBar(
484 .getString("status.processing_commandline_args"),
485 progress = System.currentTimeMillis());
487 System.out.println("CMD [-open " + file + "] executed successfully!");
489 if (!file.startsWith("http://"))
491 if (!(new File(file)).exists())
493 System.out.println("Can't find " + file);
501 protocol = AppletFormatAdapter.checkProtocol(file);
505 format = new IdentifyFile().identify(file, protocol);
506 } catch (FileFormatException e1)
511 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
515 System.out.println("error");
519 setCurrentAlignFrame(af);
520 data = aparser.getValue("colour", true);
523 data.replaceAll("%20", " ");
525 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
526 af.getViewport(), af.getViewport().getAlignment(), data);
531 "CMD [-color " + data + "] executed successfully!");
536 // Must maintain ability to use the groups flag
537 data = aparser.getValue("groups", true);
540 af.parseFeaturesFile(data,
541 AppletFormatAdapter.checkProtocol(data));
542 // System.out.println("Added " + data);
544 "CMD groups[-" + data + "] executed successfully!");
546 data = aparser.getValue("features", true);
549 af.parseFeaturesFile(data,
550 AppletFormatAdapter.checkProtocol(data));
551 // System.out.println("Added " + data);
553 "CMD [-features " + data + "] executed successfully!");
556 data = aparser.getValue("annotations", true);
559 af.loadJalviewDataFile(data, null, null, null);
560 // System.out.println("Added " + data);
562 "CMD [-annotations " + data + "] executed successfully!");
564 // set or clear the sortbytree flag.
565 if (aparser.contains("sortbytree"))
567 af.getViewport().setSortByTree(true);
568 if (af.getViewport().getSortByTree())
570 System.out.println("CMD [-sortbytree] executed successfully!");
573 if (aparser.contains("no-annotation"))
575 af.getViewport().setShowAnnotation(false);
576 if (!af.getViewport().isShowAnnotation())
578 System.out.println("CMD no-annotation executed successfully!");
581 if (aparser.contains("nosortbytree"))
583 af.getViewport().setSortByTree(false);
584 if (!af.getViewport().getSortByTree())
587 .println("CMD [-nosortbytree] executed successfully!");
590 data = aparser.getValue("tree", true);
596 "CMD [-tree " + data + "] executed successfully!");
597 NewickFile nf = new NewickFile(data,
598 AppletFormatAdapter.checkProtocol(data));
600 .setCurrentTree(af.showNewickTree(nf, data).getTree());
601 } catch (IOException ex)
603 System.err.println("Couldn't add tree " + data);
604 ex.printStackTrace(System.err);
607 // TODO - load PDB structure(s) to alignment JAL-629
608 // (associate with identical sequence in alignment, or a specified
610 if (groovyscript != null)
612 // Execute the groovy script after we've done all the rendering stuff
613 // and before any images or figures are generated.
614 System.out.println("Executing script " + groovyscript);
615 executeGroovyScript(groovyscript, af);
616 System.out.println("CMD groovy[" + groovyscript
617 + "] executed successfully!");
620 String imageName = "unnamed.png";
621 while (aparser.getSize() > 1)
623 String outputFormat = aparser.nextValue();
624 file = aparser.nextValue();
626 if (outputFormat.equalsIgnoreCase("png"))
628 af.createPNG(new File(file));
629 imageName = (new File(file)).getName();
630 System.out.println("Creating PNG image: " + file);
633 else if (outputFormat.equalsIgnoreCase("svg"))
635 File imageFile = new File(file);
636 imageName = imageFile.getName();
637 af.createSVG(imageFile);
638 System.out.println("Creating SVG image: " + file);
641 else if (outputFormat.equalsIgnoreCase("html"))
643 File imageFile = new File(file);
644 imageName = imageFile.getName();
645 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
646 htmlSVG.exportHTML(file);
648 System.out.println("Creating HTML image: " + file);
651 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
655 System.err.println("The output html file must not be null");
660 BioJsHTMLOutput.refreshVersionInfo(
661 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
662 } catch (URISyntaxException e)
666 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
667 bjs.exportHTML(file);
669 .println("Creating BioJS MSA Viwer HTML file: " + file);
672 else if (outputFormat.equalsIgnoreCase("imgMap"))
674 af.createImageMap(new File(file), imageName);
675 System.out.println("Creating image map: " + file);
678 else if (outputFormat.equalsIgnoreCase("eps"))
680 File outputFile = new File(file);
682 "Creating EPS file: " + outputFile.getAbsolutePath());
683 af.createEPS(outputFile);
687 if (af.saveAlignment(file, format))
689 System.out.println("Written alignment in " + format
690 + " format to " + file);
694 System.out.println("Error writing file " + file + " in "
695 + format + " format!!");
700 while (aparser.getSize() > 0)
702 System.out.println("Unknown arg: " + aparser.nextValue());
706 AlignFrame startUpAlframe = null;
707 // We'll only open the default file if the desktop is visible.
709 // ////////////////////
711 if (!headless && file == null
712 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
714 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
715 jalview.bin.Cache.getDefault("www.jalview.org",
716 "http://www.jalview.org")
717 + "/examples/exampleFile_2_7.jar");
719 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
721 // hardwire upgrade of the startup file
722 file.replace("_2_3.jar", "_2_7.jar");
723 // and remove the stale setting
724 jalview.bin.Cache.removeProperty("STARTUP_FILE");
727 protocol = DataSourceType.FILE;
729 if (file.indexOf("http:") > -1)
731 protocol = DataSourceType.URL;
734 if (file.endsWith(".jar"))
736 format = FileFormat.Jalview;
742 format = new IdentifyFile().identify(file, protocol);
743 } catch (FileFormatException e)
749 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
751 // extract groovy arguments before anything else.
754 // Once all other stuff is done, execute any groovy scripts (in order)
755 if (groovyscript != null)
757 if (Cache.groovyJarsPresent())
759 System.out.println("Executing script " + groovyscript);
760 executeGroovyScript(groovyscript, startUpAlframe);
765 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
769 // and finally, turn off batch mode indicator - if the desktop still exists
774 desktop.setProgressBar(null, progress);
776 desktop.setInBatchMode(false);
780 private static void showUsage()
783 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
784 + "-nodisplay\tRun Jalview without User Interface.\n"
785 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
786 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
787 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
788 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
789 + "-features FILE\tUse the given file to mark features on the alignment.\n"
790 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
791 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
792 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
793 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
794 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
795 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
796 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
797 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
798 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
799 + "-png FILE\tCreate PNG image FILE from alignment.\n"
800 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
801 + "-html FILE\tCreate HTML file from alignment.\n"
802 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
803 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
804 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
805 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
806 + "-noquestionnaire\tTurn off questionnaire check.\n"
807 + "-nonews\tTurn off check for Jalview news.\n"
808 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
809 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
811 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
812 // after all other properties files have been read\n\t
813 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
814 // passed in correctly)"
815 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
816 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
817 + "-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"
818 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
821 private static void startUsageStats(final Desktop desktop)
824 * start a User Config prompt asking if we can log usage statistics.
826 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
827 "USAGESTATS", "Jalview Usage Statistics",
828 "Do you want to help make Jalview better by enabling "
829 + "the collection of usage statistics with Google Analytics ?"
830 + "\n\n(you can enable or disable usage tracking in the preferences)",
837 "Initialising googletracker for usage stats.");
838 Cache.initGoogleTracker();
839 Cache.log.debug("Tracking enabled.");
846 Cache.log.debug("Not enabling Google Tracking.");
849 desktop.addDialogThread(prompter);
853 * Locate the given string as a file and pass it to the groovy interpreter.
855 * @param groovyscript
856 * the script to execute
857 * @param jalviewContext
858 * the Jalview Desktop object passed in to the groovy
859 * binding as the 'Jalview' object.
861 private void executeGroovyScript(String groovyscript, AlignFrame af)
864 * for scripts contained in files
871 if (groovyscript.trim().equals("STDIN"))
873 // read from stdin into a tempfile and execute it
876 tfile = File.createTempFile("jalview", "groovy");
877 PrintWriter outfile = new PrintWriter(
878 new OutputStreamWriter(new FileOutputStream(tfile)));
879 BufferedReader br = new BufferedReader(
880 new InputStreamReader(System.in));
882 while ((line = br.readLine()) != null)
884 outfile.write(line + "\n");
890 } catch (Exception ex)
892 System.err.println("Failed to read from STDIN into tempfile "
893 + ((tfile == null) ? "(tempfile wasn't created)"
894 : tfile.toString()));
895 ex.printStackTrace();
900 sfile = tfile.toURI().toURL();
901 } catch (Exception x)
904 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
914 sfile = new URI(groovyscript).toURL();
915 } catch (Exception x)
917 tfile = new File(groovyscript);
920 System.err.println("File '" + groovyscript + "' does not exist.");
923 if (!tfile.canRead())
925 System.err.println("File '" + groovyscript + "' cannot be read.");
928 if (tfile.length() < 1)
930 System.err.println("File '" + groovyscript + "' is empty.");
935 sfile = tfile.getAbsoluteFile().toURI().toURL();
936 } catch (Exception ex)
938 System.err.println("Failed to create a file URL for "
939 + tfile.getAbsoluteFile());
946 Map<String, java.lang.Object> vbinding = new HashMap<>();
947 vbinding.put("Jalview", this);
950 vbinding.put("currentAlFrame", af);
952 Binding gbinding = new Binding(vbinding);
953 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
954 gse.run(sfile.toString(), gbinding);
955 if ("STDIN".equals(groovyscript))
957 // delete temp file that we made -
958 // only if it was successfully executed
961 } catch (Exception e)
963 System.err.println("Exception Whilst trying to execute file " + sfile
964 + " as a groovy script.");
965 e.printStackTrace(System.err);
970 public static boolean isHeadlessMode()
972 String isheadless = System.getProperty("java.awt.headless");
973 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
980 public AlignFrame[] getAlignFrames()
982 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
983 : Desktop.getAlignFrames();
988 * Quit method delegates to Desktop.quit - unless running in headless mode when
989 * it just ends the JVM
1003 public static AlignFrame getCurrentAlignFrame()
1005 return Jalview.currentAlignFrame;
1008 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1010 Jalview.currentAlignFrame = currentAlignFrame;