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.PrintWriter;
51 import java.net.MalformedURLException;
53 import java.net.URISyntaxException;
55 import java.security.AllPermission;
56 import java.security.CodeSource;
57 import java.security.PermissionCollection;
58 import java.security.Permissions;
59 import java.security.Policy;
60 import java.util.HashMap;
62 import java.util.Vector;
64 import javax.swing.LookAndFeel;
65 import javax.swing.UIManager;
67 import com.threerings.getdown.util.LaunchUtil;
69 import groovy.lang.Binding;
70 import groovy.util.GroovyScriptEngine;
73 * Main class for Jalview Application <br>
75 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
78 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
79 * jalview.bin.Jalview jalview.bin.Jalview
81 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
82 * embellish '*' to e.g. '*.jar')
90 * singleton instance of this class
92 private static Jalview instance;
94 private Desktop desktop;
96 public static AlignFrame currentAlignFrame;
100 // grab all the rights we can the JVM
101 Policy.setPolicy(new Policy()
104 public PermissionCollection getPermissions(CodeSource codesource)
106 Permissions perms = new Permissions();
107 perms.add(new AllPermission());
112 public void refresh()
119 * keep track of feature fetching tasks.
127 * TODO: generalise to track all jalview events to orchestrate batch
131 private int queued = 0;
133 private int running = 0;
135 public FeatureFetcher()
140 public void addFetcher(final AlignFrame af,
141 final Vector<String> dasSources)
143 final long id = System.currentTimeMillis();
145 final FeatureFetcher us = this;
146 new Thread(new Runnable()
158 af.setProgressBar(MessageManager
159 .getString("status.das_features_being_retrived"), id);
160 af.featureSettings_actionPerformed(null);
161 af.setProgressBar(null, id);
170 public synchronized boolean allFinished()
172 return queued == 0 && running == 0;
177 public static Jalview getInstance()
183 * main class for Jalview application
186 * open <em>filename</em>
188 public static void main(String[] args)
190 instance = new Jalview();
191 instance.doMain(args);
197 void doMain(String[] args)
199 System.setSecurityManager(null);
201 .println("Java version: " + System.getProperty("java.version"));
202 System.out.println(System.getProperty("os.arch") + " "
203 + System.getProperty("os.name") + " "
204 + System.getProperty("os.version"));
205 // report Jalview version
206 Cache.loadBuildProperties(true);
208 String appdirString = System.getProperty("getdownappdir");
209 if (appdirString != null && appdirString.length() > 0)
211 final File appdir = new File(appdirString);
217 LaunchUtil.upgradeGetdown(
218 new File(appdir, "getdown-launcher-old.jar"),
219 new File(appdir, "getdown-launcher.jar"),
220 new File(appdir, "getdown-launcher-new.jar"));
225 ArgsParser aparser = new ArgsParser(args);
226 boolean headless = false;
228 if (aparser.contains("help") || aparser.contains("h"))
233 if (aparser.contains("nodisplay") || aparser.contains("nogui")
234 || aparser.contains("headless"))
236 System.setProperty("java.awt.headless", "true");
239 String usrPropsFile = aparser.getValue("props");
240 Cache.loadProperties(usrPropsFile); // must do this before
241 if (usrPropsFile != null)
244 "CMD [-props " + usrPropsFile + "] executed successfully!");
249 final String jabawsUrl = aparser.getValue("jabaws");
250 if (jabawsUrl != null)
254 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
256 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
257 } catch (MalformedURLException e)
260 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
264 String defs = aparser.getValue("setprop");
267 int p = defs.indexOf('=');
270 System.err.println("Ignoring invalid setprop argument : " + defs);
274 System.out.println("Executing setprop argument: " + defs);
275 // DISABLED FOR SECURITY REASONS
276 // TODO: add a property to allow properties to be overriden by cli args
277 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
279 defs = aparser.getValue("setprop");
281 if (System.getProperty("java.awt.headless") != null
282 && System.getProperty("java.awt.headless").equals("true"))
286 System.setProperty("http.agent",
287 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
291 } catch (NoClassDefFoundError error)
293 error.printStackTrace();
294 System.out.println("\nEssential logging libraries not found."
295 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
303 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
304 } catch (Exception ex)
306 System.err.println("Unexpected Look and Feel Exception");
307 ex.printStackTrace();
309 if (Platform.isAMac())
312 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
314 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
316 System.setProperty("apple.laf.useScreenMenuBar", "true");
317 if (lookAndFeel != null)
321 UIManager.setLookAndFeel(lookAndFeel);
322 } catch (Throwable e)
325 "Failed to set QuaQua look and feel: " + e.toString());
328 if (lookAndFeel == null || !(lookAndFeel.getClass()
329 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
330 || !UIManager.getLookAndFeel().getClass().toString()
331 .toLowerCase().contains("quaqua"))
336 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
337 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
338 } catch (Throwable e)
341 "Failed to reset look and feel: " + e.toString());
347 * configure 'full' SO model if preferences say to,
348 * else use the default (SO Lite)
350 if (Cache.getDefault("USE_FULL_SO", false))
352 SequenceOntologyFactory.setInstance(new SequenceOntology());
357 desktop = new Desktop();
358 desktop.setInBatchMode(true); // indicate we are starting up
362 JalviewTaskbar.setTaskbar(this);
363 } catch (Exception e)
365 System.out.println("Cannot set Taskbar");
366 // e.printStackTrace();
367 } catch (Throwable t)
369 System.out.println("Cannot set Taskbar");
370 // t.printStackTrace();
373 desktop.setVisible(true);
374 desktop.startServiceDiscovery();
375 if (!aparser.contains("nousagestats"))
377 startUsageStats(desktop);
381 System.err.println("CMD [-nousagestats] executed successfully!");
384 if (!aparser.contains("noquestionnaire"))
386 String url = aparser.getValue("questionnaire");
389 // Start the desktop questionnaire prompter with the specified
391 Cache.log.debug("Starting questionnaire url at " + url);
392 desktop.checkForQuestionnaire(url);
394 "CMD questionnaire[-" + url + "] executed successfully!");
398 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
400 // Start the desktop questionnaire prompter with the specified
403 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
405 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
407 "Starting questionnaire with default url: " + defurl);
408 desktop.checkForQuestionnaire(defurl);
414 System.err.println("CMD [-noquestionnaire] executed successfully!");
417 if (!aparser.contains("nonews"))
419 desktop.checkForNews();
422 BioJsHTMLOutput.updateBioJS();
425 String file = null, data = null;
426 FileFormatI format = null;
427 DataSourceType protocol = null;
428 FileLoader fileLoader = new FileLoader(!headless);
430 String groovyscript = null; // script to execute after all loading is
431 // completed one way or another
432 // extract groovy argument and execute if necessary
433 groovyscript = aparser.getValue("groovy", true);
434 file = aparser.getValue("open", true);
436 if (file == null && desktop == null)
438 System.out.println("No files to open!");
442 // Finally, deal with the remaining input data.
447 desktop.setProgressBar(
449 .getString("status.processing_commandline_args"),
450 progress = System.currentTimeMillis());
452 System.out.println("CMD [-open " + file + "] executed successfully!");
454 if (!file.startsWith("http://"))
456 if (!(new File(file)).exists())
458 System.out.println("Can't find " + file);
466 protocol = AppletFormatAdapter.checkProtocol(file);
470 format = new IdentifyFile().identify(file, protocol);
471 } catch (FileFormatException e1)
476 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
480 System.out.println("error");
484 setCurrentAlignFrame(af);
485 data = aparser.getValue("colour", true);
488 data.replaceAll("%20", " ");
490 ColourSchemeI cs = ColourSchemeProperty
491 .getColourScheme(af.getViewport(),
492 af.getViewport().getAlignment(), data);
497 "CMD [-color " + data + "] executed successfully!");
502 // Must maintain ability to use the groups flag
503 data = aparser.getValue("groups", true);
506 af.parseFeaturesFile(data,
507 AppletFormatAdapter.checkProtocol(data));
508 // System.out.println("Added " + data);
510 "CMD groups[-" + data + "] executed successfully!");
512 data = aparser.getValue("features", true);
515 af.parseFeaturesFile(data,
516 AppletFormatAdapter.checkProtocol(data));
517 // System.out.println("Added " + data);
519 "CMD [-features " + data + "] executed successfully!");
522 data = aparser.getValue("annotations", true);
525 af.loadJalviewDataFile(data, null, null, null);
526 // System.out.println("Added " + data);
528 "CMD [-annotations " + data + "] executed successfully!");
530 // set or clear the sortbytree flag.
531 if (aparser.contains("sortbytree"))
533 af.getViewport().setSortByTree(true);
534 if (af.getViewport().getSortByTree())
536 System.out.println("CMD [-sortbytree] executed successfully!");
539 if (aparser.contains("no-annotation"))
541 af.getViewport().setShowAnnotation(false);
542 if (!af.getViewport().isShowAnnotation())
544 System.out.println("CMD no-annotation executed successfully!");
547 if (aparser.contains("nosortbytree"))
549 af.getViewport().setSortByTree(false);
550 if (!af.getViewport().getSortByTree())
553 .println("CMD [-nosortbytree] executed successfully!");
556 data = aparser.getValue("tree", true);
562 "CMD [-tree " + data + "] executed successfully!");
563 NewickFile nf = new NewickFile(data,
564 AppletFormatAdapter.checkProtocol(data));
566 .setCurrentTree(af.showNewickTree(nf, data).getTree());
567 } catch (IOException ex)
569 System.err.println("Couldn't add tree " + data);
570 ex.printStackTrace(System.err);
573 // TODO - load PDB structure(s) to alignment JAL-629
574 // (associate with identical sequence in alignment, or a specified
576 if (groovyscript != null)
578 // Execute the groovy script after we've done all the rendering stuff
579 // and before any images or figures are generated.
580 System.out.println("Executing script " + groovyscript);
581 executeGroovyScript(groovyscript, af);
582 System.out.println("CMD groovy[" + groovyscript
583 + "] executed successfully!");
586 String imageName = "unnamed.png";
587 while (aparser.getSize() > 1)
589 String outputFormat = aparser.nextValue();
590 file = aparser.nextValue();
592 if (outputFormat.equalsIgnoreCase("png"))
594 af.createPNG(new File(file));
595 imageName = (new File(file)).getName();
596 System.out.println("Creating PNG image: " + file);
599 else if (outputFormat.equalsIgnoreCase("svg"))
601 File imageFile = new File(file);
602 imageName = imageFile.getName();
603 af.createSVG(imageFile);
604 System.out.println("Creating SVG image: " + file);
607 else if (outputFormat.equalsIgnoreCase("html"))
609 File imageFile = new File(file);
610 imageName = imageFile.getName();
611 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
612 htmlSVG.exportHTML(file);
614 System.out.println("Creating HTML image: " + file);
617 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
621 System.err.println("The output html file must not be null");
626 BioJsHTMLOutput.refreshVersionInfo(
627 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
628 } catch (URISyntaxException e)
632 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
633 bjs.exportHTML(file);
635 .println("Creating BioJS MSA Viwer HTML file: " + file);
638 else if (outputFormat.equalsIgnoreCase("imgMap"))
640 af.createImageMap(new File(file), imageName);
641 System.out.println("Creating image map: " + file);
644 else if (outputFormat.equalsIgnoreCase("eps"))
646 File outputFile = new File(file);
648 "Creating EPS file: " + outputFile.getAbsolutePath());
649 af.createEPS(outputFile);
653 if (af.saveAlignment(file, format))
655 System.out.println("Written alignment in " + format
656 + " format to " + file);
660 System.out.println("Error writing file " + file + " in "
661 + format + " format!!");
666 while (aparser.getSize() > 0)
668 System.out.println("Unknown arg: " + aparser.nextValue());
672 AlignFrame startUpAlframe = null;
673 // We'll only open the default file if the desktop is visible.
675 // ////////////////////
677 if (!headless && file == null
678 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
680 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
681 jalview.bin.Cache.getDefault("www.jalview.org",
682 "http://www.jalview.org")
683 + "/examples/exampleFile_2_7.jar");
685 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
687 // hardwire upgrade of the startup file
688 file.replace("_2_3.jar", "_2_7.jar");
689 // and remove the stale setting
690 jalview.bin.Cache.removeProperty("STARTUP_FILE");
693 protocol = DataSourceType.FILE;
695 if (file.indexOf("http:") > -1)
697 protocol = DataSourceType.URL;
700 if (file.endsWith(".jar"))
702 format = FileFormat.Jalview;
708 format = new IdentifyFile().identify(file, protocol);
709 } catch (FileFormatException e)
715 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
717 // extract groovy arguments before anything else.
720 // Once all other stuff is done, execute any groovy scripts (in order)
721 if (groovyscript != null)
723 if (Cache.groovyJarsPresent())
725 System.out.println("Executing script " + groovyscript);
726 executeGroovyScript(groovyscript, startUpAlframe);
731 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
735 // and finally, turn off batch mode indicator - if the desktop still exists
740 desktop.setProgressBar(null, progress);
742 desktop.setInBatchMode(false);
746 private static void showUsage()
749 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
750 + "-nodisplay\tRun Jalview without User Interface.\n"
751 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
752 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
753 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
754 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
755 + "-features FILE\tUse the given file to mark features on the alignment.\n"
756 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
757 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
758 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
759 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
760 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
761 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
762 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
763 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
764 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
765 + "-png FILE\tCreate PNG image FILE from alignment.\n"
766 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
767 + "-html FILE\tCreate HTML file from alignment.\n"
768 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
769 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
770 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
771 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
772 + "-noquestionnaire\tTurn off questionnaire check.\n"
773 + "-nonews\tTurn off check for Jalview news.\n"
774 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
775 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
777 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
778 // after all other properties files have been read\n\t
779 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
780 // passed in correctly)"
781 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
782 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
783 + "-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"
784 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
787 private static void startUsageStats(final Desktop desktop)
790 * start a User Config prompt asking if we can log usage statistics.
792 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
793 "USAGESTATS", "Jalview Usage Statistics",
794 "Do you want to help make Jalview better by enabling "
795 + "the collection of usage statistics with Google Analytics ?"
796 + "\n\n(you can enable or disable usage tracking in the preferences)",
803 "Initialising googletracker for usage stats.");
804 Cache.initGoogleTracker();
805 Cache.log.debug("Tracking enabled.");
812 Cache.log.debug("Not enabling Google Tracking.");
815 desktop.addDialogThread(prompter);
819 * Locate the given string as a file and pass it to the groovy interpreter.
821 * @param groovyscript
822 * the script to execute
823 * @param jalviewContext
824 * the Jalview Desktop object passed in to the groovy binding as the
827 private void executeGroovyScript(String groovyscript, AlignFrame af)
830 * for scripts contained in files
837 if (groovyscript.trim().equals("STDIN"))
839 // read from stdin into a tempfile and execute it
842 tfile = File.createTempFile("jalview", "groovy");
843 PrintWriter outfile = new PrintWriter(
844 new OutputStreamWriter(new FileOutputStream(tfile)));
845 BufferedReader br = new BufferedReader(
846 new InputStreamReader(System.in));
848 while ((line = br.readLine()) != null)
850 outfile.write(line + "\n");
856 } catch (Exception ex)
858 System.err.println("Failed to read from STDIN into tempfile "
859 + ((tfile == null) ? "(tempfile wasn't created)"
860 : tfile.toString()));
861 ex.printStackTrace();
866 sfile = tfile.toURI().toURL();
867 } catch (Exception x)
870 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
880 sfile = new URI(groovyscript).toURL();
881 } catch (Exception x)
883 tfile = new File(groovyscript);
886 System.err.println("File '" + groovyscript + "' does not exist.");
889 if (!tfile.canRead())
891 System.err.println("File '" + groovyscript + "' cannot be read.");
894 if (tfile.length() < 1)
896 System.err.println("File '" + groovyscript + "' is empty.");
901 sfile = tfile.getAbsoluteFile().toURI().toURL();
902 } catch (Exception ex)
904 System.err.println("Failed to create a file URL for "
905 + tfile.getAbsoluteFile());
912 Map<String, java.lang.Object> vbinding = new HashMap<>();
913 vbinding.put("Jalview", this);
916 vbinding.put("currentAlFrame", af);
918 Binding gbinding = new Binding(vbinding);
919 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
920 gse.run(sfile.toString(), gbinding);
921 if ("STDIN".equals(groovyscript))
923 // delete temp file that we made -
924 // only if it was successfully executed
927 } catch (Exception e)
929 System.err.println("Exception Whilst trying to execute file " + sfile
930 + " as a groovy script.");
931 e.printStackTrace(System.err);
936 public static boolean isHeadlessMode()
938 String isheadless = System.getProperty("java.awt.headless");
939 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
946 public AlignFrame[] getAlignFrames()
948 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
949 : Desktop.getAlignFrames();
954 * Quit method delegates to Desktop.quit - unless running in headless mode
955 * when it just ends the JVM
969 public static AlignFrame getCurrentAlignFrame()
971 return Jalview.currentAlignFrame;
974 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
976 Jalview.currentAlignFrame = currentAlignFrame;