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 processing
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 ArgsParser aparser = new ArgsParser(args);
209 boolean headless = false;
211 if (aparser.contains("help") || aparser.contains("h"))
216 if (aparser.contains("nodisplay") || aparser.contains("nogui")
217 || aparser.contains("headless"))
219 System.setProperty("java.awt.headless", "true");
222 String usrPropsFile = aparser.getValue("props");
223 Cache.loadProperties(usrPropsFile); // must do this before
224 if (usrPropsFile != null)
227 "CMD [-props " + usrPropsFile + "] executed successfully!");
232 final String jabawsUrl = aparser.getValue("jabaws");
233 if (jabawsUrl != null)
237 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
239 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
240 } catch (MalformedURLException e)
243 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
247 String defs = aparser.getValue("setprop");
250 int p = defs.indexOf('=');
253 System.err.println("Ignoring invalid setprop argument : " + defs);
257 System.out.println("Executing setprop argument: " + defs);
258 // DISABLED FOR SECURITY REASONS
259 // TODO: add a property to allow properties to be overriden by cli args
260 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
262 defs = aparser.getValue("setprop");
264 if (System.getProperty("java.awt.headless") != null
265 && System.getProperty("java.awt.headless").equals("true"))
269 System.setProperty("http.agent",
270 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
274 } catch (NoClassDefFoundError error)
276 error.printStackTrace();
277 System.out.println("\nEssential logging libraries not found."
278 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
286 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
287 } catch (Exception ex)
289 System.err.println("Unexpected Look and Feel Exception");
290 ex.printStackTrace();
292 if (Platform.isAMac())
295 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
297 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
299 System.setProperty("apple.laf.useScreenMenuBar", "true");
300 if (lookAndFeel != null)
304 UIManager.setLookAndFeel(lookAndFeel);
305 } catch (Throwable e)
308 "Failed to set QuaQua look and feel: " + e.toString());
311 if (lookAndFeel == null
312 || !(lookAndFeel.getClass().isAssignableFrom(
313 UIManager.getLookAndFeel().getClass()))
314 || !UIManager.getLookAndFeel().getClass().toString()
315 .toLowerCase().contains("quaqua"))
320 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
321 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
322 } catch (Throwable e)
325 "Failed to reset look and feel: " + e.toString());
331 * configure 'full' SO model if preferences say to, else use the default (SO
334 if (Cache.getDefault("USE_FULL_SO", true))
336 SequenceOntologyFactory.setInstance(new SequenceOntology());
341 desktop = new Desktop();
342 desktop.setInBatchMode(true); // indicate we are starting up
346 JalviewTaskbar.setTaskbar(this);
347 } catch (Exception e)
349 System.out.println("Cannot set Taskbar");
350 // e.printStackTrace();
351 } catch (Throwable t)
353 System.out.println("Cannot set Taskbar");
354 // t.printStackTrace();
357 desktop.setVisible(true);
358 desktop.startServiceDiscovery();
359 if (!aparser.contains("nousagestats"))
361 startUsageStats(desktop);
365 System.err.println("CMD [-nousagestats] executed successfully!");
368 if (!aparser.contains("noquestionnaire"))
370 String url = aparser.getValue("questionnaire");
373 // Start the desktop questionnaire prompter with the specified
375 Cache.log.debug("Starting questionnaire url at " + url);
376 desktop.checkForQuestionnaire(url);
378 "CMD questionnaire[-" + url + "] executed successfully!");
382 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
384 // Start the desktop questionnaire prompter with the specified
387 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
389 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
391 "Starting questionnaire with default url: " + defurl);
392 desktop.checkForQuestionnaire(defurl);
398 System.err.println("CMD [-noquestionnaire] executed successfully!");
401 if (!aparser.contains("nonews"))
403 desktop.checkForNews();
406 BioJsHTMLOutput.updateBioJS();
409 // Move any new getdown-launcher-new.jar into place over old
410 // getdown-launcher.jar
411 String appdirString = System.getProperty("getdownappdir");
412 if (appdirString != null && appdirString.length() > 0)
414 final File appdir = new File(appdirString);
420 LaunchUtil.upgradeGetdown(
421 new File(appdir, "getdown-launcher-old.jar"),
422 new File(appdir, "getdown-launcher.jar"),
423 new File(appdir, "getdown-launcher-new.jar"));
428 String file = null, data = null;
429 FileFormatI format = null;
430 DataSourceType protocol = null;
431 FileLoader fileLoader = new FileLoader(!headless);
433 String groovyscript = null; // script to execute after all loading is
434 // completed one way or another
435 // extract groovy argument and execute if necessary
436 groovyscript = aparser.getValue("groovy", true);
437 file = aparser.getValue("open", true);
439 if (file == null && desktop == null)
441 System.out.println("No files to open!");
445 // Finally, deal with the remaining input data.
450 desktop.setProgressBar(
452 .getString("status.processing_commandline_args"),
453 progress = System.currentTimeMillis());
455 System.out.println("CMD [-open " + file + "] executed successfully!");
457 if (!file.startsWith("http://"))
459 if (!(new File(file)).exists())
461 System.out.println("Can't find " + file);
469 protocol = AppletFormatAdapter.checkProtocol(file);
473 format = new IdentifyFile().identify(file, protocol);
474 } catch (FileFormatException e1)
479 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
483 System.out.println("error");
487 setCurrentAlignFrame(af);
488 data = aparser.getValue("colour", true);
491 data.replaceAll("%20", " ");
493 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
494 af.getViewport(), af.getViewport().getAlignment(), data);
499 "CMD [-color " + data + "] executed successfully!");
504 // Must maintain ability to use the groups flag
505 data = aparser.getValue("groups", true);
508 af.parseFeaturesFile(data,
509 AppletFormatAdapter.checkProtocol(data));
510 // System.out.println("Added " + data);
512 "CMD groups[-" + data + "] executed successfully!");
514 data = aparser.getValue("features", true);
517 af.parseFeaturesFile(data,
518 AppletFormatAdapter.checkProtocol(data));
519 // System.out.println("Added " + data);
521 "CMD [-features " + data + "] executed successfully!");
524 data = aparser.getValue("annotations", true);
527 af.loadJalviewDataFile(data, null, null, null);
528 // System.out.println("Added " + data);
530 "CMD [-annotations " + data + "] executed successfully!");
532 // set or clear the sortbytree flag.
533 if (aparser.contains("sortbytree"))
535 af.getViewport().setSortByTree(true);
536 if (af.getViewport().getSortByTree())
538 System.out.println("CMD [-sortbytree] executed successfully!");
541 if (aparser.contains("no-annotation"))
543 af.getViewport().setShowAnnotation(false);
544 if (!af.getViewport().isShowAnnotation())
546 System.out.println("CMD no-annotation executed successfully!");
549 if (aparser.contains("nosortbytree"))
551 af.getViewport().setSortByTree(false);
552 if (!af.getViewport().getSortByTree())
555 .println("CMD [-nosortbytree] executed successfully!");
558 data = aparser.getValue("tree", true);
564 "CMD [-tree " + data + "] executed successfully!");
565 NewickFile nf = new NewickFile(data,
566 AppletFormatAdapter.checkProtocol(data));
568 .setCurrentTree(af.showNewickTree(nf, data).getTree());
569 } catch (IOException ex)
571 System.err.println("Couldn't add tree " + data);
572 ex.printStackTrace(System.err);
575 // TODO - load PDB structure(s) to alignment JAL-629
576 // (associate with identical sequence in alignment, or a specified
578 if (groovyscript != null)
580 // Execute the groovy script after we've done all the rendering stuff
581 // and before any images or figures are generated.
582 System.out.println("Executing script " + groovyscript);
583 executeGroovyScript(groovyscript, af);
584 System.out.println("CMD groovy[" + groovyscript
585 + "] executed successfully!");
588 String imageName = "unnamed.png";
589 while (aparser.getSize() > 1)
591 String outputFormat = aparser.nextValue();
592 file = aparser.nextValue();
594 if (outputFormat.equalsIgnoreCase("png"))
596 af.createPNG(new File(file));
597 imageName = (new File(file)).getName();
598 System.out.println("Creating PNG image: " + file);
601 else if (outputFormat.equalsIgnoreCase("svg"))
603 File imageFile = new File(file);
604 imageName = imageFile.getName();
605 af.createSVG(imageFile);
606 System.out.println("Creating SVG image: " + file);
609 else if (outputFormat.equalsIgnoreCase("html"))
611 File imageFile = new File(file);
612 imageName = imageFile.getName();
613 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
614 htmlSVG.exportHTML(file);
616 System.out.println("Creating HTML image: " + file);
619 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
623 System.err.println("The output html file must not be null");
628 BioJsHTMLOutput.refreshVersionInfo(
629 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
630 } catch (URISyntaxException e)
634 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
635 bjs.exportHTML(file);
637 .println("Creating BioJS MSA Viwer HTML file: " + file);
640 else if (outputFormat.equalsIgnoreCase("imgMap"))
642 af.createImageMap(new File(file), imageName);
643 System.out.println("Creating image map: " + file);
646 else if (outputFormat.equalsIgnoreCase("eps"))
648 File outputFile = new File(file);
650 "Creating EPS file: " + outputFile.getAbsolutePath());
651 af.createEPS(outputFile);
655 if (af.saveAlignment(file, format))
657 System.out.println("Written alignment in " + format
658 + " format to " + file);
662 System.out.println("Error writing file " + file + " in "
663 + format + " format!!");
668 while (aparser.getSize() > 0)
670 System.out.println("Unknown arg: " + aparser.nextValue());
674 AlignFrame startUpAlframe = null;
675 // We'll only open the default file if the desktop is visible.
677 // ////////////////////
679 if (!headless && file == null
680 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
682 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
683 jalview.bin.Cache.getDefault("www.jalview.org",
684 "http://www.jalview.org")
685 + "/examples/exampleFile_2_7.jar");
687 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
689 // hardwire upgrade of the startup file
690 file.replace("_2_3.jar", "_2_7.jar");
691 // and remove the stale setting
692 jalview.bin.Cache.removeProperty("STARTUP_FILE");
695 protocol = DataSourceType.FILE;
697 if (file.indexOf("http:") > -1)
699 protocol = DataSourceType.URL;
702 if (file.endsWith(".jar"))
704 format = FileFormat.Jalview;
710 format = new IdentifyFile().identify(file, protocol);
711 } catch (FileFormatException e)
717 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
719 // extract groovy arguments before anything else.
722 // Once all other stuff is done, execute any groovy scripts (in order)
723 if (groovyscript != null)
725 if (Cache.groovyJarsPresent())
727 System.out.println("Executing script " + groovyscript);
728 executeGroovyScript(groovyscript, startUpAlframe);
733 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
737 // and finally, turn off batch mode indicator - if the desktop still exists
742 desktop.setProgressBar(null, progress);
744 desktop.setInBatchMode(false);
748 private static void showUsage()
751 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
752 + "-nodisplay\tRun Jalview without User Interface.\n"
753 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
754 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
755 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
756 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
757 + "-features FILE\tUse the given file to mark features on the alignment.\n"
758 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
759 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
760 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
761 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
762 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
763 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
764 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
765 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
766 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
767 + "-png FILE\tCreate PNG image FILE from alignment.\n"
768 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
769 + "-html FILE\tCreate HTML file from alignment.\n"
770 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
771 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
772 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
773 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
774 + "-noquestionnaire\tTurn off questionnaire check.\n"
775 + "-nonews\tTurn off check for Jalview news.\n"
776 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
777 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
779 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
780 // after all other properties files have been read\n\t
781 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
782 // passed in correctly)"
783 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
784 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
785 + "-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"
786 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
789 private static void startUsageStats(final Desktop desktop)
792 * start a User Config prompt asking if we can log usage statistics.
794 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
795 "USAGESTATS", "Jalview Usage Statistics",
796 "Do you want to help make Jalview better by enabling "
797 + "the collection of usage statistics with Google Analytics ?"
798 + "\n\n(you can enable or disable usage tracking in the preferences)",
805 "Initialising googletracker for usage stats.");
806 Cache.initGoogleTracker();
807 Cache.log.debug("Tracking enabled.");
814 Cache.log.debug("Not enabling Google Tracking.");
817 desktop.addDialogThread(prompter);
821 * Locate the given string as a file and pass it to the groovy interpreter.
823 * @param groovyscript
824 * the script to execute
825 * @param jalviewContext
826 * the Jalview Desktop object passed in to the groovy
827 * binding as the 'Jalview' object.
829 private void executeGroovyScript(String groovyscript, AlignFrame af)
832 * for scripts contained in files
839 if (groovyscript.trim().equals("STDIN"))
841 // read from stdin into a tempfile and execute it
844 tfile = File.createTempFile("jalview", "groovy");
845 PrintWriter outfile = new PrintWriter(
846 new OutputStreamWriter(new FileOutputStream(tfile)));
847 BufferedReader br = new BufferedReader(
848 new InputStreamReader(System.in));
850 while ((line = br.readLine()) != null)
852 outfile.write(line + "\n");
858 } catch (Exception ex)
860 System.err.println("Failed to read from STDIN into tempfile "
861 + ((tfile == null) ? "(tempfile wasn't created)"
862 : tfile.toString()));
863 ex.printStackTrace();
868 sfile = tfile.toURI().toURL();
869 } catch (Exception x)
872 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
882 sfile = new URI(groovyscript).toURL();
883 } catch (Exception x)
885 tfile = new File(groovyscript);
888 System.err.println("File '" + groovyscript + "' does not exist.");
891 if (!tfile.canRead())
893 System.err.println("File '" + groovyscript + "' cannot be read.");
896 if (tfile.length() < 1)
898 System.err.println("File '" + groovyscript + "' is empty.");
903 sfile = tfile.getAbsoluteFile().toURI().toURL();
904 } catch (Exception ex)
906 System.err.println("Failed to create a file URL for "
907 + tfile.getAbsoluteFile());
914 Map<String, java.lang.Object> vbinding = new HashMap<>();
915 vbinding.put("Jalview", this);
918 vbinding.put("currentAlFrame", af);
920 Binding gbinding = new Binding(vbinding);
921 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
922 gse.run(sfile.toString(), gbinding);
923 if ("STDIN".equals(groovyscript))
925 // delete temp file that we made -
926 // only if it was successfully executed
929 } catch (Exception e)
931 System.err.println("Exception Whilst trying to execute file " + sfile
932 + " as a groovy script.");
933 e.printStackTrace(System.err);
938 public static boolean isHeadlessMode()
940 String isheadless = System.getProperty("java.awt.headless");
941 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
948 public AlignFrame[] getAlignFrames()
950 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
951 : Desktop.getAlignFrames();
956 * Quit method delegates to Desktop.quit - unless running in headless mode when
957 * it just ends the JVM
971 public static AlignFrame getCurrentAlignFrame()
973 return Jalview.currentAlignFrame;
976 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
978 Jalview.currentAlignFrame = currentAlignFrame;