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.ArrayList;
43 import java.util.HashMap;
44 import java.util.List;
45 import java.util.Locale;
47 import java.util.Properties;
48 import java.util.Vector;
49 import java.util.logging.ConsoleHandler;
50 import java.util.logging.Level;
51 import java.util.logging.Logger;
53 import javax.swing.JDialog;
54 import javax.swing.JFrame;
55 import javax.swing.JOptionPane;
56 import javax.swing.SwingUtilities;
57 import javax.swing.UIManager;
58 import javax.swing.UIManager.LookAndFeelInfo;
59 import javax.swing.UnsupportedLookAndFeelException;
61 import com.formdev.flatlaf.FlatLightLaf;
62 import com.formdev.flatlaf.themes.FlatMacLightLaf;
63 import com.formdev.flatlaf.util.SystemInfo;
64 import com.threerings.getdown.util.LaunchUtil;
66 //import edu.stanford.ejalbert.launching.IBrowserLaunching;
67 import groovy.lang.Binding;
68 import groovy.util.GroovyScriptEngine;
69 import jalview.bin.argparser.Arg;
70 import jalview.bin.argparser.ArgParser;
71 import jalview.bin.argparser.BootstrapArgs;
72 import jalview.ext.so.SequenceOntology;
73 import jalview.gui.AlignFrame;
74 import jalview.gui.Desktop;
75 import jalview.gui.PromptUserConfig;
76 import jalview.gui.QuitHandler;
77 import jalview.gui.QuitHandler.QResponse;
78 import jalview.io.AppletFormatAdapter;
79 import jalview.io.BioJsHTMLOutput;
80 import jalview.io.DataSourceType;
81 import jalview.io.FileFormat;
82 import jalview.io.FileFormatException;
83 import jalview.io.FileFormatI;
84 import jalview.io.FileFormats;
85 import jalview.io.FileLoader;
86 import jalview.io.HtmlSvgOutput;
87 import jalview.io.IdentifyFile;
88 import jalview.io.NewickFile;
89 import jalview.io.gff.SequenceOntologyFactory;
90 import jalview.schemes.ColourSchemeI;
91 import jalview.schemes.ColourSchemeProperty;
92 import jalview.util.ChannelProperties;
93 import jalview.util.HttpUtils;
94 import jalview.util.LaunchUtils;
95 import jalview.util.MessageManager;
96 import jalview.util.Platform;
97 import jalview.ws.jws2.Jws2Discoverer;
100 * Main class for Jalview Application <br>
102 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
103 * jalview.bin.Jalview
105 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
106 * jalview.bin.Jalview jalview.bin.Jalview
108 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
109 * embellish '*' to e.g. '*.jar')
112 * @version $Revision$
118 Platform.getURLCommandArguments();
119 Platform.addJ2SDirectDatabaseCall("https://www.jalview.org");
120 Platform.addJ2SDirectDatabaseCall("http://www.jalview.org");
121 Platform.addJ2SDirectDatabaseCall("http://www.compbio.dundee.ac.uk");
122 Platform.addJ2SDirectDatabaseCall("https://www.compbio.dundee.ac.uk");
126 * singleton instance of this class
128 private static Jalview instance;
130 private Desktop desktop;
132 protected Commands cmds;
134 public static AlignFrame currentAlignFrame;
138 if (!Platform.isJS())
145 // grab all the rights we can for the JVM
146 Policy.setPolicy(new Policy()
149 public PermissionCollection getPermissions(CodeSource codesource)
151 Permissions perms = new Permissions();
152 perms.add(new AllPermission());
157 public void refresh()
165 * keep track of feature fetching tasks.
173 * TODO: generalise to track all jalview events to orchestrate batch processing
177 private int queued = 0;
179 private int running = 0;
181 public FeatureFetcher()
186 public void addFetcher(final AlignFrame af,
187 final Vector<String> dasSources)
189 final long id = System.currentTimeMillis();
191 final FeatureFetcher us = this;
192 new Thread(new Runnable()
204 af.setProgressBar(MessageManager
205 .getString("status.das_features_being_retrived"), id);
206 af.featureSettings_actionPerformed(null);
207 af.setProgressBar(null, id);
216 public synchronized boolean allFinished()
218 return queued == 0 && running == 0;
223 public static Jalview getInstance()
229 * main class for Jalview application
232 * open <em>filename</em>
234 public static void main(String[] args)
236 // setLogging(); // BH - for event debugging in JavaScript
237 instance = new Jalview();
238 instance.doMain(args);
241 private static void logClass(String name)
243 // BH - for event debugging in JavaScript
244 ConsoleHandler consoleHandler = new ConsoleHandler();
245 consoleHandler.setLevel(Level.ALL);
246 Logger logger = Logger.getLogger(name);
247 logger.setLevel(Level.ALL);
248 logger.addHandler(consoleHandler);
251 @SuppressWarnings("unused")
252 private static void setLogging()
260 System.out.println("not in js");
263 // BH - for event debugging in JavaScript (Java mode only)
264 if (!Platform.isJS())
271 Logger.getLogger("").setLevel(Level.ALL);
272 logClass("java.awt.EventDispatchThread");
273 logClass("java.awt.EventQueue");
274 logClass("java.awt.Component");
275 logClass("java.awt.focus.Component");
276 logClass("java.awt.focus.DefaultKeyboardFocusManager");
284 void doMain(String[] args)
286 if (!Platform.isJS())
288 System.setSecurityManager(null);
292 args = new String[] {};
294 // Move any new getdown-launcher-new.jar into place over old
295 // getdown-launcher.jar
296 String appdirString = System.getProperty("getdownappdir");
297 if (appdirString != null && appdirString.length() > 0)
299 final File appdir = new File(appdirString);
305 LaunchUtil.upgradeGetdown(
306 new File(appdir, "getdown-launcher-old.jar"),
307 new File(appdir, "getdown-launcher.jar"),
308 new File(appdir, "getdown-launcher-new.jar"));
313 // get args needed before proper ArgParser
314 BootstrapArgs bootstrapArgs = BootstrapArgs.getBootstrapArgs(args);
316 if (!Platform.isJS())
318 // are we being --quiet ?
319 if (bootstrapArgs.contains(Arg.QUIET))
321 OutputStream devNull = new OutputStream()
324 public void write(int b)
329 System.setOut(new PrintStream(devNull));
330 // redirecting stderr not working
331 if (bootstrapArgs.getList(Arg.QUIET).size() > 1)
333 System.setErr(new PrintStream(devNull));
339 .println("Java version: " + System.getProperty("java.version"));
340 System.out.println("Java Home: " + System.getProperty("java.home"));
341 System.out.println(System.getProperty("os.arch") + " "
342 + System.getProperty("os.name") + " "
343 + System.getProperty("os.version"));
345 String val = System.getProperty("sys.install4jVersion");
348 System.out.println("Install4j version: " + val);
350 val = System.getProperty("installer_template_version");
353 System.out.println("Install4j template version: " + val);
355 val = System.getProperty("launcher_version");
358 System.out.println("Launcher version: " + val);
361 if (Platform.isLinux() && LaunchUtils.getJavaVersion() < 11)
363 System.setProperty("flatlaf.uiScale", "1");
366 // get bootstrap properties (mainly for the logger level)
367 Properties bootstrapProperties = Cache
368 .bootstrapProperties(bootstrapArgs.get(Arg.PROPS));
370 // report Jalview version
371 Cache.loadBuildProperties(true);
374 ArgsParser aparser = new ArgsParser(args);
377 boolean headless = false;
379 boolean headlessArg = false;
383 String logLevel = bootstrapArgs.contains(Arg.DEBUG) ? "DEBUG" : null;
384 if (logLevel == null && !(bootstrapProperties == null))
386 logLevel = bootstrapProperties.getProperty(Cache.JALVIEWLOGLEVEL);
388 Console.initLogger(logLevel);
389 } catch (NoClassDefFoundError error)
391 error.printStackTrace();
392 String message = "\nEssential logging libraries not found."
393 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
394 Jalview.exit(message, 0);
397 // register SIGTERM listener
398 Runtime.getRuntime().addShutdownHook(new Thread()
402 Console.debug("Running shutdown hook");
403 if (QuitHandler.gotQuitResponse() == QResponse.CANCEL_QUIT)
405 // Got to here by a SIGTERM signal.
406 // Note we will not actually cancel the quit from here -- it's too
407 // late -- but we can wait for saving files.
408 Console.debug("Checking for saving files");
409 QuitHandler.getQuitResponse(false);
413 Console.debug("Nothing more to do");
415 Console.debug("Exiting, bye!");
416 // shutdownHook cannot be cancelled, JVM will now halt
420 String usrPropsFile = bootstrapArgs.contains(Arg.PROPS)
421 ? bootstrapArgs.get(Arg.PROPS)
422 : aparser.getValue("props");
423 // if usrPropsFile == null, loadProperties will use the Channel
425 Cache.loadProperties(usrPropsFile);
426 if (usrPropsFile != null)
429 "CMD [-props " + usrPropsFile + "] executed successfully!");
434 // --argfile=... -- OVERRIDES ALL NON-BOOTSTRAP ARGS
435 if (bootstrapArgs.contains(Arg.ARGFILE))
437 argparser = ArgParser.parseArgFiles(
438 bootstrapArgs.getList(Arg.ARGFILE),
439 bootstrapArgs.getBoolean(Arg.INITSUBSTITUTIONS));
443 argparser = new ArgParser(args,
444 bootstrapArgs.getBoolean(Arg.INITSUBSTITUTIONS));
447 if (!Platform.isJS())
454 if (bootstrapArgs.contains(Arg.HELP))
456 System.out.println(Arg.usage());
457 Jalview.exit(null, 0);
459 if (aparser.contains("help") || aparser.contains("h"))
462 Jalview.exit(null, 0);
465 if (bootstrapArgs.contains(Arg.HEADLESS))
467 System.setProperty("java.awt.headless", "true");
469 headlessArg = bootstrapArgs.getBoolean(Arg.HEADLESS);
471 if (aparser.contains("nodisplay") || aparser.contains("nogui")
472 || aparser.contains("headless"))
474 System.setProperty("java.awt.headless", "true");
480 // allow https handshakes to download intermediate certs if necessary
481 System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
483 final String jabawsUrl = aparser.getValue("jabaws");
484 if (jabawsUrl != null)
488 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
490 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
491 } catch (MalformedURLException e)
494 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
499 List<String> setprops = new ArrayList<>();
500 if (bootstrapArgs.contains(Arg.SETPROP))
502 setprops = bootstrapArgs.getList(Arg.SETPROP);
506 String sp = aparser.getValue("setprop");
510 sp = aparser.getValue("setprop");
513 for (String setprop : setprops)
515 int p = setprop.indexOf('=');
519 .println("Ignoring invalid setprop argument : " + setprop);
523 System.out.println("Executing setprop argument: " + setprop);
526 Cache.setProperty(setprop.substring(0, p),
527 setprop.substring(p + 1));
529 // DISABLED FOR SECURITY REASONS
530 // TODO: add a property to allow properties to be overriden by cli args
531 // Cache.setProperty(setprop.substring(0,p), setprop.substring(p+1));
534 if (System.getProperty("java.awt.headless") != null
535 && System.getProperty("java.awt.headless").equals("true"))
539 System.setProperty("http.agent",
540 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
544 Console.initLogger();
547 NoClassDefFoundError error)
549 error.printStackTrace();
550 String message = "\nEssential logging libraries not found."
551 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
552 Jalview.exit(message, 0);
556 if (!(headless || headlessArg))
560 * configure 'full' SO model if preferences say to, else use the default (full SO)
561 * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
563 boolean soDefault = !Platform.isJS();
564 if (Cache.getDefault("USE_FULL_SO", soDefault))
566 SequenceOntologyFactory.setInstance(new SequenceOntology());
569 if (!(headless || headlessArg))
571 Desktop.nosplash = "false".equals(bootstrapArgs.get(Arg.SPLASH))
572 || aparser.contains("nosplash")
573 || Cache.getDefault("SPLASH", "true").equals("false");
574 desktop = new Desktop();
575 desktop.setInBatchMode(true); // indicate we are starting up
579 JalviewTaskbar.setTaskbar(this);
580 } catch (Exception e)
582 Console.info("Cannot set Taskbar");
583 Console.error(e.getMessage());
584 // e.printStackTrace();
585 } catch (Throwable t)
587 Console.info("Cannot set Taskbar");
588 Console.error(t.getMessage());
589 // t.printStackTrace();
592 // set Proxy settings before all the internet calls
593 Cache.setProxyPropertiesFromPreferences();
595 desktop.setVisible(true);
597 if (!Platform.isJS())
606 * Check to see that the JVM version being run is suitable for the Java
607 * version this Jalview was compiled for. Popup a warning if not.
609 if (!LaunchUtils.checkJavaVersion())
611 Console.warn("The Java version being used (Java "
612 + LaunchUtils.getJavaVersion()
613 + ") may lead to problems. This installation of Jalview should be used with Java "
614 + LaunchUtils.getJavaCompileVersion() + ".");
617 .getBooleanUserPreference("IGNORE_JVM_WARNING_POPUP"))
620 MessageManager.getString("label.continue") };
621 JOptionPane.showOptionDialog(null,
622 MessageManager.formatMessage(
623 "warning.wrong_jvm_version_message",
624 LaunchUtils.getJavaVersion(),
625 LaunchUtils.getJavaCompileVersion()),
627 .getString("warning.wrong_jvm_version_title"),
628 JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
629 null, options, options[0]);
633 boolean doWebServiceDiscovery = !aparser
634 .contains("nowebservicediscovery");
635 if (bootstrapArgs.contains(Arg.WEBSERVICEDISCOVERY))
636 doWebServiceDiscovery = bootstrapArgs
637 .getBoolean(Arg.WEBSERVICEDISCOVERY);
638 if (doWebServiceDiscovery)
640 desktop.startServiceDiscovery();
642 if (!aparser.contains("nousagestats"))
644 startUsageStats(desktop);
648 System.err.println("CMD [-nousagestats] executed successfully!");
651 if (!aparser.contains("noquestionnaire"))
653 String url = aparser.getValue("questionnaire");
656 // Start the desktop questionnaire prompter with the specified
658 Console.debug("Starting questionnaire url at " + url);
659 desktop.checkForQuestionnaire(url);
660 System.out.println("CMD questionnaire[-" + url
661 + "] executed successfully!");
665 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
667 // Start the desktop questionnaire prompter with the specified
670 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
672 String defurl = "https://www.jalview.org/cgi-bin/questionnaire.pl";
674 "Starting questionnaire with default url: " + defurl);
675 desktop.checkForQuestionnaire(defurl);
682 .println("CMD [-noquestionnaire] executed successfully!");
685 if ((!aparser.contains("nonews")
686 && Cache.getProperty("NONEWS") == null
687 && !"false".equals(bootstrapArgs.get(Arg.NEWS)))
688 || "true".equals(bootstrapArgs.get(Arg.NEWS)))
690 desktop.checkForNews();
693 if (!aparser.contains("nohtmltemplates")
694 && Cache.getProperty("NOHTMLTEMPLATES") == null)
696 BioJsHTMLOutput.updateBioJS();
700 // Run Commands from cli
701 cmds = new Commands(argparser, headlessArg);
702 boolean commandsSuccess = cmds.argsWereParsed();
707 Jalview.exit("Successfully completed commands in headless mode", 0);
709 Console.info("Successfully completed commands");
715 Jalview.exit("Error when running Commands in headless mode", 1);
717 Console.warn("Error when running commands");
720 // Check if JVM and compile version might cause problems and log if it
722 if (headless && !Platform.isJS() && !LaunchUtils.checkJavaVersion())
724 Console.warn("The Java version being used (Java "
725 + LaunchUtils.getJavaVersion()
726 + ") may lead to problems. This installation of Jalview should be used with Java "
727 + LaunchUtils.getJavaCompileVersion() + ".");
730 String file = null, data = null;
732 FileFormatI format = null;
734 DataSourceType protocol = null;
736 FileLoader fileLoader = new FileLoader(!headless);
738 String groovyscript = null; // script to execute after all loading is
739 // completed one way or another
740 // extract groovy argument and execute if necessary
741 groovyscript = aparser.getValue("groovy", true);
742 file = aparser.getValue("open", true);
744 if (file == null && desktop == null && !commandsSuccess)
746 Jalview.exit("No files to open!", 1);
750 // Finally, deal with the remaining input data.
755 desktop.setProgressBar(
757 .getString("status.processing_commandline_args"),
758 progress = System.currentTimeMillis());
760 System.out.println("CMD [-open " + file + "] executed successfully!");
762 if (!Platform.isJS())
764 * ignore in JavaScript -- can't just file existence - could load it?
769 if (!HttpUtils.startsWithHttpOrHttps(file))
771 if (!(new File(file)).exists())
776 "Can't find file '" + file + "' in headless mode", 1);
778 Console.warn("Can't find file'" + file + "'");
783 protocol = AppletFormatAdapter.checkProtocol(file);
787 format = new IdentifyFile().identify(file, protocol);
788 } catch (FileFormatException e1)
793 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
797 System.out.println("error");
801 setCurrentAlignFrame(af);
802 data = aparser.getValue("colour", true);
805 data.replaceAll("%20", " ");
807 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
808 af.getViewport(), af.getViewport().getAlignment(), data);
813 "CMD [-colour " + data + "] executed successfully!");
818 // Must maintain ability to use the groups flag
819 data = aparser.getValue("groups", true);
822 af.parseFeaturesFile(data,
823 AppletFormatAdapter.checkProtocol(data));
824 // System.out.println("Added " + data);
826 "CMD groups[-" + data + "] executed successfully!");
828 data = aparser.getValue("features", true);
831 af.parseFeaturesFile(data,
832 AppletFormatAdapter.checkProtocol(data));
833 // System.out.println("Added " + data);
835 "CMD [-features " + data + "] executed successfully!");
838 data = aparser.getValue("annotations", true);
841 af.loadJalviewDataFile(data, null, null, null);
842 // System.out.println("Added " + data);
844 "CMD [-annotations " + data + "] executed successfully!");
846 // set or clear the sortbytree flag.
847 if (aparser.contains("sortbytree"))
849 af.getViewport().setSortByTree(true);
850 if (af.getViewport().getSortByTree())
852 System.out.println("CMD [-sortbytree] executed successfully!");
855 if (aparser.contains("no-annotation"))
857 af.getViewport().setShowAnnotation(false);
858 if (!af.getViewport().isShowAnnotation())
860 System.out.println("CMD no-annotation executed successfully!");
863 if (aparser.contains("nosortbytree"))
865 af.getViewport().setSortByTree(false);
866 if (!af.getViewport().getSortByTree())
869 .println("CMD [-nosortbytree] executed successfully!");
872 data = aparser.getValue("tree", true);
878 "CMD [-tree " + data + "] executed successfully!");
879 NewickFile nf = new NewickFile(data,
880 AppletFormatAdapter.checkProtocol(data));
882 .setCurrentTree(af.showNewickTree(nf, data).getTree());
883 } catch (IOException ex)
885 System.err.println("Couldn't add tree " + data);
886 ex.printStackTrace(System.err);
889 // TODO - load PDB structure(s) to alignment JAL-629
890 // (associate with identical sequence in alignment, or a specified
892 if (groovyscript != null)
894 // Execute the groovy script after we've done all the rendering stuff
895 // and before any images or figures are generated.
896 System.out.println("Executing script " + groovyscript);
897 executeGroovyScript(groovyscript, af);
898 System.out.println("CMD groovy[" + groovyscript
899 + "] executed successfully!");
902 String imageName = "unnamed.png";
903 while (aparser.getSize() > 1)
905 String outputFormat = aparser.nextValue();
906 file = aparser.nextValue();
908 if (outputFormat.equalsIgnoreCase("png"))
910 af.createPNG(new File(file));
911 imageName = (new File(file)).getName();
912 System.out.println("Creating PNG image: " + file);
915 else if (outputFormat.equalsIgnoreCase("svg"))
917 File imageFile = new File(file);
918 imageName = imageFile.getName();
919 af.createSVG(imageFile);
920 System.out.println("Creating SVG image: " + file);
923 else if (outputFormat.equalsIgnoreCase("html"))
925 File imageFile = new File(file);
926 imageName = imageFile.getName();
927 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
928 htmlSVG.exportHTML(file);
930 System.out.println("Creating HTML image: " + file);
933 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
937 System.err.println("The output html file must not be null");
942 BioJsHTMLOutput.refreshVersionInfo(
943 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
944 } catch (URISyntaxException e)
948 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
949 bjs.exportHTML(file);
951 .println("Creating BioJS MSA Viwer HTML file: " + file);
954 else if (outputFormat.equalsIgnoreCase("imgMap"))
956 af.createImageMap(new File(file), imageName);
957 System.out.println("Creating image map: " + file);
960 else if (outputFormat.equalsIgnoreCase("eps"))
962 File outputFile = new File(file);
964 "Creating EPS file: " + outputFile.getAbsolutePath());
965 af.createEPS(outputFile);
968 FileFormatI outFormat = null;
971 outFormat = FileFormats.getInstance().forName(outputFormat);
972 } catch (Exception formatP)
974 System.out.println("Couldn't parse " + outFormat
975 + " as a valid Jalview format string.");
977 if (outFormat != null)
979 if (!outFormat.isWritable())
982 "This version of Jalview does not support alignment export as "
987 af.saveAlignment(file, outFormat);
988 if (af.isSaveAlignmentSuccessful())
990 System.out.println("Written alignment in "
991 + outFormat.getName() + " format to " + file);
995 System.out.println("Error writing file " + file + " in "
996 + outFormat.getName() + " format!!");
1003 while (aparser.getSize() > 0)
1005 System.out.println("Unknown arg: " + aparser.nextValue());
1010 AlignFrame startUpAlframe = null;
1011 // We'll only open the default file if the desktop is visible.
1013 // ////////////////////
1015 if (!Platform.isJS() && !headless && file == null
1016 && Cache.getDefault("SHOW_STARTUP_FILE", true)
1017 && !cmds.commandArgsProvided())
1018 // don't open the startup file if command line args have been processed
1019 // (&& !Commands.commandArgsProvided())
1026 file = Cache.getDefault("STARTUP_FILE",
1027 Cache.getDefault("www.jalview.org", "https://www.jalview.org")
1028 + "/examples/exampleFile_2_7.jvp");
1029 if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar")
1031 "http://www.jalview.org/examples/exampleFile_2_7.jar"))
1033 file.replace("http:", "https:");
1034 // hardwire upgrade of the startup file
1035 file.replace("_2_3", "_2_7");
1036 file.replace("2_7.jar", "2_7.jvp");
1037 // and remove the stale setting
1038 Cache.removeProperty("STARTUP_FILE");
1041 protocol = AppletFormatAdapter.checkProtocol(file);
1043 if (file.endsWith(".jar"))
1045 format = FileFormat.Jalview;
1051 format = new IdentifyFile().identify(file, protocol);
1052 } catch (FileFormatException e)
1058 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
1060 // don't ask to save when quitting if only the startup file has been
1062 Console.debug("Resetting up-to-date flag for startup file");
1063 startUpAlframe.getViewport().setSavedUpToDate(true);
1064 // extract groovy arguments before anything else.
1067 // Once all other stuff is done, execute any groovy scripts (in order)
1068 if (groovyscript != null)
1070 if (Cache.groovyJarsPresent())
1072 System.out.println("Executing script " + groovyscript);
1073 executeGroovyScript(groovyscript, startUpAlframe);
1078 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
1082 // and finally, turn off batch mode indicator - if the desktop still exists
1083 if (desktop != null)
1087 desktop.setProgressBar(null, progress);
1089 desktop.setInBatchMode(false);
1093 private static void setLookAndFeel()
1095 // property laf = "crossplatform", "system", "gtk", "metal", "nimbus",
1097 // If not set (or chosen laf fails), use the normal SystemLaF and if on Mac,
1098 // try Quaqua/Vaqua.
1099 String lafProp = System.getProperty("laf");
1100 String lafSetting = Cache.getDefault("PREFERRED_LAF", null);
1101 String laf = "none";
1102 if (lafProp != null)
1106 else if (lafSetting != null)
1110 boolean lafSet = false;
1113 case "crossplatform":
1114 lafSet = setCrossPlatformLookAndFeel();
1117 Console.error("Could not set requested laf=" + laf);
1121 lafSet = setSystemLookAndFeel();
1124 Console.error("Could not set requested laf=" + laf);
1128 lafSet = setGtkLookAndFeel();
1131 Console.error("Could not set requested laf=" + laf);
1135 lafSet = setMetalLookAndFeel();
1138 Console.error("Could not set requested laf=" + laf);
1142 lafSet = setNimbusLookAndFeel();
1145 Console.error("Could not set requested laf=" + laf);
1149 lafSet = setFlatLookAndFeel();
1152 Console.error("Could not set requested laf=" + laf);
1156 lafSet = setMacLookAndFeel();
1159 Console.error("Could not set requested laf=" + laf);
1165 Console.error("Requested laf=" + laf + " not implemented");
1169 setSystemLookAndFeel();
1170 if (Platform.isLinux())
1172 setLinuxLookAndFeel();
1174 if (Platform.isMac())
1176 setMacLookAndFeel();
1181 private static boolean setCrossPlatformLookAndFeel()
1183 boolean set = false;
1186 UIManager.setLookAndFeel(
1187 UIManager.getCrossPlatformLookAndFeelClassName());
1189 } catch (Exception ex)
1191 Console.error("Unexpected Look and Feel Exception");
1192 Console.error(ex.getMessage());
1193 Console.debug(Cache.getStackTraceString(ex));
1198 private static boolean setSystemLookAndFeel()
1200 boolean set = false;
1203 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1205 } catch (Exception ex)
1207 Console.error("Unexpected Look and Feel Exception");
1208 Console.error(ex.getMessage());
1209 Console.debug(Cache.getStackTraceString(ex));
1214 private static boolean setSpecificLookAndFeel(String name,
1215 String className, boolean nameStartsWith)
1217 boolean set = false;
1220 for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
1222 if (info.getName() != null && nameStartsWith
1223 ? info.getName().toLowerCase(Locale.ROOT)
1224 .startsWith(name.toLowerCase(Locale.ROOT))
1225 : info.getName().toLowerCase(Locale.ROOT)
1226 .equals(name.toLowerCase(Locale.ROOT)))
1228 className = info.getClassName();
1232 UIManager.setLookAndFeel(className);
1234 } catch (Exception ex)
1236 Console.error("Unexpected Look and Feel Exception");
1237 Console.error(ex.getMessage());
1238 Console.debug(Cache.getStackTraceString(ex));
1243 private static boolean setGtkLookAndFeel()
1245 return setSpecificLookAndFeel("gtk",
1246 "com.sun.java.swing.plaf.gtk.GTKLookAndFeel", true);
1249 private static boolean setMetalLookAndFeel()
1251 return setSpecificLookAndFeel("metal",
1252 "javax.swing.plaf.metal.MetalLookAndFeel", false);
1255 private static boolean setNimbusLookAndFeel()
1257 return setSpecificLookAndFeel("nimbus",
1258 "javax.swing.plaf.nimbus.NimbusLookAndFeel", false);
1261 private static boolean setFlatLookAndFeel()
1263 boolean set = false;
1264 if (SystemInfo.isMacOS)
1268 UIManager.setLookAndFeel(
1269 "com.formdev.flatlaf.themes.FlatMacLightLaf");
1271 Console.debug("Using FlatMacLightLaf");
1272 } catch (ClassNotFoundException | InstantiationException
1273 | IllegalAccessException | UnsupportedLookAndFeelException e)
1275 Console.debug("Exception loading FlatLightLaf", e);
1277 System.setProperty("apple.laf.useScreenMenuBar", "true");
1278 System.setProperty("apple.awt.application.name",
1279 ChannelProperties.getProperty("app_name"));
1280 System.setProperty("apple.awt.application.appearance", "system");
1281 if (SystemInfo.isMacFullWindowContentSupported
1282 && Desktop.desktop != null)
1284 Console.debug("Setting transparent title bar");
1285 Desktop.desktop.getRootPane()
1286 .putClientProperty("apple.awt.fullWindowContent", true);
1287 Desktop.desktop.getRootPane()
1288 .putClientProperty("apple.awt.transparentTitleBar", true);
1289 Desktop.desktop.getRootPane()
1290 .putClientProperty("apple.awt.fullscreenable", true);
1292 SwingUtilities.invokeLater(() -> {
1293 FlatMacLightLaf.setup();
1295 Console.debug("Using FlatMacLightLaf");
1302 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1304 Console.debug("Using FlatLightLaf");
1305 } catch (ClassNotFoundException | InstantiationException
1306 | IllegalAccessException | UnsupportedLookAndFeelException e)
1308 Console.debug("Exception loading FlatLightLaf", e);
1310 // Windows specific properties here
1311 SwingUtilities.invokeLater(() -> {
1312 FlatLightLaf.setup();
1314 Console.debug("Using FlatLightLaf");
1317 else if (SystemInfo.isLinux)
1321 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1323 Console.debug("Using FlatLightLaf");
1324 } catch (ClassNotFoundException | InstantiationException
1325 | IllegalAccessException | UnsupportedLookAndFeelException e)
1327 Console.debug("Exception loading FlatLightLaf", e);
1329 // enable custom window decorations
1330 JFrame.setDefaultLookAndFeelDecorated(true);
1331 JDialog.setDefaultLookAndFeelDecorated(true);
1332 SwingUtilities.invokeLater(() -> {
1333 FlatLightLaf.setup();
1335 Console.debug("Using FlatLightLaf");
1343 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1345 Console.debug("Using FlatLightLaf");
1346 } catch (ClassNotFoundException | InstantiationException
1347 | IllegalAccessException | UnsupportedLookAndFeelException e)
1349 Console.debug("Exception loading FlatLightLaf", e);
1355 UIManager.put("TabbedPane.tabType", "card");
1356 UIManager.put("TabbedPane.showTabSeparators", true);
1357 UIManager.put("TabbedPane.showContentSeparator", true);
1358 UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
1359 UIManager.put("TabbedPane.tabsOverlapBorder", true);
1360 UIManager.put("TabbedPane.hasFullBorder", true);
1361 UIManager.put("TabbedPane.tabLayoutPolicy", "scroll");
1362 UIManager.put("TabbedPane.scrollButtonsPolicy", "asNeeded");
1363 UIManager.put("TabbedPane.smoothScrolling", true);
1364 UIManager.put("TabbedPane.tabWidthMode", "compact");
1365 UIManager.put("TabbedPane.selectedBackground", Color.white);
1368 Desktop.setLiveDragMode(Cache.getDefault("FLAT_LIVE_DRAG_MODE", true));
1372 private static boolean setMacLookAndFeel()
1374 boolean set = false;
1375 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
1376 ChannelProperties.getProperty("app_name"));
1377 System.setProperty("apple.laf.useScreenMenuBar", "true");
1379 * broken native LAFs on (ARM?) macbooks
1380 set = setQuaquaLookAndFeel();
1381 if ((!set) || !UIManager.getLookAndFeel().getClass().toString()
1382 .toLowerCase(Locale.ROOT).contains("quaqua"))
1384 set = setVaquaLookAndFeel();
1387 set = setFlatLookAndFeel();
1391 private static boolean setLinuxLookAndFeel()
1393 boolean set = false;
1394 set = setFlatLookAndFeel();
1396 set = setMetalLookAndFeel();
1397 // avoid GtkLookAndFeel -- not good results especially on HiDPI
1399 set = setNimbusLookAndFeel();
1403 private static void showUsage()
1406 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1407 + "-nodisplay\tRun Jalview without User Interface.\n"
1408 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1409 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1410 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1411 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1412 + "-features FILE\tUse the given file to mark features on the alignment.\n"
1413 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1414 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1415 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1416 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1417 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1418 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1419 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1420 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1421 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1422 + "-png FILE\tCreate PNG image FILE from alignment.\n"
1423 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1424 + "-html FILE\tCreate HTML file from alignment.\n"
1425 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1426 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1427 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1428 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1429 + "-noquestionnaire\tTurn off questionnaire check.\n"
1430 + "-nonews\tTurn off check for Jalview news.\n"
1431 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1432 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1434 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1435 // after all other properties files have been read\n\t
1436 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1437 // passed in correctly)"
1438 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1439 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1440 + "-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"
1441 + "-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"
1442 + "-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"
1443 + "\n~Read documentation in Application or visit https://www.jalview.org for description of Features and Annotations file~\n\n");
1446 private static void startUsageStats(final Desktop desktop)
1449 * start a User Config prompt asking if we can log usage statistics.
1451 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1452 "USAGESTATS", "Jalview Usage Statistics",
1453 "Do you want to help make Jalview better by enabling "
1454 + "the collection of usage statistics with Google Analytics ?"
1455 + "\n\n(you can enable or disable usage tracking in the preferences)",
1462 "Initialising googletracker for usage stats.");
1463 Cache.initGoogleTracker();
1464 Console.debug("Tracking enabled.");
1471 Console.debug("Not enabling Google Tracking.");
1474 desktop.addDialogThread(prompter);
1478 * Locate the given string as a file and pass it to the groovy interpreter.
1480 * @param groovyscript
1481 * the script to execute
1482 * @param jalviewContext
1483 * the Jalview Desktop object passed in to the groovy binding as the
1486 private void executeGroovyScript(String groovyscript, AlignFrame af)
1489 * for scripts contained in files
1496 if (groovyscript.trim().equals("STDIN"))
1498 // read from stdin into a tempfile and execute it
1501 tfile = File.createTempFile("jalview", "groovy");
1502 PrintWriter outfile = new PrintWriter(
1503 new OutputStreamWriter(new FileOutputStream(tfile)));
1504 BufferedReader br = new BufferedReader(
1505 new InputStreamReader(System.in));
1507 while ((line = br.readLine()) != null)
1509 outfile.write(line + "\n");
1515 } catch (Exception ex)
1517 System.err.println("Failed to read from STDIN into tempfile "
1518 + ((tfile == null) ? "(tempfile wasn't created)"
1519 : tfile.toString()));
1520 ex.printStackTrace();
1525 sfile = tfile.toURI().toURL();
1526 } catch (Exception x)
1529 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1531 x.printStackTrace();
1539 sfile = new URI(groovyscript).toURL();
1540 } catch (Exception x)
1542 tfile = new File(groovyscript);
1543 if (!tfile.exists())
1545 System.err.println("File '" + groovyscript + "' does not exist.");
1548 if (!tfile.canRead())
1550 System.err.println("File '" + groovyscript + "' cannot be read.");
1553 if (tfile.length() < 1)
1555 System.err.println("File '" + groovyscript + "' is empty.");
1560 sfile = tfile.getAbsoluteFile().toURI().toURL();
1561 } catch (Exception ex)
1563 System.err.println("Failed to create a file URL for "
1564 + tfile.getAbsoluteFile());
1571 Map<String, java.lang.Object> vbinding = new HashMap<>();
1572 vbinding.put("Jalview", this);
1575 vbinding.put("currentAlFrame", af);
1577 Binding gbinding = new Binding(vbinding);
1578 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1579 gse.run(sfile.toString(), gbinding);
1580 if ("STDIN".equals(groovyscript))
1582 // delete temp file that we made -
1583 // only if it was successfully executed
1586 } catch (Exception e)
1588 System.err.println("Exception Whilst trying to execute file " + sfile
1589 + " as a groovy script.");
1590 e.printStackTrace(System.err);
1595 public static boolean isHeadlessMode()
1597 String isheadless = System.getProperty("java.awt.headless");
1598 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1605 public AlignFrame[] getAlignFrames()
1607 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1608 : Desktop.getAlignFrames();
1613 * jalview.bin.Jalview.quit() will just run the non-GUI shutdownHook and exit
1617 // System.exit will run the shutdownHook first
1618 Jalview.exit("Quitting now. Bye!", 0);
1621 public static AlignFrame getCurrentAlignFrame()
1623 return Jalview.currentAlignFrame;
1626 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1628 Jalview.currentAlignFrame = currentAlignFrame;
1631 protected Commands getCommands()
1636 public static void exit(String message, int exitcode)
1638 Console.debug("Using Jalview.exit");
1639 if (message != null)
1641 Console.info(message);
1643 Console.error(message);
1645 System.exit(exitcode);