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.Arg.Opt;
71 import jalview.bin.argparser.Arg.Type;
72 import jalview.bin.argparser.ArgParser;
73 import jalview.bin.argparser.BootstrapArgs;
74 import jalview.ext.so.SequenceOntology;
75 import jalview.gui.AlignFrame;
76 import jalview.gui.Desktop;
77 import jalview.gui.PromptUserConfig;
78 import jalview.gui.QuitHandler;
79 import jalview.gui.QuitHandler.QResponse;
80 import jalview.io.AppletFormatAdapter;
81 import jalview.io.BioJsHTMLOutput;
82 import jalview.io.DataSourceType;
83 import jalview.io.FileFormat;
84 import jalview.io.FileFormatException;
85 import jalview.io.FileFormatI;
86 import jalview.io.FileFormats;
87 import jalview.io.FileLoader;
88 import jalview.io.HtmlSvgOutput;
89 import jalview.io.IdentifyFile;
90 import jalview.io.NewickFile;
91 import jalview.io.gff.SequenceOntologyFactory;
92 import jalview.schemes.ColourSchemeI;
93 import jalview.schemes.ColourSchemeProperty;
94 import jalview.util.ChannelProperties;
95 import jalview.util.HttpUtils;
96 import jalview.util.LaunchUtils;
97 import jalview.util.MessageManager;
98 import jalview.util.Platform;
99 import jalview.ws.jws2.Jws2Discoverer;
102 * Main class for Jalview Application <br>
104 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
105 * jalview.bin.Jalview
107 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
108 * jalview.bin.Jalview jalview.bin.Jalview
110 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
111 * embellish '*' to e.g. '*.jar')
114 * @version $Revision$
120 Platform.getURLCommandArguments();
121 Platform.addJ2SDirectDatabaseCall("https://www.jalview.org");
122 Platform.addJ2SDirectDatabaseCall("http://www.jalview.org");
123 Platform.addJ2SDirectDatabaseCall("http://www.compbio.dundee.ac.uk");
124 Platform.addJ2SDirectDatabaseCall("https://www.compbio.dundee.ac.uk");
128 * singleton instance of this class
130 private static Jalview instance;
132 private Desktop desktop;
134 protected Commands cmds;
136 public static AlignFrame currentAlignFrame;
138 public ArgParser argparser = null;
140 public BootstrapArgs bootstrapArgs = null;
142 private boolean QUIET = false;
144 public static boolean quiet()
146 return Jalview.getInstance() != null && Jalview.getInstance().QUIET;
151 if (!Platform.isJS())
158 // grab all the rights we can for the JVM
159 Policy.setPolicy(new Policy()
162 public PermissionCollection getPermissions(CodeSource codesource)
164 Permissions perms = new Permissions();
165 perms.add(new AllPermission());
170 public void refresh()
178 * keep track of feature fetching tasks.
186 * TODO: generalise to track all jalview events to orchestrate batch processing
190 private int queued = 0;
192 private int running = 0;
194 public FeatureFetcher()
199 public void addFetcher(final AlignFrame af,
200 final Vector<String> dasSources)
202 final long id = System.currentTimeMillis();
204 final FeatureFetcher us = this;
205 new Thread(new Runnable()
217 af.setProgressBar(MessageManager
218 .getString("status.das_features_being_retrived"), id);
219 af.featureSettings_actionPerformed(null);
220 af.setProgressBar(null, id);
229 public synchronized boolean allFinished()
231 return queued == 0 && running == 0;
236 public static Jalview getInstance()
242 * main class for Jalview application
245 * open <em>filename</em>
247 public static void main(String[] args)
249 // setLogging(); // BH - for event debugging in JavaScript
250 instance = new Jalview();
251 instance.doMain(args);
254 private static void logClass(String name)
256 // BH - for event debugging in JavaScript
257 ConsoleHandler consoleHandler = new ConsoleHandler();
258 consoleHandler.setLevel(Level.ALL);
259 Logger logger = Logger.getLogger(name);
260 logger.setLevel(Level.ALL);
261 logger.addHandler(consoleHandler);
264 @SuppressWarnings("unused")
265 private static void setLogging()
273 System.out.println("not in js");
276 // BH - for event debugging in JavaScript (Java mode only)
277 if (!Platform.isJS())
284 Logger.getLogger("").setLevel(Level.ALL);
285 logClass("java.awt.EventDispatchThread");
286 logClass("java.awt.EventQueue");
287 logClass("java.awt.Component");
288 logClass("java.awt.focus.Component");
289 logClass("java.awt.focus.DefaultKeyboardFocusManager");
297 void doMain(String[] args)
299 if (!Platform.isJS())
301 System.setSecurityManager(null);
305 args = new String[] {};
307 // get args needed before proper ArgParser
308 bootstrapArgs = BootstrapArgs.getBootstrapArgs(args);
310 if (!Platform.isJS())
312 // are we being --quiet ?
313 if (bootstrapArgs.contains(Arg.QUIET))
316 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));
333 if (bootstrapArgs.contains(Arg.HELP)
334 || bootstrapArgs.contains(Arg.VERSION))
340 // Move any new getdown-launcher-new.jar into place over old
341 // getdown-launcher.jar
342 String appdirString = System.getProperty("getdownappdir");
343 if (appdirString != null && appdirString.length() > 0)
345 final File appdir = new File(appdirString);
351 LaunchUtil.upgradeGetdown(
352 new File(appdir, "getdown-launcher-old.jar"),
353 new File(appdir, "getdown-launcher.jar"),
354 new File(appdir, "getdown-launcher-new.jar"));
359 if (!quiet() || bootstrapArgs.contains(Arg.VERSION))
362 "Java version: " + System.getProperty("java.version"));
363 System.out.println("Java home: " + System.getProperty("java.home"));
364 System.out.println("Java arch: " + System.getProperty("os.arch") + " "
365 + System.getProperty("os.name") + " "
366 + System.getProperty("os.version"));
368 String val = System.getProperty("sys.install4jVersion");
371 System.out.println("Install4j version: " + val);
373 val = System.getProperty("installer_template_version");
376 System.out.println("Install4j template version: " + val);
378 val = System.getProperty("launcher_version");
381 System.out.println("Launcher version: " + val);
385 if (Platform.isLinux() && LaunchUtils.getJavaVersion() < 11)
387 System.setProperty("flatlaf.uiScale", "1");
390 // get bootstrap properties (mainly for the logger level)
391 Properties bootstrapProperties = Cache
392 .bootstrapProperties(bootstrapArgs.get(Arg.PROPS));
394 // report Jalview version
395 Cache.loadBuildProperties(
396 !quiet() || bootstrapArgs.contains(Arg.VERSION));
398 // stop now if only after --version
399 if (bootstrapArgs.contains(Arg.VERSION))
401 Jalview.exit(null, 0);
405 ArgsParser aparser = new ArgsParser(args);
408 boolean headless = false;
410 boolean headlessArg = false;
414 String logLevel = null;
415 if (bootstrapArgs.contains(Arg.TRACE))
419 else if (bootstrapArgs.contains(Arg.DEBUG))
423 if (logLevel == null && !(bootstrapProperties == null))
425 logLevel = bootstrapProperties.getProperty(Cache.JALVIEWLOGLEVEL);
427 Console.initLogger(logLevel);
428 } catch (NoClassDefFoundError error)
430 error.printStackTrace();
431 String message = "\nEssential logging libraries not found."
432 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
433 Jalview.exit(message, 0);
436 // register SIGTERM listener
437 Runtime.getRuntime().addShutdownHook(new Thread()
441 Console.debug("Running shutdown hook");
442 if (QuitHandler.gotQuitResponse() == QResponse.CANCEL_QUIT)
444 // Got to here by a SIGTERM signal.
445 // Note we will not actually cancel the quit from here -- it's too
446 // late -- but we can wait for saving files.
447 Console.debug("Checking for saving files");
448 QuitHandler.getQuitResponse(false);
452 Console.debug("Nothing more to do");
454 Console.debug("Exiting, bye!");
455 // shutdownHook cannot be cancelled, JVM will now halt
459 String usrPropsFile = bootstrapArgs.contains(Arg.PROPS)
460 ? bootstrapArgs.get(Arg.PROPS)
461 : aparser.getValue("props");
462 // if usrPropsFile == null, loadProperties will use the Channel
464 Cache.loadProperties(usrPropsFile);
465 if (usrPropsFile != null)
468 "CMD [-props " + usrPropsFile + "] executed successfully!");
469 testoutput(bootstrapArgs, Arg.PROPS,
470 "test/jalview/bin/testProps.jvprops", usrPropsFile);
473 // --argfile=... -- OVERRIDES ALL NON-BOOTSTRAP ARGS
474 if (bootstrapArgs.contains(Arg.ARGFILE))
476 argparser = ArgParser.parseArgFiles(
477 bootstrapArgs.getValueList(Arg.ARGFILE),
478 bootstrapArgs.getBoolean(Arg.INITSUBSTITUTIONS),
483 argparser = new ArgParser(args,
484 bootstrapArgs.getBoolean(Arg.INITSUBSTITUTIONS),
488 if (!Platform.isJS())
495 if (bootstrapArgs.containsType(Type.HELP))
497 System.out.println("##### HERE");
499 .println(Arg.usage(bootstrapArgs.getArgsOfType(Type.HELP)));
500 Jalview.exit(null, 0);
502 if (aparser.contains("help") || aparser.contains("h"))
505 * Now using new usage statement.
508 System.out.println(Arg.usage());
509 Jalview.exit(null, 0);
512 if (bootstrapArgs.contains(Arg.HEADLESS))
514 System.setProperty("java.awt.headless", "true");
516 headlessArg = bootstrapArgs.getBoolean(Arg.HEADLESS);
518 if (aparser.contains("nodisplay") || aparser.contains("nogui")
519 || aparser.contains("headless"))
521 System.setProperty("java.awt.headless", "true");
527 // allow https handshakes to download intermediate certs if necessary
528 System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
530 String jabawsUrl = bootstrapArgs.get(Arg.JABAWS);
531 if (jabawsUrl == null)
532 jabawsUrl = aparser.getValue("jabaws");
533 if (jabawsUrl != null)
537 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
539 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
540 testoutput(bootstrapArgs, Arg.JABAWS,
541 "http://www.compbio.dundee.ac.uk/jabaws", jabawsUrl);
542 } catch (MalformedURLException e)
545 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
550 List<String> setprops = new ArrayList<>();
551 if (bootstrapArgs.contains(Arg.SETPROP))
553 setprops = bootstrapArgs.getValueList(Arg.SETPROP);
557 String sp = aparser.getValue("setprop");
561 sp = aparser.getValue("setprop");
564 for (String setprop : setprops)
566 int p = setprop.indexOf('=');
570 .println("Ignoring invalid setprop argument : " + setprop);
574 System.out.println("Executing setprop argument: " + setprop);
577 Cache.setProperty(setprop.substring(0, p),
578 setprop.substring(p + 1));
580 // DISABLED FOR SECURITY REASONS
581 // TODO: add a property to allow properties to be overriden by cli args
582 // Cache.setProperty(setprop.substring(0,p), setprop.substring(p+1));
585 if (System.getProperty("java.awt.headless") != null
586 && System.getProperty("java.awt.headless").equals("true"))
590 System.setProperty("http.agent",
591 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
595 Console.initLogger();
598 NoClassDefFoundError error)
600 error.printStackTrace();
601 String message = "\nEssential logging libraries not found."
602 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
603 Jalview.exit(message, 0);
607 if (!(headless || headlessArg))
611 * configure 'full' SO model if preferences say to, else use the default (full SO)
612 * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
614 boolean soDefault = !Platform.isJS();
615 if (Cache.getDefault("USE_FULL_SO", soDefault))
617 SequenceOntologyFactory.setInstance(new SequenceOntology());
620 if (!(headless || headlessArg))
622 Desktop.nosplash = "false".equals(bootstrapArgs.get(Arg.SPLASH))
623 || aparser.contains("nosplash")
624 || Cache.getDefault("SPLASH", "true").equals("false");
625 desktop = new Desktop();
626 desktop.setInBatchMode(true); // indicate we are starting up
630 JalviewTaskbar.setTaskbar(this);
631 } catch (Exception e)
633 Console.info("Cannot set Taskbar");
634 Console.error(e.getMessage());
635 // e.printStackTrace();
636 } catch (Throwable t)
638 Console.info("Cannot set Taskbar");
639 Console.error(t.getMessage());
640 // t.printStackTrace();
643 // set Proxy settings before all the internet calls
644 Cache.setProxyPropertiesFromPreferences();
646 desktop.setVisible(true);
648 if (!Platform.isJS())
657 * Check to see that the JVM version being run is suitable for the Java
658 * version this Jalview was compiled for. Popup a warning if not.
660 if (!LaunchUtils.checkJavaVersion())
662 Console.warn("The Java version being used (Java "
663 + LaunchUtils.getJavaVersion()
664 + ") may lead to problems. This installation of Jalview should be used with Java "
665 + LaunchUtils.getJavaCompileVersion() + ".");
668 .getBooleanUserPreference("IGNORE_JVM_WARNING_POPUP"))
671 MessageManager.getString("label.continue") };
672 JOptionPane.showOptionDialog(null,
673 MessageManager.formatMessage(
674 "warning.wrong_jvm_version_message",
675 LaunchUtils.getJavaVersion(),
676 LaunchUtils.getJavaCompileVersion()),
678 .getString("warning.wrong_jvm_version_title"),
679 JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
680 null, options, options[0]);
684 boolean webservicediscovery = bootstrapArgs
685 .getBoolean(Arg.WEBSERVICEDISCOVERY);
686 if (aparser.contains("nowebservicediscovery"))
687 webservicediscovery = false;
688 if (webservicediscovery)
690 desktop.startServiceDiscovery();
694 testoutput(argparser, Arg.WEBSERVICEDISCOVERY);
697 boolean usagestats = bootstrapArgs.getBoolean(Arg.USAGESTATS);
698 if (aparser.contains("nousagestats"))
702 startUsageStats(desktop);
703 testoutput(argparser, Arg.USAGESTATS);
707 System.out.println("CMD [-nousagestats] executed successfully!");
708 testoutput(argparser, Arg.USAGESTATS);
711 boolean questionnaire = bootstrapArgs.getBoolean(Arg.QUESTIONNAIRE);
712 if (aparser.contains("noquestionnaire"))
713 questionnaire = false;
716 String url = aparser.getValue("questionnaire");
719 // Start the desktop questionnaire prompter with the specified
721 Console.debug("Starting questionnaire url at " + url);
722 desktop.checkForQuestionnaire(url);
723 System.out.println("CMD questionnaire[-" + url
724 + "] executed successfully!");
728 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
730 // Start the desktop questionnaire prompter with the specified
733 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
735 String defurl = "https://www.jalview.org/cgi-bin/questionnaire.pl";
737 "Starting questionnaire with default url: " + defurl);
738 desktop.checkForQuestionnaire(defurl);
745 .println("CMD [-noquestionnaire] executed successfully!");
746 testoutput(argparser, Arg.QUESTIONNAIRE);
749 if ((!aparser.contains("nonews")
750 && Cache.getProperty("NONEWS") == null
751 && !"false".equals(bootstrapArgs.get(Arg.NEWS)))
752 || "true".equals(bootstrapArgs.get(Arg.NEWS)))
754 desktop.checkForNews();
757 if (!aparser.contains("nohtmltemplates")
758 && Cache.getProperty("NOHTMLTEMPLATES") == null)
760 BioJsHTMLOutput.updateBioJS();
764 // Run Commands from cli
765 cmds = new Commands(argparser, headlessArg);
766 boolean commandsSuccess = cmds.argsWereParsed();
771 Jalview.exit("Successfully completed commands in headless mode", 0);
773 Console.info("Successfully completed commands");
779 Jalview.exit("Error when running Commands in headless mode", 1);
781 Console.warn("Error when running commands");
784 // Check if JVM and compile version might cause problems and log if it
786 if (headless && !Platform.isJS() && !LaunchUtils.checkJavaVersion())
788 Console.warn("The Java version being used (Java "
789 + LaunchUtils.getJavaVersion()
790 + ") may lead to problems. This installation of Jalview should be used with Java "
791 + LaunchUtils.getJavaCompileVersion() + ".");
794 String file = null, data = null;
796 FileFormatI format = null;
798 DataSourceType protocol = null;
800 FileLoader fileLoader = new FileLoader(!headless);
802 String groovyscript = null; // script to execute after all loading is
803 // completed one way or another
804 // extract groovy argument and execute if necessary
805 groovyscript = aparser.getValue("groovy", true);
806 file = aparser.getValue("open", true);
808 if (file == null && desktop == null && !commandsSuccess)
810 Jalview.exit("No files to open!", 1);
814 // Finally, deal with the remaining input data.
819 desktop.setProgressBar(
821 .getString("status.processing_commandline_args"),
822 progress = System.currentTimeMillis());
824 System.out.println("CMD [-open " + file + "] executed successfully!");
826 if (!Platform.isJS())
828 * ignore in JavaScript -- can't just file existence - could load it?
833 if (!HttpUtils.startsWithHttpOrHttps(file))
835 if (!(new File(file)).exists())
840 "Can't find file '" + file + "' in headless mode", 1);
842 Console.warn("Can't find file'" + file + "'");
847 protocol = AppletFormatAdapter.checkProtocol(file);
851 format = new IdentifyFile().identify(file, protocol);
852 } catch (FileFormatException e1)
857 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
861 System.out.println("error");
865 setCurrentAlignFrame(af);
866 data = aparser.getValue("colour", true);
869 data.replaceAll("%20", " ");
871 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
872 af.getViewport(), af.getViewport().getAlignment(), data);
877 "CMD [-colour " + data + "] executed successfully!");
882 // Must maintain ability to use the groups flag
883 data = aparser.getValue("groups", true);
886 af.parseFeaturesFile(data,
887 AppletFormatAdapter.checkProtocol(data));
888 // System.out.println("Added " + data);
890 "CMD groups[-" + data + "] executed successfully!");
892 data = aparser.getValue("features", true);
895 af.parseFeaturesFile(data,
896 AppletFormatAdapter.checkProtocol(data));
897 // System.out.println("Added " + data);
899 "CMD [-features " + data + "] executed successfully!");
902 data = aparser.getValue("annotations", true);
905 af.loadJalviewDataFile(data, null, null, null);
906 // System.out.println("Added " + data);
908 "CMD [-annotations " + data + "] executed successfully!");
910 // set or clear the sortbytree flag.
911 if (aparser.contains("sortbytree"))
913 af.getViewport().setSortByTree(true);
914 if (af.getViewport().getSortByTree())
916 System.out.println("CMD [-sortbytree] executed successfully!");
919 if (aparser.contains("no-annotation"))
921 af.getViewport().setShowAnnotation(false);
922 if (!af.getViewport().isShowAnnotation())
924 System.out.println("CMD no-annotation executed successfully!");
927 if (aparser.contains("nosortbytree"))
929 af.getViewport().setSortByTree(false);
930 if (!af.getViewport().getSortByTree())
933 .println("CMD [-nosortbytree] executed successfully!");
936 data = aparser.getValue("tree", true);
942 "CMD [-tree " + data + "] executed successfully!");
943 NewickFile nf = new NewickFile(data,
944 AppletFormatAdapter.checkProtocol(data));
946 .setCurrentTree(af.showNewickTree(nf, data).getTree());
947 } catch (IOException ex)
949 System.err.println("Couldn't add tree " + data);
950 ex.printStackTrace(System.err);
953 // TODO - load PDB structure(s) to alignment JAL-629
954 // (associate with identical sequence in alignment, or a specified
956 if (groovyscript != null)
958 // Execute the groovy script after we've done all the rendering stuff
959 // and before any images or figures are generated.
960 System.out.println("Executing script " + groovyscript);
961 executeGroovyScript(groovyscript, af);
962 System.out.println("CMD groovy[" + groovyscript
963 + "] executed successfully!");
966 String imageName = "unnamed.png";
967 while (aparser.getSize() > 1)
969 String outputFormat = aparser.nextValue();
970 file = aparser.nextValue();
972 if (outputFormat.equalsIgnoreCase("png"))
974 af.createPNG(new File(file));
975 imageName = (new File(file)).getName();
976 System.out.println("Creating PNG image: " + file);
979 else if (outputFormat.equalsIgnoreCase("svg"))
981 File imageFile = new File(file);
982 imageName = imageFile.getName();
983 af.createSVG(imageFile);
984 System.out.println("Creating SVG image: " + file);
987 else if (outputFormat.equalsIgnoreCase("html"))
989 File imageFile = new File(file);
990 imageName = imageFile.getName();
991 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
992 htmlSVG.exportHTML(file);
994 System.out.println("Creating HTML image: " + file);
997 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
1001 System.err.println("The output html file must not be null");
1006 BioJsHTMLOutput.refreshVersionInfo(
1007 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1008 } catch (URISyntaxException e)
1010 e.printStackTrace();
1012 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1013 bjs.exportHTML(file);
1015 .println("Creating BioJS MSA Viwer HTML file: " + file);
1018 else if (outputFormat.equalsIgnoreCase("imgMap"))
1020 af.createImageMap(new File(file), imageName);
1021 System.out.println("Creating image map: " + file);
1024 else if (outputFormat.equalsIgnoreCase("eps"))
1026 File outputFile = new File(file);
1028 "Creating EPS file: " + outputFile.getAbsolutePath());
1029 af.createEPS(outputFile);
1032 FileFormatI outFormat = null;
1035 outFormat = FileFormats.getInstance().forName(outputFormat);
1036 } catch (Exception formatP)
1038 System.out.println("Couldn't parse " + outFormat
1039 + " as a valid Jalview format string.");
1041 if (outFormat != null)
1043 if (!outFormat.isWritable())
1046 "This version of Jalview does not support alignment export as "
1051 af.saveAlignment(file, outFormat);
1052 if (af.isSaveAlignmentSuccessful())
1054 System.out.println("Written alignment in "
1055 + outFormat.getName() + " format to " + file);
1059 System.out.println("Error writing file " + file + " in "
1060 + outFormat.getName() + " format!!");
1067 while (aparser.getSize() > 0)
1069 System.out.println("Unknown arg: " + aparser.nextValue());
1074 AlignFrame startUpAlframe = null;
1075 // We'll only open the default file if the desktop is visible.
1077 // ////////////////////
1079 if (!Platform.isJS() && !headless && file == null
1080 && Cache.getDefault("SHOW_STARTUP_FILE", true)
1081 && !cmds.commandArgsProvided())
1082 // don't open the startup file if command line args have been processed
1083 // (&& !Commands.commandArgsProvided())
1090 file = Cache.getDefault("STARTUP_FILE",
1091 Cache.getDefault("www.jalview.org", "https://www.jalview.org")
1092 + "/examples/exampleFile_2_7.jvp");
1093 if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar")
1095 "http://www.jalview.org/examples/exampleFile_2_7.jar"))
1097 file.replace("http:", "https:");
1098 // hardwire upgrade of the startup file
1099 file.replace("_2_3", "_2_7");
1100 file.replace("2_7.jar", "2_7.jvp");
1101 // and remove the stale setting
1102 Cache.removeProperty("STARTUP_FILE");
1105 protocol = AppletFormatAdapter.checkProtocol(file);
1107 if (file.endsWith(".jar"))
1109 format = FileFormat.Jalview;
1115 format = new IdentifyFile().identify(file, protocol);
1116 } catch (FileFormatException e)
1122 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
1124 // don't ask to save when quitting if only the startup file has been
1126 Console.debug("Resetting up-to-date flag for startup file");
1127 startUpAlframe.getViewport().setSavedUpToDate(true);
1128 // extract groovy arguments before anything else.
1131 // Once all other stuff is done, execute any groovy scripts (in order)
1132 if (groovyscript != null)
1134 if (Cache.groovyJarsPresent())
1136 System.out.println("Executing script " + groovyscript);
1137 executeGroovyScript(groovyscript, startUpAlframe);
1142 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
1146 // and finally, turn off batch mode indicator - if the desktop still exists
1147 if (desktop != null)
1151 desktop.setProgressBar(null, progress);
1153 desktop.setInBatchMode(false);
1157 private static void setLookAndFeel()
1159 // property laf = "crossplatform", "system", "gtk", "metal", "nimbus",
1161 // If not set (or chosen laf fails), use the normal SystemLaF and if on Mac,
1162 // try Quaqua/Vaqua.
1163 String lafProp = System.getProperty("laf");
1164 String lafSetting = Cache.getDefault("PREFERRED_LAF", null);
1165 String laf = "none";
1166 if (lafProp != null)
1170 else if (lafSetting != null)
1174 boolean lafSet = false;
1177 case "crossplatform":
1178 lafSet = setCrossPlatformLookAndFeel();
1181 Console.error("Could not set requested laf=" + laf);
1185 lafSet = setSystemLookAndFeel();
1188 Console.error("Could not set requested laf=" + laf);
1192 lafSet = setGtkLookAndFeel();
1195 Console.error("Could not set requested laf=" + laf);
1199 lafSet = setMetalLookAndFeel();
1202 Console.error("Could not set requested laf=" + laf);
1206 lafSet = setNimbusLookAndFeel();
1209 Console.error("Could not set requested laf=" + laf);
1213 lafSet = setFlatLookAndFeel();
1216 Console.error("Could not set requested laf=" + laf);
1220 lafSet = setMacLookAndFeel();
1223 Console.error("Could not set requested laf=" + laf);
1229 Console.error("Requested laf=" + laf + " not implemented");
1233 setSystemLookAndFeel();
1234 if (Platform.isLinux())
1236 setLinuxLookAndFeel();
1238 if (Platform.isMac())
1240 setMacLookAndFeel();
1245 private static boolean setCrossPlatformLookAndFeel()
1247 boolean set = false;
1250 UIManager.setLookAndFeel(
1251 UIManager.getCrossPlatformLookAndFeelClassName());
1253 } catch (Exception ex)
1255 Console.error("Unexpected Look and Feel Exception");
1256 Console.error(ex.getMessage());
1257 Console.debug(Cache.getStackTraceString(ex));
1262 private static boolean setSystemLookAndFeel()
1264 boolean set = false;
1267 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1269 } catch (Exception ex)
1271 Console.error("Unexpected Look and Feel Exception");
1272 Console.error(ex.getMessage());
1273 Console.debug(Cache.getStackTraceString(ex));
1278 private static boolean setSpecificLookAndFeel(String name,
1279 String className, boolean nameStartsWith)
1281 boolean set = false;
1284 for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
1286 if (info.getName() != null && nameStartsWith
1287 ? info.getName().toLowerCase(Locale.ROOT)
1288 .startsWith(name.toLowerCase(Locale.ROOT))
1289 : info.getName().toLowerCase(Locale.ROOT)
1290 .equals(name.toLowerCase(Locale.ROOT)))
1292 className = info.getClassName();
1296 UIManager.setLookAndFeel(className);
1298 } catch (Exception ex)
1300 Console.error("Unexpected Look and Feel Exception");
1301 Console.error(ex.getMessage());
1302 Console.debug(Cache.getStackTraceString(ex));
1307 private static boolean setGtkLookAndFeel()
1309 return setSpecificLookAndFeel("gtk",
1310 "com.sun.java.swing.plaf.gtk.GTKLookAndFeel", true);
1313 private static boolean setMetalLookAndFeel()
1315 return setSpecificLookAndFeel("metal",
1316 "javax.swing.plaf.metal.MetalLookAndFeel", false);
1319 private static boolean setNimbusLookAndFeel()
1321 return setSpecificLookAndFeel("nimbus",
1322 "javax.swing.plaf.nimbus.NimbusLookAndFeel", false);
1325 private static boolean setFlatLookAndFeel()
1327 boolean set = false;
1328 if (SystemInfo.isMacOS)
1332 UIManager.setLookAndFeel(
1333 "com.formdev.flatlaf.themes.FlatMacLightLaf");
1335 Console.debug("Using FlatMacLightLaf");
1336 } catch (ClassNotFoundException | InstantiationException
1337 | IllegalAccessException | UnsupportedLookAndFeelException e)
1339 Console.debug("Exception loading FlatLightLaf", e);
1341 System.setProperty("apple.laf.useScreenMenuBar", "true");
1342 System.setProperty("apple.awt.application.name",
1343 ChannelProperties.getProperty("app_name"));
1344 System.setProperty("apple.awt.application.appearance", "system");
1345 if (SystemInfo.isMacFullWindowContentSupported
1346 && Desktop.desktop != null)
1348 Console.debug("Setting transparent title bar");
1349 Desktop.desktop.getRootPane()
1350 .putClientProperty("apple.awt.fullWindowContent", true);
1351 Desktop.desktop.getRootPane()
1352 .putClientProperty("apple.awt.transparentTitleBar", true);
1353 Desktop.desktop.getRootPane()
1354 .putClientProperty("apple.awt.fullscreenable", true);
1356 SwingUtilities.invokeLater(() -> {
1357 FlatMacLightLaf.setup();
1359 Console.debug("Using FlatMacLightLaf");
1366 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1368 Console.debug("Using FlatLightLaf");
1369 } catch (ClassNotFoundException | InstantiationException
1370 | IllegalAccessException | UnsupportedLookAndFeelException e)
1372 Console.debug("Exception loading FlatLightLaf", e);
1374 // Windows specific properties here
1375 SwingUtilities.invokeLater(() -> {
1376 FlatLightLaf.setup();
1378 Console.debug("Using FlatLightLaf");
1381 else if (SystemInfo.isLinux)
1385 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1387 Console.debug("Using FlatLightLaf");
1388 } catch (ClassNotFoundException | InstantiationException
1389 | IllegalAccessException | UnsupportedLookAndFeelException e)
1391 Console.debug("Exception loading FlatLightLaf", e);
1393 // enable custom window decorations
1394 JFrame.setDefaultLookAndFeelDecorated(true);
1395 JDialog.setDefaultLookAndFeelDecorated(true);
1396 SwingUtilities.invokeLater(() -> {
1397 FlatLightLaf.setup();
1399 Console.debug("Using FlatLightLaf");
1407 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1409 Console.debug("Using FlatLightLaf");
1410 } catch (ClassNotFoundException | InstantiationException
1411 | IllegalAccessException | UnsupportedLookAndFeelException e)
1413 Console.debug("Exception loading FlatLightLaf", e);
1419 UIManager.put("TabbedPane.tabType", "card");
1420 UIManager.put("TabbedPane.showTabSeparators", true);
1421 UIManager.put("TabbedPane.showContentSeparator", true);
1422 UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
1423 UIManager.put("TabbedPane.tabsOverlapBorder", true);
1424 UIManager.put("TabbedPane.hasFullBorder", true);
1425 UIManager.put("TabbedPane.tabLayoutPolicy", "scroll");
1426 UIManager.put("TabbedPane.scrollButtonsPolicy", "asNeeded");
1427 UIManager.put("TabbedPane.smoothScrolling", true);
1428 UIManager.put("TabbedPane.tabWidthMode", "compact");
1429 UIManager.put("TabbedPane.selectedBackground", Color.white);
1432 Desktop.setLiveDragMode(Cache.getDefault("FLAT_LIVE_DRAG_MODE", true));
1436 private static boolean setMacLookAndFeel()
1438 boolean set = false;
1439 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
1440 ChannelProperties.getProperty("app_name"));
1441 System.setProperty("apple.laf.useScreenMenuBar", "true");
1443 * broken native LAFs on (ARM?) macbooks
1444 set = setQuaquaLookAndFeel();
1445 if ((!set) || !UIManager.getLookAndFeel().getClass().toString()
1446 .toLowerCase(Locale.ROOT).contains("quaqua"))
1448 set = setVaquaLookAndFeel();
1451 set = setFlatLookAndFeel();
1455 private static boolean setLinuxLookAndFeel()
1457 boolean set = false;
1458 set = setFlatLookAndFeel();
1460 set = setMetalLookAndFeel();
1461 // avoid GtkLookAndFeel -- not good results especially on HiDPI
1463 set = setNimbusLookAndFeel();
1467 private static void showUsage()
1470 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1471 + "-nodisplay\tRun Jalview without User Interface.\n"
1472 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1473 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1474 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1475 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1476 + "-features FILE\tUse the given file to mark features on the alignment.\n"
1477 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1478 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1479 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1480 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1481 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1482 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1483 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1484 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1485 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1486 + "-png FILE\tCreate PNG image FILE from alignment.\n"
1487 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1488 + "-html FILE\tCreate HTML file from alignment.\n"
1489 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1490 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1491 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1492 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1493 + "-noquestionnaire\tTurn off questionnaire check.\n"
1494 + "-nonews\tTurn off check for Jalview news.\n"
1495 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1496 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1498 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1499 // after all other properties files have been read\n\t
1500 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1501 // passed in correctly)"
1502 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1503 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1504 + "-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"
1505 + "-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"
1506 + "-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"
1507 + "\n~Read documentation in Application or visit https://www.jalview.org for description of Features and Annotations file~\n\n");
1510 private static void startUsageStats(final Desktop desktop)
1513 * start a User Config prompt asking if we can log usage statistics.
1515 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1516 "USAGESTATS", "Jalview Usage Statistics",
1517 "Do you want to help make Jalview better by enabling "
1518 + "the collection of usage statistics with Google Analytics ?"
1519 + "\n\n(you can enable or disable usage tracking in the preferences)",
1526 "Initialising googletracker for usage stats.");
1527 Cache.initGoogleTracker();
1528 Console.debug("Tracking enabled.");
1535 Console.debug("Not enabling Google Tracking.");
1538 desktop.addDialogThread(prompter);
1542 * Locate the given string as a file and pass it to the groovy interpreter.
1544 * @param groovyscript
1545 * the script to execute
1546 * @param jalviewContext
1547 * the Jalview Desktop object passed in to the groovy binding as the
1550 protected void executeGroovyScript(String groovyscript, AlignFrame af)
1553 * for scripts contained in files
1560 if (groovyscript.trim().equals("STDIN"))
1562 // read from stdin into a tempfile and execute it
1565 tfile = File.createTempFile("jalview", "groovy");
1566 PrintWriter outfile = new PrintWriter(
1567 new OutputStreamWriter(new FileOutputStream(tfile)));
1568 BufferedReader br = new BufferedReader(
1569 new InputStreamReader(System.in));
1571 while ((line = br.readLine()) != null)
1573 outfile.write(line + "\n");
1579 } catch (Exception ex)
1581 System.err.println("Failed to read from STDIN into tempfile "
1582 + ((tfile == null) ? "(tempfile wasn't created)"
1583 : tfile.toString()));
1584 ex.printStackTrace();
1589 sfile = tfile.toURI().toURL();
1590 } catch (Exception x)
1593 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1595 x.printStackTrace();
1603 sfile = new URI(groovyscript).toURL();
1604 } catch (Exception x)
1606 tfile = new File(groovyscript);
1607 if (!tfile.exists())
1609 System.err.println("File '" + groovyscript + "' does not exist.");
1612 if (!tfile.canRead())
1614 System.err.println("File '" + groovyscript + "' cannot be read.");
1617 if (tfile.length() < 1)
1619 System.err.println("File '" + groovyscript + "' is empty.");
1624 sfile = tfile.getAbsoluteFile().toURI().toURL();
1625 } catch (Exception ex)
1627 System.err.println("Failed to create a file URL for "
1628 + tfile.getAbsoluteFile());
1635 Map<String, java.lang.Object> vbinding = new HashMap<>();
1636 vbinding.put("Jalview", this);
1639 vbinding.put("currentAlFrame", af);
1641 Binding gbinding = new Binding(vbinding);
1642 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1643 gse.run(sfile.toString(), gbinding);
1644 if ("STDIN".equals(groovyscript))
1646 // delete temp file that we made -
1647 // only if it was successfully executed
1650 } catch (Exception e)
1652 System.err.println("Exception Whilst trying to execute file " + sfile
1653 + " as a groovy script.");
1654 e.printStackTrace(System.err);
1659 public static boolean isHeadlessMode()
1661 String isheadless = System.getProperty("java.awt.headless");
1662 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1669 public AlignFrame[] getAlignFrames()
1671 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1672 : Desktop.getAlignFrames();
1677 * jalview.bin.Jalview.quit() will just run the non-GUI shutdownHook and exit
1681 // System.exit will run the shutdownHook first
1682 Jalview.exit("Quitting now. Bye!", 0);
1685 public static AlignFrame getCurrentAlignFrame()
1687 return Jalview.currentAlignFrame;
1690 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1692 Jalview.currentAlignFrame = currentAlignFrame;
1695 protected Commands getCommands()
1700 public static void exit(String message, int exitcode)
1702 Console.debug("Using Jalview.exit");
1703 if (message != null)
1705 Console.info(message);
1707 Console.error(message);
1709 System.exit(exitcode);
1713 * testoutput for string values
1715 protected static void testoutput(ArgParser ap, Arg a, String s1,
1718 BootstrapArgs bsa = ap.getBootstrapArgs();
1719 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1721 if (!((s1 == null && s2 == null) || (s1 != null && s1.equals(s2))))
1723 Console.debug("testoutput with unmatching values '" + s1 + "' and '"
1724 + s2 + "' for arg " + a.argString());
1727 boolean isset = a.hasOption(Opt.BOOTSTRAP) ? bsa.contains(a)
1731 Console.warn("Arg '" + a.getName() + "' not set at all");
1734 testoutput(true, a, s1, s2);
1737 protected static void testoutput(BootstrapArgs bsa, Arg a, String s1,
1740 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1742 if (!((s1 == null && s2 == null) || (s1 != null && s1.equals(s2))))
1744 Console.debug("testoutput with unmatching values '" + s1 + "' and '"
1745 + s2 + "' for arg " + a.argString());
1748 if (!a.hasOption(Opt.BOOTSTRAP))
1750 Console.error("Non-bootstrap Arg '" + a.getName()
1751 + "' given to testoutput(BootstrapArgs bsa, Arg a, String s1, String s2) with only BootstrapArgs");
1753 if (!bsa.contains(a))
1755 Console.warn("Arg '" + a.getName() + "' not set at all");
1758 testoutput(true, a, s1, s2);
1761 private static void testoutput(boolean yes, Arg a, String s1, String s2)
1763 if (yes && ((s1 == null && s2 == null)
1764 || (s1 != null && s1.equals(s2))))
1766 System.out.println("[TESTOUTPUT] arg " + a.argString() + "='" + s1
1772 * testoutput for boolean values
1774 protected static void testoutput(ArgParser ap, Arg a)
1778 BootstrapArgs bsa = ap.getBootstrapArgs();
1781 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1783 boolean val = a.hasOption(Opt.BOOTSTRAP) ? bsa.getBoolean(a)
1785 boolean isset = a.hasOption(Opt.BOOTSTRAP) ? bsa.contains(a)
1789 Console.warn("Arg '" + a.getName() + "' not set at all");
1795 protected static void testoutput(BootstrapArgs bsa, Arg a)
1797 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1799 if (!a.hasOption(Opt.BOOTSTRAP))
1801 Console.warn("Non-bootstrap Arg '" + a.getName()
1802 + "' given to testoutput(BootstrapArgs bsa, Arg a) with only BootstrapArgs");
1805 if (!bsa.contains(a))
1807 Console.warn("Arg '" + a.getName() + "' not set at all");
1810 testoutput(bsa.getBoolean(a), a);
1813 private static void testoutput(boolean yes, Arg a)
1815 System.out.println("[TESTOUTPUT] arg "
1816 + (yes ? a.argString() : a.negateArgString()) + " was set");