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 java.awt.Color;
24 import java.io.BufferedReader;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStreamReader;
29 import java.io.OutputStream;
30 import java.io.OutputStreamWriter;
31 import java.io.PrintStream;
32 import java.io.PrintWriter;
33 import java.net.MalformedURLException;
35 import java.net.URISyntaxException;
37 import java.security.AllPermission;
38 import java.security.CodeSource;
39 import java.security.PermissionCollection;
40 import java.security.Permissions;
41 import java.security.Policy;
42 import java.util.HashMap;
43 import java.util.Locale;
45 import java.util.Properties;
46 import java.util.Vector;
47 import java.util.logging.ConsoleHandler;
48 import java.util.logging.Level;
49 import java.util.logging.Logger;
51 import javax.swing.JDialog;
52 import javax.swing.JFrame;
53 import javax.swing.JOptionPane;
54 import javax.swing.SwingUtilities;
55 import javax.swing.UIManager;
56 import javax.swing.UIManager.LookAndFeelInfo;
57 import javax.swing.UnsupportedLookAndFeelException;
59 import com.formdev.flatlaf.FlatLightLaf;
60 import com.formdev.flatlaf.themes.FlatMacLightLaf;
61 import com.formdev.flatlaf.util.SystemInfo;
62 import com.threerings.getdown.util.LaunchUtil;
64 //import edu.stanford.ejalbert.launching.IBrowserLaunching;
65 import groovy.lang.Binding;
66 import groovy.util.GroovyScriptEngine;
67 import jalview.bin.argparser.Arg;
68 import jalview.bin.argparser.ArgParser;
69 import jalview.bin.argparser.BootstrapArgs;
70 import jalview.ext.so.SequenceOntology;
71 import jalview.gui.AlignFrame;
72 import jalview.gui.Desktop;
73 import jalview.gui.PromptUserConfig;
74 import jalview.gui.QuitHandler;
75 import jalview.gui.QuitHandler.QResponse;
76 import jalview.io.AppletFormatAdapter;
77 import jalview.io.BioJsHTMLOutput;
78 import jalview.io.DataSourceType;
79 import jalview.io.FileFormat;
80 import jalview.io.FileFormatException;
81 import jalview.io.FileFormatI;
82 import jalview.io.FileFormats;
83 import jalview.io.FileLoader;
84 import jalview.io.HtmlSvgOutput;
85 import jalview.io.IdentifyFile;
86 import jalview.io.NewickFile;
87 import jalview.io.gff.SequenceOntologyFactory;
88 import jalview.schemes.ColourSchemeI;
89 import jalview.schemes.ColourSchemeProperty;
90 import jalview.util.ChannelProperties;
91 import jalview.util.HttpUtils;
92 import jalview.util.LaunchUtils;
93 import jalview.util.MessageManager;
94 import jalview.util.Platform;
95 import jalview.ws.jws2.Jws2Discoverer;
98 * Main class for Jalview Application <br>
100 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
101 * jalview.bin.Jalview
103 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
104 * jalview.bin.Jalview jalview.bin.Jalview
106 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
107 * embellish '*' to e.g. '*.jar')
110 * @version $Revision$
116 Platform.getURLCommandArguments();
117 Platform.addJ2SDirectDatabaseCall("https://www.jalview.org");
118 Platform.addJ2SDirectDatabaseCall("http://www.jalview.org");
119 Platform.addJ2SDirectDatabaseCall("http://www.compbio.dundee.ac.uk");
120 Platform.addJ2SDirectDatabaseCall("https://www.compbio.dundee.ac.uk");
124 * singleton instance of this class
126 private static Jalview instance;
128 private Desktop desktop;
130 protected Commands cmds;
132 public static AlignFrame currentAlignFrame;
136 if (!Platform.isJS())
143 // grab all the rights we can for the JVM
144 Policy.setPolicy(new Policy()
147 public PermissionCollection getPermissions(CodeSource codesource)
149 Permissions perms = new Permissions();
150 perms.add(new AllPermission());
155 public void refresh()
163 * keep track of feature fetching tasks.
171 * TODO: generalise to track all jalview events to orchestrate batch processing
175 private int queued = 0;
177 private int running = 0;
179 public FeatureFetcher()
184 public void addFetcher(final AlignFrame af,
185 final Vector<String> dasSources)
187 final long id = System.currentTimeMillis();
189 final FeatureFetcher us = this;
190 new Thread(new Runnable()
202 af.setProgressBar(MessageManager
203 .getString("status.das_features_being_retrived"), id);
204 af.featureSettings_actionPerformed(null);
205 af.setProgressBar(null, id);
214 public synchronized boolean allFinished()
216 return queued == 0 && running == 0;
221 public static Jalview getInstance()
227 * main class for Jalview application
230 * open <em>filename</em>
232 public static void main(String[] args)
234 // setLogging(); // BH - for event debugging in JavaScript
235 instance = new Jalview();
236 instance.doMain(args);
239 private static void logClass(String name)
241 // BH - for event debugging in JavaScript
242 ConsoleHandler consoleHandler = new ConsoleHandler();
243 consoleHandler.setLevel(Level.ALL);
244 Logger logger = Logger.getLogger(name);
245 logger.setLevel(Level.ALL);
246 logger.addHandler(consoleHandler);
249 @SuppressWarnings("unused")
250 private static void setLogging()
258 System.out.println("not in js");
261 // BH - for event debugging in JavaScript (Java mode only)
262 if (!Platform.isJS())
269 Logger.getLogger("").setLevel(Level.ALL);
270 logClass("java.awt.EventDispatchThread");
271 logClass("java.awt.EventQueue");
272 logClass("java.awt.Component");
273 logClass("java.awt.focus.Component");
274 logClass("java.awt.focus.DefaultKeyboardFocusManager");
282 void doMain(String[] args)
285 if (!Platform.isJS())
287 System.setSecurityManager(null);
290 // Move any new getdown-launcher-new.jar into place over old
291 // getdown-launcher.jar
292 String appdirString = System.getProperty("getdownappdir");
293 if (appdirString != null && appdirString.length() > 0)
295 final File appdir = new File(appdirString);
301 LaunchUtil.upgradeGetdown(
302 new File(appdir, "getdown-launcher-old.jar"),
303 new File(appdir, "getdown-launcher.jar"),
304 new File(appdir, "getdown-launcher-new.jar"));
309 // get args needed before proper ArgParser
310 BootstrapArgs bootstrapArgs = BootstrapArgs.getBootstrapArgs(args);
312 if (!Platform.isJS())
314 // are we being --quiet ?
315 if (bootstrapArgs.contains(Arg.QUIET))
317 OutputStream devNull = new OutputStream()
320 public void write(int b)
325 System.setOut(new PrintStream(devNull));
326 // redirecting stderr not working
327 if (bootstrapArgs.getList(Arg.QUIET).size() > 1)
329 System.setErr(new PrintStream(devNull));
335 .println("Java version: " + System.getProperty("java.version"));
336 System.out.println("Java Home: " + System.getProperty("java.home"));
337 System.out.println(System.getProperty("os.arch") + " "
338 + System.getProperty("os.name") + " "
339 + System.getProperty("os.version"));
341 String val = System.getProperty("sys.install4jVersion");
344 System.out.println("Install4j version: " + val);
346 val = System.getProperty("installer_template_version");
349 System.out.println("Install4j template version: " + val);
351 val = System.getProperty("launcher_version");
354 System.out.println("Launcher version: " + val);
357 if (Platform.isLinux() && LaunchUtils.getJavaVersion() < 11)
359 System.setProperty("flatlaf.uiScale", "1");
362 // get bootstrap properties (mainly for the logger level)
363 Properties bootstrapProperties = Cache
364 .bootstrapProperties(bootstrapArgs.get(Arg.PROPS));
366 // report Jalview version
367 Cache.loadBuildProperties(true);
370 ArgsParser aparser = new ArgsParser(args);
373 boolean headless = false;
375 boolean headlessArg = false;
379 String logLevel = bootstrapArgs.contains(Arg.DEBUG) ? "DEBUG" : null;
380 if (logLevel == null && !(bootstrapProperties == null))
382 logLevel = bootstrapProperties.getProperty(Cache.JALVIEWLOGLEVEL);
384 Console.initLogger(logLevel);
385 } catch (NoClassDefFoundError error)
387 error.printStackTrace();
388 String message = "\nEssential logging libraries not found."
389 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
390 Jalview.exit(message, 0);
393 // register SIGTERM listener
394 Runtime.getRuntime().addShutdownHook(new Thread()
398 Console.debug("Running shutdown hook");
399 if (QuitHandler.gotQuitResponse() == QResponse.CANCEL_QUIT)
401 // Got to here by a SIGTERM signal.
402 // Note we will not actually cancel the quit from here -- it's too
403 // late -- but we can wait for saving files.
404 Console.debug("Checking for saving files");
405 QuitHandler.getQuitResponse(false);
409 Console.debug("Nothing more to do");
411 Console.debug("Exiting, bye!");
412 // shutdownHook cannot be cancelled, JVM will now halt
416 String usrPropsFile = bootstrapArgs.contains(Arg.PROPS)
417 ? bootstrapArgs.get(Arg.PROPS)
418 : aparser.getValue("props");
419 if (usrPropsFile != null)
421 Cache.loadProperties(usrPropsFile);
423 "CMD [-props " + usrPropsFile + "] executed successfully!");
428 // --argfile=... -- OVERRIDES ALL NON-BOOTSTRAP ARGS
429 if (bootstrapArgs.contains(Arg.ARGFILE))
431 argparser = ArgParser
432 .parseArgFiles(bootstrapArgs.getList(Arg.ARGFILE));
436 argparser = new ArgParser(args);
439 if (!Platform.isJS())
446 if (aparser.contains("help") || aparser.contains("h")
447 || argparser.getBool(Arg.HELP))
450 Jalview.exit(null, 0);
453 if (bootstrapArgs.contains(Arg.HEADLESS))
455 System.setProperty("java.awt.headless", "true");
457 headlessArg = argparser.getBool(Arg.HEADLESS);
459 if (aparser.contains("nodisplay") || aparser.contains("nogui")
460 || aparser.contains("headless"))
462 System.setProperty("java.awt.headless", "true");
468 // allow https handshakes to download intermediate certs if necessary
469 System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
471 final String jabawsUrl = aparser.getValue("jabaws");
472 if (jabawsUrl != null)
476 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
478 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
479 } catch (MalformedURLException e)
482 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
487 String defs = aparser.getValue("setprop");
490 int p = defs.indexOf('=');
493 System.err.println("Ignoring invalid setprop argument : " + defs);
497 System.out.println("Executing setprop argument: " + defs);
500 Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
502 // DISABLED FOR SECURITY REASONS
503 // TODO: add a property to allow properties to be overriden by cli args
504 // Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
506 defs = aparser.getValue("setprop");
508 if (System.getProperty("java.awt.headless") != null
509 && System.getProperty("java.awt.headless").equals("true"))
513 System.setProperty("http.agent",
514 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
518 Console.initLogger();
521 NoClassDefFoundError error)
523 error.printStackTrace();
524 String message = "\nEssential logging libraries not found."
525 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
526 Jalview.exit(message, 0);
530 if (!(headless || headlessArg))
534 * configure 'full' SO model if preferences say to, else use the default (full SO)
535 * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
537 boolean soDefault = !Platform.isJS();
538 if (Cache.getDefault("USE_FULL_SO", soDefault))
540 SequenceOntologyFactory.setInstance(new SequenceOntology());
543 if (!(headless || headlessArg))
545 Desktop.nosplash = aparser.contains("nosplash");
546 desktop = new Desktop();
547 desktop.setInBatchMode(true); // indicate we are starting up
551 JalviewTaskbar.setTaskbar(this);
552 } catch (Exception e)
554 Console.info("Cannot set Taskbar");
555 Console.error(e.getMessage());
556 // e.printStackTrace();
557 } catch (Throwable t)
559 Console.info("Cannot set Taskbar");
560 Console.error(t.getMessage());
561 // t.printStackTrace();
564 // set Proxy settings before all the internet calls
565 Cache.setProxyPropertiesFromPreferences();
567 desktop.setVisible(true);
569 if (!Platform.isJS())
578 * Check to see that the JVM version being run is suitable for the Java
579 * version this Jalview was compiled for. Popup a warning if not.
581 if (!LaunchUtils.checkJavaVersion())
583 Console.warn("The Java version being used (Java "
584 + LaunchUtils.getJavaVersion()
585 + ") may lead to problems. This installation of Jalview should be used with Java "
586 + LaunchUtils.getJavaCompileVersion() + ".");
589 .getBooleanUserPreference("IGNORE_JVM_WARNING_POPUP"))
592 MessageManager.getString("label.continue") };
593 JOptionPane.showOptionDialog(null,
594 MessageManager.formatMessage(
595 "warning.wrong_jvm_version_message",
596 LaunchUtils.getJavaVersion(),
597 LaunchUtils.getJavaCompileVersion()),
599 .getString("warning.wrong_jvm_version_title"),
600 JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
601 null, options, options[0]);
605 if (!aparser.contains("nowebservicediscovery"))
607 desktop.startServiceDiscovery();
609 if (!aparser.contains("nousagestats"))
611 startUsageStats(desktop);
615 System.err.println("CMD [-nousagestats] executed successfully!");
618 if (!aparser.contains("noquestionnaire"))
620 String url = aparser.getValue("questionnaire");
623 // Start the desktop questionnaire prompter with the specified
625 Console.debug("Starting questionnaire url at " + url);
626 desktop.checkForQuestionnaire(url);
627 System.out.println("CMD questionnaire[-" + url
628 + "] executed successfully!");
632 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
634 // Start the desktop questionnaire prompter with the specified
637 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
639 String defurl = "https://www.jalview.org/cgi-bin/questionnaire.pl";
641 "Starting questionnaire with default url: " + defurl);
642 desktop.checkForQuestionnaire(defurl);
649 .println("CMD [-noquestionnaire] executed successfully!");
652 if (!aparser.contains("nonews")
653 || Cache.getProperty("NONEWS") == null)
655 desktop.checkForNews();
658 if (!aparser.contains("nohtmltemplates")
659 || Cache.getProperty("NOHTMLTEMPLATES") == null)
661 BioJsHTMLOutput.updateBioJS();
665 // Run Commands from cli
666 cmds = new Commands(argparser, headlessArg);
667 boolean commandsSuccess = cmds.argsWereParsed();
672 Jalview.exit("Successfully completed commands in headless mode", 0);
674 Console.info("Successfully completed commands");
680 Jalview.exit("Error when running Commands in headless mode", 1);
682 Console.warn("Error when running commands");
685 // Check if JVM and compile version might cause problems and log if it
687 if (headless && !Platform.isJS() && !LaunchUtils.checkJavaVersion())
689 Console.warn("The Java version being used (Java "
690 + LaunchUtils.getJavaVersion()
691 + ") may lead to problems. This installation of Jalview should be used with Java "
692 + LaunchUtils.getJavaCompileVersion() + ".");
695 String file = null, data = null;
697 FileFormatI format = null;
699 DataSourceType protocol = null;
701 FileLoader fileLoader = new FileLoader(!headless);
703 String groovyscript = null; // script to execute after all loading is
704 // completed one way or another
705 // extract groovy argument and execute if necessary
706 groovyscript = aparser.getValue("groovy", true);
707 file = aparser.getValue("open", true);
709 if (file == null && desktop == null && !commandsSuccess)
711 Jalview.exit("No files to open!", 1);
715 // Finally, deal with the remaining input data.
720 desktop.setProgressBar(
722 .getString("status.processing_commandline_args"),
723 progress = System.currentTimeMillis());
725 System.out.println("CMD [-open " + file + "] executed successfully!");
727 if (!Platform.isJS())
729 * ignore in JavaScript -- can't just file existence - could load it?
734 if (!HttpUtils.startsWithHttpOrHttps(file))
736 if (!(new File(file)).exists())
741 "Can't find file '" + file + "' in headless mode", 1);
743 Console.warn("Can't find file'" + file + "'");
748 protocol = AppletFormatAdapter.checkProtocol(file);
752 format = new IdentifyFile().identify(file, protocol);
753 } catch (FileFormatException e1)
758 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
762 System.out.println("error");
766 setCurrentAlignFrame(af);
767 data = aparser.getValue("colour", true);
770 data.replaceAll("%20", " ");
772 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
773 af.getViewport(), af.getViewport().getAlignment(), data);
778 "CMD [-colour " + data + "] executed successfully!");
783 // Must maintain ability to use the groups flag
784 data = aparser.getValue("groups", true);
787 af.parseFeaturesFile(data,
788 AppletFormatAdapter.checkProtocol(data));
789 // System.out.println("Added " + data);
791 "CMD groups[-" + data + "] executed successfully!");
793 data = aparser.getValue("features", true);
796 af.parseFeaturesFile(data,
797 AppletFormatAdapter.checkProtocol(data));
798 // System.out.println("Added " + data);
800 "CMD [-features " + data + "] executed successfully!");
803 data = aparser.getValue("annotations", true);
806 af.loadJalviewDataFile(data, null, null, null);
807 // System.out.println("Added " + data);
809 "CMD [-annotations " + data + "] executed successfully!");
811 // set or clear the sortbytree flag.
812 if (aparser.contains("sortbytree"))
814 af.getViewport().setSortByTree(true);
815 if (af.getViewport().getSortByTree())
817 System.out.println("CMD [-sortbytree] executed successfully!");
820 if (aparser.contains("no-annotation"))
822 af.getViewport().setShowAnnotation(false);
823 if (!af.getViewport().isShowAnnotation())
825 System.out.println("CMD no-annotation executed successfully!");
828 if (aparser.contains("nosortbytree"))
830 af.getViewport().setSortByTree(false);
831 if (!af.getViewport().getSortByTree())
834 .println("CMD [-nosortbytree] executed successfully!");
837 data = aparser.getValue("tree", true);
843 "CMD [-tree " + data + "] executed successfully!");
844 NewickFile nf = new NewickFile(data,
845 AppletFormatAdapter.checkProtocol(data));
847 .setCurrentTree(af.showNewickTree(nf, data).getTree());
848 } catch (IOException ex)
850 System.err.println("Couldn't add tree " + data);
851 ex.printStackTrace(System.err);
854 // TODO - load PDB structure(s) to alignment JAL-629
855 // (associate with identical sequence in alignment, or a specified
857 if (groovyscript != null)
859 // Execute the groovy script after we've done all the rendering stuff
860 // and before any images or figures are generated.
861 System.out.println("Executing script " + groovyscript);
862 executeGroovyScript(groovyscript, af);
863 System.out.println("CMD groovy[" + groovyscript
864 + "] executed successfully!");
867 String imageName = "unnamed.png";
868 while (aparser.getSize() > 1)
870 String outputFormat = aparser.nextValue();
871 file = aparser.nextValue();
873 if (outputFormat.equalsIgnoreCase("png"))
875 af.createPNG(new File(file));
876 imageName = (new File(file)).getName();
877 System.out.println("Creating PNG image: " + file);
880 else if (outputFormat.equalsIgnoreCase("svg"))
882 File imageFile = new File(file);
883 imageName = imageFile.getName();
884 af.createSVG(imageFile);
885 System.out.println("Creating SVG image: " + file);
888 else if (outputFormat.equalsIgnoreCase("html"))
890 File imageFile = new File(file);
891 imageName = imageFile.getName();
892 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
893 htmlSVG.exportHTML(file);
895 System.out.println("Creating HTML image: " + file);
898 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
902 System.err.println("The output html file must not be null");
907 BioJsHTMLOutput.refreshVersionInfo(
908 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
909 } catch (URISyntaxException e)
913 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
914 bjs.exportHTML(file);
916 .println("Creating BioJS MSA Viwer HTML file: " + file);
919 else if (outputFormat.equalsIgnoreCase("imgMap"))
921 af.createImageMap(new File(file), imageName);
922 System.out.println("Creating image map: " + file);
925 else if (outputFormat.equalsIgnoreCase("eps"))
927 File outputFile = new File(file);
929 "Creating EPS file: " + outputFile.getAbsolutePath());
930 af.createEPS(outputFile);
933 FileFormatI outFormat = null;
936 outFormat = FileFormats.getInstance().forName(outputFormat);
937 } catch (Exception formatP)
939 System.out.println("Couldn't parse " + outFormat
940 + " as a valid Jalview format string.");
942 if (outFormat != null)
944 if (!outFormat.isWritable())
947 "This version of Jalview does not support alignment export as "
952 af.saveAlignment(file, outFormat);
953 if (af.isSaveAlignmentSuccessful())
955 System.out.println("Written alignment in "
956 + outFormat.getName() + " format to " + file);
960 System.out.println("Error writing file " + file + " in "
961 + outFormat.getName() + " format!!");
968 while (aparser.getSize() > 0)
970 System.out.println("Unknown arg: " + aparser.nextValue());
975 AlignFrame startUpAlframe = null;
976 // We'll only open the default file if the desktop is visible.
978 // ////////////////////
980 if (!Platform.isJS() && !headless && file == null
981 && Cache.getDefault("SHOW_STARTUP_FILE", true)
982 && !cmds.commandArgsProvided())
983 // don't open the startup file if command line args have been processed
984 // (&& !Commands.commandArgsProvided())
991 file = Cache.getDefault("STARTUP_FILE",
992 Cache.getDefault("www.jalview.org", "https://www.jalview.org")
993 + "/examples/exampleFile_2_7.jvp");
994 if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar")
996 "http://www.jalview.org/examples/exampleFile_2_7.jar"))
998 file.replace("http:", "https:");
999 // hardwire upgrade of the startup file
1000 file.replace("_2_3", "_2_7");
1001 file.replace("2_7.jar", "2_7.jvp");
1002 // and remove the stale setting
1003 Cache.removeProperty("STARTUP_FILE");
1006 protocol = AppletFormatAdapter.checkProtocol(file);
1008 if (file.endsWith(".jar"))
1010 format = FileFormat.Jalview;
1016 format = new IdentifyFile().identify(file, protocol);
1017 } catch (FileFormatException e)
1023 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
1025 // don't ask to save when quitting if only the startup file has been
1027 Console.debug("Resetting up-to-date flag for startup file");
1028 startUpAlframe.getViewport().setSavedUpToDate(true);
1029 // extract groovy arguments before anything else.
1032 // Once all other stuff is done, execute any groovy scripts (in order)
1033 if (groovyscript != null)
1035 if (Cache.groovyJarsPresent())
1037 System.out.println("Executing script " + groovyscript);
1038 executeGroovyScript(groovyscript, startUpAlframe);
1043 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
1047 // and finally, turn off batch mode indicator - if the desktop still exists
1048 if (desktop != null)
1052 desktop.setProgressBar(null, progress);
1054 desktop.setInBatchMode(false);
1058 private static void setLookAndFeel()
1060 // property laf = "crossplatform", "system", "gtk", "metal", "nimbus",
1062 // If not set (or chosen laf fails), use the normal SystemLaF and if on Mac,
1063 // try Quaqua/Vaqua.
1064 String lafProp = System.getProperty("laf");
1065 String lafSetting = Cache.getDefault("PREFERRED_LAF", null);
1066 String laf = "none";
1067 if (lafProp != null)
1071 else if (lafSetting != null)
1075 boolean lafSet = false;
1078 case "crossplatform":
1079 lafSet = setCrossPlatformLookAndFeel();
1082 Console.error("Could not set requested laf=" + laf);
1086 lafSet = setSystemLookAndFeel();
1089 Console.error("Could not set requested laf=" + laf);
1093 lafSet = setGtkLookAndFeel();
1096 Console.error("Could not set requested laf=" + laf);
1100 lafSet = setMetalLookAndFeel();
1103 Console.error("Could not set requested laf=" + laf);
1107 lafSet = setNimbusLookAndFeel();
1110 Console.error("Could not set requested laf=" + laf);
1114 lafSet = setFlatLookAndFeel();
1117 Console.error("Could not set requested laf=" + laf);
1121 lafSet = setMacLookAndFeel();
1124 Console.error("Could not set requested laf=" + laf);
1130 Console.error("Requested laf=" + laf + " not implemented");
1134 setSystemLookAndFeel();
1135 if (Platform.isLinux())
1137 setLinuxLookAndFeel();
1139 if (Platform.isMac())
1141 setMacLookAndFeel();
1146 private static boolean setCrossPlatformLookAndFeel()
1148 boolean set = false;
1151 UIManager.setLookAndFeel(
1152 UIManager.getCrossPlatformLookAndFeelClassName());
1154 } catch (Exception ex)
1156 Console.error("Unexpected Look and Feel Exception");
1157 Console.error(ex.getMessage());
1158 Console.debug(Cache.getStackTraceString(ex));
1163 private static boolean setSystemLookAndFeel()
1165 boolean set = false;
1168 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1170 } catch (Exception ex)
1172 Console.error("Unexpected Look and Feel Exception");
1173 Console.error(ex.getMessage());
1174 Console.debug(Cache.getStackTraceString(ex));
1179 private static boolean setSpecificLookAndFeel(String name,
1180 String className, boolean nameStartsWith)
1182 boolean set = false;
1185 for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
1187 if (info.getName() != null && nameStartsWith
1188 ? info.getName().toLowerCase(Locale.ROOT)
1189 .startsWith(name.toLowerCase(Locale.ROOT))
1190 : info.getName().toLowerCase(Locale.ROOT)
1191 .equals(name.toLowerCase(Locale.ROOT)))
1193 className = info.getClassName();
1197 UIManager.setLookAndFeel(className);
1199 } catch (Exception ex)
1201 Console.error("Unexpected Look and Feel Exception");
1202 Console.error(ex.getMessage());
1203 Console.debug(Cache.getStackTraceString(ex));
1208 private static boolean setGtkLookAndFeel()
1210 return setSpecificLookAndFeel("gtk",
1211 "com.sun.java.swing.plaf.gtk.GTKLookAndFeel", true);
1214 private static boolean setMetalLookAndFeel()
1216 return setSpecificLookAndFeel("metal",
1217 "javax.swing.plaf.metal.MetalLookAndFeel", false);
1220 private static boolean setNimbusLookAndFeel()
1222 return setSpecificLookAndFeel("nimbus",
1223 "javax.swing.plaf.nimbus.NimbusLookAndFeel", false);
1226 private static boolean setFlatLookAndFeel()
1228 boolean set = false;
1229 if (SystemInfo.isMacOS)
1233 UIManager.setLookAndFeel(
1234 "com.formdev.flatlaf.themes.FlatMacLightLaf");
1236 Console.debug("Using FlatMacLightLaf");
1237 } catch (ClassNotFoundException | InstantiationException
1238 | IllegalAccessException | UnsupportedLookAndFeelException e)
1240 Console.debug("Exception loading FlatLightLaf", e);
1242 System.setProperty("apple.laf.useScreenMenuBar", "true");
1243 System.setProperty("apple.awt.application.name",
1244 ChannelProperties.getProperty("app_name"));
1245 System.setProperty("apple.awt.application.appearance", "system");
1246 if (SystemInfo.isMacFullWindowContentSupported
1247 && Desktop.desktop != null)
1249 Console.debug("Setting transparent title bar");
1250 Desktop.desktop.getRootPane()
1251 .putClientProperty("apple.awt.fullWindowContent", true);
1252 Desktop.desktop.getRootPane()
1253 .putClientProperty("apple.awt.transparentTitleBar", true);
1254 Desktop.desktop.getRootPane()
1255 .putClientProperty("apple.awt.fullscreenable", true);
1257 SwingUtilities.invokeLater(() -> {
1258 FlatMacLightLaf.setup();
1260 Console.debug("Using FlatMacLightLaf");
1267 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1269 Console.debug("Using FlatLightLaf");
1270 } catch (ClassNotFoundException | InstantiationException
1271 | IllegalAccessException | UnsupportedLookAndFeelException e)
1273 Console.debug("Exception loading FlatLightLaf", e);
1275 // Windows specific properties here
1276 SwingUtilities.invokeLater(() -> {
1277 FlatLightLaf.setup();
1279 Console.debug("Using FlatLightLaf");
1282 else if (SystemInfo.isLinux)
1286 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1288 Console.debug("Using FlatLightLaf");
1289 } catch (ClassNotFoundException | InstantiationException
1290 | IllegalAccessException | UnsupportedLookAndFeelException e)
1292 Console.debug("Exception loading FlatLightLaf", e);
1294 // enable custom window decorations
1295 JFrame.setDefaultLookAndFeelDecorated(true);
1296 JDialog.setDefaultLookAndFeelDecorated(true);
1297 SwingUtilities.invokeLater(() -> {
1298 FlatLightLaf.setup();
1300 Console.debug("Using FlatLightLaf");
1308 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1310 Console.debug("Using FlatLightLaf");
1311 } catch (ClassNotFoundException | InstantiationException
1312 | IllegalAccessException | UnsupportedLookAndFeelException e)
1314 Console.debug("Exception loading FlatLightLaf", e);
1320 UIManager.put("TabbedPane.tabType", "card");
1321 UIManager.put("TabbedPane.showTabSeparators", true);
1322 UIManager.put("TabbedPane.showContentSeparator", true);
1323 UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
1324 UIManager.put("TabbedPane.tabsOverlapBorder", true);
1325 UIManager.put("TabbedPane.hasFullBorder", true);
1326 UIManager.put("TabbedPane.tabLayoutPolicy", "scroll");
1327 UIManager.put("TabbedPane.scrollButtonsPolicy", "asNeeded");
1328 UIManager.put("TabbedPane.smoothScrolling", true);
1329 UIManager.put("TabbedPane.tabWidthMode", "compact");
1330 UIManager.put("TabbedPane.selectedBackground", Color.white);
1333 Desktop.setLiveDragMode(Cache.getDefault("FLAT_LIVE_DRAG_MODE", true));
1337 private static boolean setMacLookAndFeel()
1339 boolean set = false;
1340 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
1341 ChannelProperties.getProperty("app_name"));
1342 System.setProperty("apple.laf.useScreenMenuBar", "true");
1344 * broken native LAFs on (ARM?) macbooks
1345 set = setQuaquaLookAndFeel();
1346 if ((!set) || !UIManager.getLookAndFeel().getClass().toString()
1347 .toLowerCase(Locale.ROOT).contains("quaqua"))
1349 set = setVaquaLookAndFeel();
1352 set = setFlatLookAndFeel();
1356 private static boolean setLinuxLookAndFeel()
1358 boolean set = false;
1359 set = setFlatLookAndFeel();
1361 set = setMetalLookAndFeel();
1362 // avoid GtkLookAndFeel -- not good results especially on HiDPI
1364 set = setNimbusLookAndFeel();
1368 private static void showUsage()
1371 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1372 + "-nodisplay\tRun Jalview without User Interface.\n"
1373 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1374 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1375 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1376 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1377 + "-features FILE\tUse the given file to mark features on the alignment.\n"
1378 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1379 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1380 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1381 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1382 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1383 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1384 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1385 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1386 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1387 + "-png FILE\tCreate PNG image FILE from alignment.\n"
1388 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1389 + "-html FILE\tCreate HTML file from alignment.\n"
1390 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1391 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1392 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1393 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1394 + "-noquestionnaire\tTurn off questionnaire check.\n"
1395 + "-nonews\tTurn off check for Jalview news.\n"
1396 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1397 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1399 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1400 // after all other properties files have been read\n\t
1401 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1402 // passed in correctly)"
1403 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1404 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1405 + "-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"
1406 + "-jvmmempc=PERCENT\tOnly available with standalone executable jar or jalview.bin.Launcher. Limit maximum heap size (memory) to PERCENT% of total physical memory detected. This defaults to 90 if total physical memory can be detected. See https://www.jalview.org/help/html/memory.html for more details.\n"
1407 + "-jvmmemmax=MAXMEMORY\tOnly available with standalone executable jar or jalview.bin.Launcher. Limit maximum heap size (memory) to MAXMEMORY. MAXMEMORY can be specified in bytes, kilobytes(k), megabytes(m), gigabytes(g) or if you're lucky enough, terabytes(t). This defaults to 32g if total physical memory can be detected, or to 8g if total physical memory cannot be detected. See https://www.jalview.org/help/html/memory.html for more details.\n"
1408 + "\n~Read documentation in Application or visit https://www.jalview.org for description of Features and Annotations file~\n\n");
1411 private static void startUsageStats(final Desktop desktop)
1414 * start a User Config prompt asking if we can log usage statistics.
1416 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1417 "USAGESTATS", "Jalview Usage Statistics",
1418 "Do you want to help make Jalview better by enabling "
1419 + "the collection of usage statistics with Google Analytics ?"
1420 + "\n\n(you can enable or disable usage tracking in the preferences)",
1427 "Initialising googletracker for usage stats.");
1428 Cache.initGoogleTracker();
1429 Console.debug("Tracking enabled.");
1436 Console.debug("Not enabling Google Tracking.");
1439 desktop.addDialogThread(prompter);
1443 * Locate the given string as a file and pass it to the groovy interpreter.
1445 * @param groovyscript
1446 * the script to execute
1447 * @param jalviewContext
1448 * the Jalview Desktop object passed in to the groovy binding as the
1451 private void executeGroovyScript(String groovyscript, AlignFrame af)
1454 * for scripts contained in files
1461 if (groovyscript.trim().equals("STDIN"))
1463 // read from stdin into a tempfile and execute it
1466 tfile = File.createTempFile("jalview", "groovy");
1467 PrintWriter outfile = new PrintWriter(
1468 new OutputStreamWriter(new FileOutputStream(tfile)));
1469 BufferedReader br = new BufferedReader(
1470 new InputStreamReader(System.in));
1472 while ((line = br.readLine()) != null)
1474 outfile.write(line + "\n");
1480 } catch (Exception ex)
1482 System.err.println("Failed to read from STDIN into tempfile "
1483 + ((tfile == null) ? "(tempfile wasn't created)"
1484 : tfile.toString()));
1485 ex.printStackTrace();
1490 sfile = tfile.toURI().toURL();
1491 } catch (Exception x)
1494 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1496 x.printStackTrace();
1504 sfile = new URI(groovyscript).toURL();
1505 } catch (Exception x)
1507 tfile = new File(groovyscript);
1508 if (!tfile.exists())
1510 System.err.println("File '" + groovyscript + "' does not exist.");
1513 if (!tfile.canRead())
1515 System.err.println("File '" + groovyscript + "' cannot be read.");
1518 if (tfile.length() < 1)
1520 System.err.println("File '" + groovyscript + "' is empty.");
1525 sfile = tfile.getAbsoluteFile().toURI().toURL();
1526 } catch (Exception ex)
1528 System.err.println("Failed to create a file URL for "
1529 + tfile.getAbsoluteFile());
1536 Map<String, java.lang.Object> vbinding = new HashMap<>();
1537 vbinding.put("Jalview", this);
1540 vbinding.put("currentAlFrame", af);
1542 Binding gbinding = new Binding(vbinding);
1543 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1544 gse.run(sfile.toString(), gbinding);
1545 if ("STDIN".equals(groovyscript))
1547 // delete temp file that we made -
1548 // only if it was successfully executed
1551 } catch (Exception e)
1553 System.err.println("Exception Whilst trying to execute file " + sfile
1554 + " as a groovy script.");
1555 e.printStackTrace(System.err);
1560 public static boolean isHeadlessMode()
1562 String isheadless = System.getProperty("java.awt.headless");
1563 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1570 public AlignFrame[] getAlignFrames()
1572 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1573 : Desktop.getAlignFrames();
1578 * jalview.bin.Jalview.quit() will just run the non-GUI shutdownHook and exit
1582 // System.exit will run the shutdownHook first
1583 Jalview.exit("Quitting now. Bye!", 0);
1586 public static AlignFrame getCurrentAlignFrame()
1588 return Jalview.currentAlignFrame;
1591 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1593 Jalview.currentAlignFrame = currentAlignFrame;
1596 protected Commands getCommands()
1601 public static void exit(String message, int exitcode)
1603 Console.debug("Using Jalview.exit");
1604 if (message != null)
1606 Console.info(message);
1608 Console.error(message);
1610 System.exit(exitcode);