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 List<Arg> helpArgs = bootstrapArgs.getArgsOfType(Type.HELP);
498 System.out.println(Arg.usage(helpArgs));
499 Jalview.exit(null, 0);
501 if (aparser.contains("help") || aparser.contains("h"))
504 * Now using new usage statement.
507 System.out.println(Arg.usage());
508 Jalview.exit(null, 0);
511 if (bootstrapArgs.contains(Arg.HEADLESS))
513 System.setProperty("java.awt.headless", "true");
515 headlessArg = bootstrapArgs.getBoolean(Arg.HEADLESS);
517 if (aparser.contains("nodisplay") || aparser.contains("nogui")
518 || aparser.contains("headless"))
520 System.setProperty("java.awt.headless", "true");
526 // allow https handshakes to download intermediate certs if necessary
527 System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
529 String jabawsUrl = bootstrapArgs.get(Arg.JABAWS);
530 if (jabawsUrl == null)
531 jabawsUrl = aparser.getValue("jabaws");
532 if (jabawsUrl != null)
536 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
538 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
539 testoutput(bootstrapArgs, Arg.JABAWS,
540 "http://www.compbio.dundee.ac.uk/jabaws", jabawsUrl);
541 } catch (MalformedURLException e)
544 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
549 List<String> setprops = new ArrayList<>();
550 if (bootstrapArgs.contains(Arg.SETPROP))
552 setprops = bootstrapArgs.getValueList(Arg.SETPROP);
556 String sp = aparser.getValue("setprop");
560 sp = aparser.getValue("setprop");
563 for (String setprop : setprops)
565 int p = setprop.indexOf('=');
569 .println("Ignoring invalid setprop argument : " + setprop);
573 System.out.println("Executing setprop argument: " + setprop);
576 Cache.setProperty(setprop.substring(0, p),
577 setprop.substring(p + 1));
579 // DISABLED FOR SECURITY REASONS
580 // TODO: add a property to allow properties to be overriden by cli args
581 // Cache.setProperty(setprop.substring(0,p), setprop.substring(p+1));
584 if (System.getProperty("java.awt.headless") != null
585 && System.getProperty("java.awt.headless").equals("true"))
589 System.setProperty("http.agent",
590 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
594 Console.initLogger();
597 NoClassDefFoundError error)
599 error.printStackTrace();
600 String message = "\nEssential logging libraries not found."
601 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
602 Jalview.exit(message, 0);
606 if (!(headless || headlessArg))
610 * configure 'full' SO model if preferences say to, else use the default (full SO)
611 * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
613 boolean soDefault = !Platform.isJS();
614 if (Cache.getDefault("USE_FULL_SO", soDefault))
616 SequenceOntologyFactory.setInstance(new SequenceOntology());
619 if (!(headless || headlessArg))
621 Desktop.nosplash = "false".equals(bootstrapArgs.get(Arg.SPLASH))
622 || aparser.contains("nosplash")
623 || Cache.getDefault("SPLASH", "true").equals("false");
624 desktop = new Desktop();
625 desktop.setInBatchMode(true); // indicate we are starting up
629 JalviewTaskbar.setTaskbar(this);
630 } catch (Exception e)
632 Console.info("Cannot set Taskbar");
633 Console.error(e.getMessage());
634 // e.printStackTrace();
635 } catch (Throwable t)
637 Console.info("Cannot set Taskbar");
638 Console.error(t.getMessage());
639 // t.printStackTrace();
642 // set Proxy settings before all the internet calls
643 Cache.setProxyPropertiesFromPreferences();
645 desktop.setVisible(true);
647 if (!Platform.isJS())
656 * Check to see that the JVM version being run is suitable for the Java
657 * version this Jalview was compiled for. Popup a warning if not.
659 if (!LaunchUtils.checkJavaVersion())
661 Console.warn("The Java version being used (Java "
662 + LaunchUtils.getJavaVersion()
663 + ") may lead to problems. This installation of Jalview should be used with Java "
664 + LaunchUtils.getJavaCompileVersion() + ".");
667 .getBooleanUserPreference("IGNORE_JVM_WARNING_POPUP"))
670 MessageManager.getString("label.continue") };
671 JOptionPane.showOptionDialog(null,
672 MessageManager.formatMessage(
673 "warning.wrong_jvm_version_message",
674 LaunchUtils.getJavaVersion(),
675 LaunchUtils.getJavaCompileVersion()),
677 .getString("warning.wrong_jvm_version_title"),
678 JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
679 null, options, options[0]);
683 boolean webservicediscovery = bootstrapArgs
684 .getBoolean(Arg.WEBSERVICEDISCOVERY);
685 if (aparser.contains("nowebservicediscovery"))
686 webservicediscovery = false;
687 if (webservicediscovery)
689 desktop.startServiceDiscovery();
693 testoutput(argparser, Arg.WEBSERVICEDISCOVERY);
696 boolean usagestats = bootstrapArgs.getBoolean(Arg.USAGESTATS);
697 if (aparser.contains("nousagestats"))
701 startUsageStats(desktop);
702 testoutput(argparser, Arg.USAGESTATS);
706 System.out.println("CMD [-nousagestats] executed successfully!");
707 testoutput(argparser, Arg.USAGESTATS);
710 boolean questionnaire = bootstrapArgs.getBoolean(Arg.QUESTIONNAIRE);
711 if (aparser.contains("noquestionnaire"))
712 questionnaire = false;
715 String url = aparser.getValue("questionnaire");
718 // Start the desktop questionnaire prompter with the specified
720 Console.debug("Starting questionnaire url at " + url);
721 desktop.checkForQuestionnaire(url);
722 System.out.println("CMD questionnaire[-" + url
723 + "] executed successfully!");
727 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
729 // Start the desktop questionnaire prompter with the specified
732 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
734 String defurl = "https://www.jalview.org/cgi-bin/questionnaire.pl";
736 "Starting questionnaire with default url: " + defurl);
737 desktop.checkForQuestionnaire(defurl);
744 .println("CMD [-noquestionnaire] executed successfully!");
745 testoutput(argparser, Arg.QUESTIONNAIRE);
748 if ((!aparser.contains("nonews")
749 && Cache.getProperty("NONEWS") == null
750 && !"false".equals(bootstrapArgs.get(Arg.NEWS)))
751 || "true".equals(bootstrapArgs.get(Arg.NEWS)))
753 desktop.checkForNews();
756 if (!aparser.contains("nohtmltemplates")
757 && Cache.getProperty("NOHTMLTEMPLATES") == null)
759 BioJsHTMLOutput.updateBioJS();
763 // Run Commands from cli
764 cmds = new Commands(argparser, headlessArg);
765 boolean commandsSuccess = cmds.argsWereParsed();
770 Jalview.exit("Successfully completed commands in headless mode", 0);
772 Console.info("Successfully completed commands");
778 Jalview.exit("Error when running Commands in headless mode", 1);
780 Console.warn("Error when running commands");
783 // Check if JVM and compile version might cause problems and log if it
785 if (headless && !Platform.isJS() && !LaunchUtils.checkJavaVersion())
787 Console.warn("The Java version being used (Java "
788 + LaunchUtils.getJavaVersion()
789 + ") may lead to problems. This installation of Jalview should be used with Java "
790 + LaunchUtils.getJavaCompileVersion() + ".");
793 String file = null, data = null;
795 FileFormatI format = null;
797 DataSourceType protocol = null;
799 FileLoader fileLoader = new FileLoader(!headless);
801 String groovyscript = null; // script to execute after all loading is
802 // completed one way or another
803 // extract groovy argument and execute if necessary
804 groovyscript = aparser.getValue("groovy", true);
805 file = aparser.getValue("open", true);
807 if (file == null && desktop == null && !commandsSuccess)
809 Jalview.exit("No files to open!", 1);
813 // Finally, deal with the remaining input data.
818 desktop.setProgressBar(
820 .getString("status.processing_commandline_args"),
821 progress = System.currentTimeMillis());
823 System.out.println("CMD [-open " + file + "] executed successfully!");
825 if (!Platform.isJS())
827 * ignore in JavaScript -- can't just file existence - could load it?
832 if (!HttpUtils.startsWithHttpOrHttps(file))
834 if (!(new File(file)).exists())
839 "Can't find file '" + file + "' in headless mode", 1);
841 Console.warn("Can't find file'" + file + "'");
846 protocol = AppletFormatAdapter.checkProtocol(file);
850 format = new IdentifyFile().identify(file, protocol);
851 } catch (FileFormatException e1)
856 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
860 System.out.println("error");
864 setCurrentAlignFrame(af);
865 data = aparser.getValue("colour", true);
868 data.replaceAll("%20", " ");
870 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
871 af.getViewport(), af.getViewport().getAlignment(), data);
876 "CMD [-colour " + data + "] executed successfully!");
881 // Must maintain ability to use the groups flag
882 data = aparser.getValue("groups", true);
885 af.parseFeaturesFile(data,
886 AppletFormatAdapter.checkProtocol(data));
887 // System.out.println("Added " + data);
889 "CMD groups[-" + data + "] executed successfully!");
891 data = aparser.getValue("features", true);
894 af.parseFeaturesFile(data,
895 AppletFormatAdapter.checkProtocol(data));
896 // System.out.println("Added " + data);
898 "CMD [-features " + data + "] executed successfully!");
901 data = aparser.getValue("annotations", true);
904 af.loadJalviewDataFile(data, null, null, null);
905 // System.out.println("Added " + data);
907 "CMD [-annotations " + data + "] executed successfully!");
909 // set or clear the sortbytree flag.
910 if (aparser.contains("sortbytree"))
912 af.getViewport().setSortByTree(true);
913 if (af.getViewport().getSortByTree())
915 System.out.println("CMD [-sortbytree] executed successfully!");
918 if (aparser.contains("no-annotation"))
920 af.getViewport().setShowAnnotation(false);
921 if (!af.getViewport().isShowAnnotation())
923 System.out.println("CMD no-annotation executed successfully!");
926 if (aparser.contains("nosortbytree"))
928 af.getViewport().setSortByTree(false);
929 if (!af.getViewport().getSortByTree())
932 .println("CMD [-nosortbytree] executed successfully!");
935 data = aparser.getValue("tree", true);
941 "CMD [-tree " + data + "] executed successfully!");
942 NewickFile nf = new NewickFile(data,
943 AppletFormatAdapter.checkProtocol(data));
945 .setCurrentTree(af.showNewickTree(nf, data).getTree());
946 } catch (IOException ex)
948 System.err.println("Couldn't add tree " + data);
949 ex.printStackTrace(System.err);
952 // TODO - load PDB structure(s) to alignment JAL-629
953 // (associate with identical sequence in alignment, or a specified
955 if (groovyscript != null)
957 // Execute the groovy script after we've done all the rendering stuff
958 // and before any images or figures are generated.
959 System.out.println("Executing script " + groovyscript);
960 executeGroovyScript(groovyscript, af);
961 System.out.println("CMD groovy[" + groovyscript
962 + "] executed successfully!");
965 String imageName = "unnamed.png";
966 while (aparser.getSize() > 1)
968 String outputFormat = aparser.nextValue();
969 file = aparser.nextValue();
971 if (outputFormat.equalsIgnoreCase("png"))
973 af.createPNG(new File(file));
974 imageName = (new File(file)).getName();
975 System.out.println("Creating PNG image: " + file);
978 else if (outputFormat.equalsIgnoreCase("svg"))
980 File imageFile = new File(file);
981 imageName = imageFile.getName();
982 af.createSVG(imageFile);
983 System.out.println("Creating SVG image: " + file);
986 else if (outputFormat.equalsIgnoreCase("html"))
988 File imageFile = new File(file);
989 imageName = imageFile.getName();
990 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
991 htmlSVG.exportHTML(file);
993 System.out.println("Creating HTML image: " + file);
996 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
1000 System.err.println("The output html file must not be null");
1005 BioJsHTMLOutput.refreshVersionInfo(
1006 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1007 } catch (URISyntaxException e)
1009 e.printStackTrace();
1011 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1012 bjs.exportHTML(file);
1014 .println("Creating BioJS MSA Viwer HTML file: " + file);
1017 else if (outputFormat.equalsIgnoreCase("imgMap"))
1019 af.createImageMap(new File(file), imageName);
1020 System.out.println("Creating image map: " + file);
1023 else if (outputFormat.equalsIgnoreCase("eps"))
1025 File outputFile = new File(file);
1027 "Creating EPS file: " + outputFile.getAbsolutePath());
1028 af.createEPS(outputFile);
1031 FileFormatI outFormat = null;
1034 outFormat = FileFormats.getInstance().forName(outputFormat);
1035 } catch (Exception formatP)
1037 System.out.println("Couldn't parse " + outFormat
1038 + " as a valid Jalview format string.");
1040 if (outFormat != null)
1042 if (!outFormat.isWritable())
1045 "This version of Jalview does not support alignment export as "
1050 af.saveAlignment(file, outFormat);
1051 if (af.isSaveAlignmentSuccessful())
1053 System.out.println("Written alignment in "
1054 + outFormat.getName() + " format to " + file);
1058 System.out.println("Error writing file " + file + " in "
1059 + outFormat.getName() + " format!!");
1066 while (aparser.getSize() > 0)
1068 System.out.println("Unknown arg: " + aparser.nextValue());
1073 AlignFrame startUpAlframe = null;
1074 // We'll only open the default file if the desktop is visible.
1076 // ////////////////////
1078 if (!Platform.isJS() && !headless && file == null
1079 && Cache.getDefault("SHOW_STARTUP_FILE", true)
1080 && !cmds.commandArgsProvided())
1081 // don't open the startup file if command line args have been processed
1082 // (&& !Commands.commandArgsProvided())
1089 file = Cache.getDefault("STARTUP_FILE",
1090 Cache.getDefault("www.jalview.org", "https://www.jalview.org")
1091 + "/examples/exampleFile_2_7.jvp");
1092 if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar")
1094 "http://www.jalview.org/examples/exampleFile_2_7.jar"))
1096 file.replace("http:", "https:");
1097 // hardwire upgrade of the startup file
1098 file.replace("_2_3", "_2_7");
1099 file.replace("2_7.jar", "2_7.jvp");
1100 // and remove the stale setting
1101 Cache.removeProperty("STARTUP_FILE");
1104 protocol = AppletFormatAdapter.checkProtocol(file);
1106 if (file.endsWith(".jar"))
1108 format = FileFormat.Jalview;
1114 format = new IdentifyFile().identify(file, protocol);
1115 } catch (FileFormatException e)
1121 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
1123 // don't ask to save when quitting if only the startup file has been
1125 Console.debug("Resetting up-to-date flag for startup file");
1126 startUpAlframe.getViewport().setSavedUpToDate(true);
1127 // extract groovy arguments before anything else.
1130 // Once all other stuff is done, execute any groovy scripts (in order)
1131 if (groovyscript != null)
1133 if (Cache.groovyJarsPresent())
1135 System.out.println("Executing script " + groovyscript);
1136 executeGroovyScript(groovyscript, startUpAlframe);
1141 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
1145 // and finally, turn off batch mode indicator - if the desktop still exists
1146 if (desktop != null)
1150 desktop.setProgressBar(null, progress);
1152 desktop.setInBatchMode(false);
1156 private static void setLookAndFeel()
1158 // property laf = "crossplatform", "system", "gtk", "metal", "nimbus",
1160 // If not set (or chosen laf fails), use the normal SystemLaF and if on Mac,
1161 // try Quaqua/Vaqua.
1162 String lafProp = System.getProperty("laf");
1163 String lafSetting = Cache.getDefault("PREFERRED_LAF", null);
1164 String laf = "none";
1165 if (lafProp != null)
1169 else if (lafSetting != null)
1173 boolean lafSet = false;
1176 case "crossplatform":
1177 lafSet = setCrossPlatformLookAndFeel();
1180 Console.error("Could not set requested laf=" + laf);
1184 lafSet = setSystemLookAndFeel();
1187 Console.error("Could not set requested laf=" + laf);
1191 lafSet = setGtkLookAndFeel();
1194 Console.error("Could not set requested laf=" + laf);
1198 lafSet = setMetalLookAndFeel();
1201 Console.error("Could not set requested laf=" + laf);
1205 lafSet = setNimbusLookAndFeel();
1208 Console.error("Could not set requested laf=" + laf);
1212 lafSet = setFlatLookAndFeel();
1215 Console.error("Could not set requested laf=" + laf);
1219 lafSet = setMacLookAndFeel();
1222 Console.error("Could not set requested laf=" + laf);
1228 Console.error("Requested laf=" + laf + " not implemented");
1232 setSystemLookAndFeel();
1233 if (Platform.isLinux())
1235 setLinuxLookAndFeel();
1237 if (Platform.isMac())
1239 setMacLookAndFeel();
1244 private static boolean setCrossPlatformLookAndFeel()
1246 boolean set = false;
1249 UIManager.setLookAndFeel(
1250 UIManager.getCrossPlatformLookAndFeelClassName());
1252 } catch (Exception ex)
1254 Console.error("Unexpected Look and Feel Exception");
1255 Console.error(ex.getMessage());
1256 Console.debug(Cache.getStackTraceString(ex));
1261 private static boolean setSystemLookAndFeel()
1263 boolean set = false;
1266 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1268 } catch (Exception ex)
1270 Console.error("Unexpected Look and Feel Exception");
1271 Console.error(ex.getMessage());
1272 Console.debug(Cache.getStackTraceString(ex));
1277 private static boolean setSpecificLookAndFeel(String name,
1278 String className, boolean nameStartsWith)
1280 boolean set = false;
1283 for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
1285 if (info.getName() != null && nameStartsWith
1286 ? info.getName().toLowerCase(Locale.ROOT)
1287 .startsWith(name.toLowerCase(Locale.ROOT))
1288 : info.getName().toLowerCase(Locale.ROOT)
1289 .equals(name.toLowerCase(Locale.ROOT)))
1291 className = info.getClassName();
1295 UIManager.setLookAndFeel(className);
1297 } catch (Exception ex)
1299 Console.error("Unexpected Look and Feel Exception");
1300 Console.error(ex.getMessage());
1301 Console.debug(Cache.getStackTraceString(ex));
1306 private static boolean setGtkLookAndFeel()
1308 return setSpecificLookAndFeel("gtk",
1309 "com.sun.java.swing.plaf.gtk.GTKLookAndFeel", true);
1312 private static boolean setMetalLookAndFeel()
1314 return setSpecificLookAndFeel("metal",
1315 "javax.swing.plaf.metal.MetalLookAndFeel", false);
1318 private static boolean setNimbusLookAndFeel()
1320 return setSpecificLookAndFeel("nimbus",
1321 "javax.swing.plaf.nimbus.NimbusLookAndFeel", false);
1324 private static boolean setFlatLookAndFeel()
1326 boolean set = false;
1327 if (SystemInfo.isMacOS)
1331 UIManager.setLookAndFeel(
1332 "com.formdev.flatlaf.themes.FlatMacLightLaf");
1334 Console.debug("Using FlatMacLightLaf");
1335 } catch (ClassNotFoundException | InstantiationException
1336 | IllegalAccessException | UnsupportedLookAndFeelException e)
1338 Console.debug("Exception loading FlatLightLaf", e);
1340 System.setProperty("apple.laf.useScreenMenuBar", "true");
1341 System.setProperty("apple.awt.application.name",
1342 ChannelProperties.getProperty("app_name"));
1343 System.setProperty("apple.awt.application.appearance", "system");
1344 if (SystemInfo.isMacFullWindowContentSupported
1345 && Desktop.desktop != null)
1347 Console.debug("Setting transparent title bar");
1348 Desktop.desktop.getRootPane()
1349 .putClientProperty("apple.awt.fullWindowContent", true);
1350 Desktop.desktop.getRootPane()
1351 .putClientProperty("apple.awt.transparentTitleBar", true);
1352 Desktop.desktop.getRootPane()
1353 .putClientProperty("apple.awt.fullscreenable", true);
1355 SwingUtilities.invokeLater(() -> {
1356 FlatMacLightLaf.setup();
1358 Console.debug("Using FlatMacLightLaf");
1365 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1367 Console.debug("Using FlatLightLaf");
1368 } catch (ClassNotFoundException | InstantiationException
1369 | IllegalAccessException | UnsupportedLookAndFeelException e)
1371 Console.debug("Exception loading FlatLightLaf", e);
1373 // Windows specific properties here
1374 SwingUtilities.invokeLater(() -> {
1375 FlatLightLaf.setup();
1377 Console.debug("Using FlatLightLaf");
1380 else if (SystemInfo.isLinux)
1384 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1386 Console.debug("Using FlatLightLaf");
1387 } catch (ClassNotFoundException | InstantiationException
1388 | IllegalAccessException | UnsupportedLookAndFeelException e)
1390 Console.debug("Exception loading FlatLightLaf", e);
1392 // enable custom window decorations
1393 JFrame.setDefaultLookAndFeelDecorated(true);
1394 JDialog.setDefaultLookAndFeelDecorated(true);
1395 SwingUtilities.invokeLater(() -> {
1396 FlatLightLaf.setup();
1398 Console.debug("Using FlatLightLaf");
1406 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1408 Console.debug("Using FlatLightLaf");
1409 } catch (ClassNotFoundException | InstantiationException
1410 | IllegalAccessException | UnsupportedLookAndFeelException e)
1412 Console.debug("Exception loading FlatLightLaf", e);
1418 UIManager.put("TabbedPane.tabType", "card");
1419 UIManager.put("TabbedPane.showTabSeparators", true);
1420 UIManager.put("TabbedPane.showContentSeparator", true);
1421 UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
1422 UIManager.put("TabbedPane.tabsOverlapBorder", true);
1423 UIManager.put("TabbedPane.hasFullBorder", true);
1424 UIManager.put("TabbedPane.tabLayoutPolicy", "scroll");
1425 UIManager.put("TabbedPane.scrollButtonsPolicy", "asNeeded");
1426 UIManager.put("TabbedPane.smoothScrolling", true);
1427 UIManager.put("TabbedPane.tabWidthMode", "compact");
1428 UIManager.put("TabbedPane.selectedBackground", Color.white);
1431 Desktop.setLiveDragMode(Cache.getDefault("FLAT_LIVE_DRAG_MODE", true));
1435 private static boolean setMacLookAndFeel()
1437 boolean set = false;
1438 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
1439 ChannelProperties.getProperty("app_name"));
1440 System.setProperty("apple.laf.useScreenMenuBar", "true");
1442 * broken native LAFs on (ARM?) macbooks
1443 set = setQuaquaLookAndFeel();
1444 if ((!set) || !UIManager.getLookAndFeel().getClass().toString()
1445 .toLowerCase(Locale.ROOT).contains("quaqua"))
1447 set = setVaquaLookAndFeel();
1450 set = setFlatLookAndFeel();
1454 private static boolean setLinuxLookAndFeel()
1456 boolean set = false;
1457 set = setFlatLookAndFeel();
1459 set = setMetalLookAndFeel();
1460 // avoid GtkLookAndFeel -- not good results especially on HiDPI
1462 set = setNimbusLookAndFeel();
1466 private static void showUsage()
1469 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1470 + "-nodisplay\tRun Jalview without User Interface.\n"
1471 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1472 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1473 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1474 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1475 + "-features FILE\tUse the given file to mark features on the alignment.\n"
1476 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1477 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1478 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1479 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1480 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1481 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1482 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1483 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1484 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1485 + "-png FILE\tCreate PNG image FILE from alignment.\n"
1486 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1487 + "-html FILE\tCreate HTML file from alignment.\n"
1488 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1489 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1490 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1491 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1492 + "-noquestionnaire\tTurn off questionnaire check.\n"
1493 + "-nonews\tTurn off check for Jalview news.\n"
1494 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1495 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1497 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1498 // after all other properties files have been read\n\t
1499 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1500 // passed in correctly)"
1501 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1502 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1503 + "-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"
1504 + "-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"
1505 + "-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"
1506 + "\n~Read documentation in Application or visit https://www.jalview.org for description of Features and Annotations file~\n\n");
1509 private static void startUsageStats(final Desktop desktop)
1512 * start a User Config prompt asking if we can log usage statistics.
1514 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1515 "USAGESTATS", "Jalview Usage Statistics",
1516 "Do you want to help make Jalview better by enabling "
1517 + "the collection of usage statistics with Google Analytics ?"
1518 + "\n\n(you can enable or disable usage tracking in the preferences)",
1525 "Initialising googletracker for usage stats.");
1526 Cache.initGoogleTracker();
1527 Console.debug("Tracking enabled.");
1534 Console.debug("Not enabling Google Tracking.");
1537 desktop.addDialogThread(prompter);
1541 * Locate the given string as a file and pass it to the groovy interpreter.
1543 * @param groovyscript
1544 * the script to execute
1545 * @param jalviewContext
1546 * the Jalview Desktop object passed in to the groovy binding as the
1549 protected void executeGroovyScript(String groovyscript, AlignFrame af)
1552 * for scripts contained in files
1559 if (groovyscript.trim().equals("STDIN"))
1561 // read from stdin into a tempfile and execute it
1564 tfile = File.createTempFile("jalview", "groovy");
1565 PrintWriter outfile = new PrintWriter(
1566 new OutputStreamWriter(new FileOutputStream(tfile)));
1567 BufferedReader br = new BufferedReader(
1568 new InputStreamReader(System.in));
1570 while ((line = br.readLine()) != null)
1572 outfile.write(line + "\n");
1578 } catch (Exception ex)
1580 System.err.println("Failed to read from STDIN into tempfile "
1581 + ((tfile == null) ? "(tempfile wasn't created)"
1582 : tfile.toString()));
1583 ex.printStackTrace();
1588 sfile = tfile.toURI().toURL();
1589 } catch (Exception x)
1592 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1594 x.printStackTrace();
1602 sfile = new URI(groovyscript).toURL();
1603 } catch (Exception x)
1605 tfile = new File(groovyscript);
1606 if (!tfile.exists())
1608 System.err.println("File '" + groovyscript + "' does not exist.");
1611 if (!tfile.canRead())
1613 System.err.println("File '" + groovyscript + "' cannot be read.");
1616 if (tfile.length() < 1)
1618 System.err.println("File '" + groovyscript + "' is empty.");
1623 sfile = tfile.getAbsoluteFile().toURI().toURL();
1624 } catch (Exception ex)
1626 System.err.println("Failed to create a file URL for "
1627 + tfile.getAbsoluteFile());
1634 Map<String, java.lang.Object> vbinding = new HashMap<>();
1635 vbinding.put("Jalview", this);
1638 vbinding.put("currentAlFrame", af);
1640 Binding gbinding = new Binding(vbinding);
1641 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1642 gse.run(sfile.toString(), gbinding);
1643 if ("STDIN".equals(groovyscript))
1645 // delete temp file that we made -
1646 // only if it was successfully executed
1649 } catch (Exception e)
1651 System.err.println("Exception Whilst trying to execute file " + sfile
1652 + " as a groovy script.");
1653 e.printStackTrace(System.err);
1658 public static boolean isHeadlessMode()
1660 String isheadless = System.getProperty("java.awt.headless");
1661 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1668 public AlignFrame[] getAlignFrames()
1670 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1671 : Desktop.getAlignFrames();
1676 * jalview.bin.Jalview.quit() will just run the non-GUI shutdownHook and exit
1680 // System.exit will run the shutdownHook first
1681 Jalview.exit("Quitting now. Bye!", 0);
1684 public static AlignFrame getCurrentAlignFrame()
1686 return Jalview.currentAlignFrame;
1689 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1691 Jalview.currentAlignFrame = currentAlignFrame;
1694 protected Commands getCommands()
1699 public static void exit(String message, int exitcode)
1701 Console.debug("Using Jalview.exit");
1702 if (message != null)
1704 Console.info(message);
1706 Console.error(message);
1708 System.exit(exitcode);
1712 * testoutput for string values
1714 protected static void testoutput(ArgParser ap, Arg a, String s1,
1717 BootstrapArgs bsa = ap.getBootstrapArgs();
1718 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1720 if (!((s1 == null && s2 == null) || (s1 != null && s1.equals(s2))))
1722 Console.debug("testoutput with unmatching values '" + s1 + "' and '"
1723 + s2 + "' for arg " + a.argString());
1726 boolean isset = a.hasOption(Opt.BOOTSTRAP) ? bsa.contains(a)
1730 Console.warn("Arg '" + a.getName() + "' not set at all");
1733 testoutput(true, a, s1, s2);
1736 protected static void testoutput(BootstrapArgs bsa, Arg a, String s1,
1739 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1741 if (!((s1 == null && s2 == null) || (s1 != null && s1.equals(s2))))
1743 Console.debug("testoutput with unmatching values '" + s1 + "' and '"
1744 + s2 + "' for arg " + a.argString());
1747 if (!a.hasOption(Opt.BOOTSTRAP))
1749 Console.error("Non-bootstrap Arg '" + a.getName()
1750 + "' given to testoutput(BootstrapArgs bsa, Arg a, String s1, String s2) with only BootstrapArgs");
1752 if (!bsa.contains(a))
1754 Console.warn("Arg '" + a.getName() + "' not set at all");
1757 testoutput(true, a, s1, s2);
1760 private static void testoutput(boolean yes, Arg a, String s1, String s2)
1762 if (yes && ((s1 == null && s2 == null)
1763 || (s1 != null && s1.equals(s2))))
1765 System.out.println("[TESTOUTPUT] arg " + a.argString() + "='" + s1
1771 * testoutput for boolean values
1773 protected static void testoutput(ArgParser ap, Arg a)
1777 BootstrapArgs bsa = ap.getBootstrapArgs();
1780 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1782 boolean val = a.hasOption(Opt.BOOTSTRAP) ? bsa.getBoolean(a)
1784 boolean isset = a.hasOption(Opt.BOOTSTRAP) ? bsa.contains(a)
1788 Console.warn("Arg '" + a.getName() + "' not set at all");
1794 protected static void testoutput(BootstrapArgs bsa, Arg a)
1796 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1798 if (!a.hasOption(Opt.BOOTSTRAP))
1800 Console.warn("Non-bootstrap Arg '" + a.getName()
1801 + "' given to testoutput(BootstrapArgs bsa, Arg a) with only BootstrapArgs");
1804 if (!bsa.contains(a))
1806 Console.warn("Arg '" + a.getName() + "' not set at all");
1809 testoutput(bsa.getBoolean(a), a);
1812 private static void testoutput(boolean yes, Arg a)
1814 System.out.println("[TESTOUTPUT] arg "
1815 + (yes ? a.argString() : a.negateArgString()) + " was set");