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;
52 import java.util.stream.Collectors;
54 import javax.swing.JDialog;
55 import javax.swing.JFrame;
56 import javax.swing.JInternalFrame;
57 import javax.swing.JOptionPane;
58 import javax.swing.SwingUtilities;
59 import javax.swing.UIManager;
60 import javax.swing.UIManager.LookAndFeelInfo;
61 import javax.swing.UnsupportedLookAndFeelException;
63 import com.formdev.flatlaf.FlatLightLaf;
64 import com.formdev.flatlaf.themes.FlatMacLightLaf;
65 import com.formdev.flatlaf.util.SystemInfo;
66 import com.threerings.getdown.util.LaunchUtil;
68 //import edu.stanford.ejalbert.launching.IBrowserLaunching;
69 import groovy.lang.Binding;
70 import groovy.util.GroovyScriptEngine;
71 import jalview.bin.argparser.Arg;
72 import jalview.bin.argparser.Arg.Opt;
73 import jalview.bin.argparser.Arg.Type;
74 import jalview.bin.argparser.ArgParser;
75 import jalview.bin.argparser.BootstrapArgs;
76 import jalview.bin.groovy.JalviewObject;
77 import jalview.bin.groovy.JalviewObjectI;
78 import jalview.ext.so.SequenceOntology;
79 import jalview.gui.AlignFrame;
80 import jalview.gui.Desktop;
81 import jalview.gui.JvOptionPane;
82 import jalview.gui.PromptUserConfig;
83 import jalview.gui.QuitHandler;
84 import jalview.gui.QuitHandler.QResponse;
85 import jalview.gui.StructureViewerBase;
86 import jalview.io.AppletFormatAdapter;
87 import jalview.io.BioJsHTMLOutput;
88 import jalview.io.DataSourceType;
89 import jalview.io.FileFormat;
90 import jalview.io.FileFormatException;
91 import jalview.io.FileFormatI;
92 import jalview.io.FileFormats;
93 import jalview.io.FileLoader;
94 import jalview.io.HtmlSvgOutput;
95 import jalview.io.IdentifyFile;
96 import jalview.io.NewickFile;
97 import jalview.io.exceptions.ImageOutputException;
98 import jalview.io.gff.SequenceOntologyFactory;
99 import jalview.schemes.ColourSchemeI;
100 import jalview.schemes.ColourSchemeProperty;
101 import jalview.util.ChannelProperties;
102 import jalview.util.HttpUtils;
103 import jalview.util.LaunchUtils;
104 import jalview.util.MessageManager;
105 import jalview.util.Platform;
106 import jalview.ws.jws2.Jws2Discoverer;
109 * Main class for Jalview Application <br>
111 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
112 * jalview.bin.Jalview
114 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
115 * jalview.bin.Jalview jalview.bin.Jalview
117 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
118 * embellish '*' to e.g. '*.jar')
121 * @version $Revision$
123 public class Jalview implements JalviewObjectI
127 Platform.getURLCommandArguments();
128 Platform.addJ2SDirectDatabaseCall("https://www.jalview.org");
129 Platform.addJ2SDirectDatabaseCall("http://www.jalview.org");
130 Platform.addJ2SDirectDatabaseCall("http://www.compbio.dundee.ac.uk");
131 Platform.addJ2SDirectDatabaseCall("https://www.compbio.dundee.ac.uk");
135 * singleton instance of this class
137 private static Jalview instance;
139 private Desktop desktop;
141 protected Commands cmds;
143 public AlignFrame currentAlignFrame = null;
145 private ArgParser argparser = null;
147 private BootstrapArgs bootstrapArgs = null;
149 private boolean QUIET = false;
151 public static boolean quiet()
153 return Jalview.getInstance() != null && Jalview.getInstance().QUIET;
158 if (!Platform.isJS())
165 // grab all the rights we can for the JVM
166 Policy.setPolicy(new Policy()
169 public PermissionCollection getPermissions(CodeSource codesource)
171 Permissions perms = new Permissions();
172 perms.add(new AllPermission());
177 public void refresh()
185 * keep track of feature fetching tasks.
193 * TODO: generalise to track all jalview events to orchestrate batch processing
197 private int queued = 0;
199 private int running = 0;
201 public FeatureFetcher()
206 public void addFetcher(final AlignFrame af,
207 final Vector<String> dasSources)
209 final long id = System.currentTimeMillis();
211 final FeatureFetcher us = this;
212 new Thread(new Runnable()
224 af.setProgressBar(MessageManager
225 .getString("status.das_features_being_retrived"), id);
226 af.featureSettings_actionPerformed(null);
227 af.setProgressBar(null, id);
236 public synchronized boolean allFinished()
238 return queued == 0 && running == 0;
243 public static Jalview getInstance()
249 * main class for Jalview application
252 * open <em>filename</em>
254 public static void main(String[] args)
256 // setLogging(); // BH - for event debugging in JavaScript
257 instance = new Jalview();
258 instance.doMain(args);
261 private static void logClass(String name)
263 // BH - for event debugging in JavaScript
264 ConsoleHandler consoleHandler = new ConsoleHandler();
265 consoleHandler.setLevel(Level.ALL);
266 Logger logger = Logger.getLogger(name);
267 logger.setLevel(Level.ALL);
268 logger.addHandler(consoleHandler);
271 @SuppressWarnings("unused")
272 private static void setLogging()
280 Console.outPrintln("not in js");
283 // BH - for event debugging in JavaScript (Java mode only)
284 if (!Platform.isJS())
291 Logger.getLogger("").setLevel(Level.ALL);
292 logClass("java.awt.EventDispatchThread");
293 logClass("java.awt.EventQueue");
294 logClass("java.awt.Component");
295 logClass("java.awt.focus.Component");
296 logClass("java.awt.focus.DefaultKeyboardFocusManager");
304 void doMain(String[] args)
306 if (!Platform.isJS())
308 System.setSecurityManager(null);
311 if (args == null || args.length == 0 || (args.length == 1
312 && (args[0] == null || args[0].length() == 0)))
314 args = new String[] {};
317 // get args needed before proper ArgParser
318 bootstrapArgs = BootstrapArgs.getBootstrapArgs(args);
320 if (!Platform.isJS())
322 // are we being --quiet ?
323 if (bootstrapArgs.contains(Arg.QUIET))
326 OutputStream devNull = new OutputStream()
330 public void write(int b)
335 System.setOut(new PrintStream(devNull));
336 // redirecting stderr not working
337 if (bootstrapArgs.getList(Arg.QUIET).size() > 1)
339 System.setErr(new PrintStream(devNull));
343 if (bootstrapArgs.contains(Arg.HELP)
344 || bootstrapArgs.contains(Arg.VERSION))
350 // set individual session preferences
351 if (bootstrapArgs.contains(Arg.P))
353 for (String kev : bootstrapArgs.getValueList(Arg.P))
359 int equalsIndex = kev.indexOf(ArgParser.EQUALS);
360 if (equalsIndex > -1)
362 String key = kev.substring(0, equalsIndex);
363 String val = kev.substring(equalsIndex + 1);
364 Cache.setSessionProperty(key, val);
369 // Move any new getdown-launcher-new.jar into place over old
370 // getdown-launcher.jar
371 String appdirString = System.getProperty("getdownappdir");
372 if (appdirString != null && appdirString.length() > 0)
374 final File appdir = new File(appdirString);
381 LaunchUtil.upgradeGetdown(
382 new File(appdir, "getdown-launcher-old.jar"),
383 new File(appdir, "getdown-launcher.jar"),
384 new File(appdir, "getdown-launcher-new.jar"));
389 if (!quiet() || !bootstrapArgs.outputToStdout()
390 || bootstrapArgs.contains(Arg.VERSION))
393 "Java version: " + System.getProperty("java.version"));
394 Console.outPrintln("Java home: " + System.getProperty("java.home"));
395 Console.outPrintln("Java arch: " + System.getProperty("os.arch") + " "
396 + System.getProperty("os.name") + " "
397 + System.getProperty("os.version"));
399 String val = System.getProperty("sys.install4jVersion");
402 Console.outPrintln("Install4j version: " + val);
404 val = System.getProperty("installer_template_version");
407 Console.outPrintln("Install4j template version: " + val);
409 val = System.getProperty("launcher_version");
412 Console.outPrintln("Launcher version: " + val);
416 if (Platform.isLinux() && LaunchUtils.getJavaVersion() < 11)
418 System.setProperty("flatlaf.uiScale", "1");
421 // get bootstrap properties (mainly for the logger level)
422 Properties bootstrapProperties = Cache
423 .bootstrapProperties(bootstrapArgs.getValue(Arg.PROPS));
425 // report Jalview version
426 Cache.loadBuildProperties(
427 !quiet() || bootstrapArgs.contains(Arg.VERSION));
429 // stop now if only after --version
430 if (bootstrapArgs.contains(Arg.VERSION))
432 Jalview.exit(null, ExitCode.OK);
436 ArgsParser aparser = new ArgsParser(args);
439 boolean headless = false;
441 boolean headlessArg = false;
445 String logLevel = null;
446 if (bootstrapArgs.contains(Arg.TRACE))
450 else if (bootstrapArgs.contains(Arg.DEBUG))
452 logLevel = bootstrapArgs.getBoolean(Arg.DEBUG) ? "DEBUG" : "INFO";
454 if (logLevel == null && !(bootstrapProperties == null))
456 logLevel = bootstrapProperties.getProperty(Cache.JALVIEWLOGLEVEL);
458 Console.initLogger(logLevel);
459 } catch (NoClassDefFoundError error)
461 error.printStackTrace();
462 String message = "\nEssential logging libraries not found."
463 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
464 Jalview.exit(message, ExitCode.OK);
467 // register SIGTERM listener
468 Runtime.getRuntime().addShutdownHook(new Thread()
473 Console.debug("Running shutdown hook");
474 QuitHandler.startForceQuit();
475 boolean closeExternal = Cache
476 .getDefault("DEFAULT_CLOSE_EXTERNAL_VIEWERS", false)
477 || Cache.getDefault("ALWAYS_CLOSE_EXTERNAL_VIEWERS", false);
478 StructureViewerBase.setQuitClose(closeExternal);
481 for (JInternalFrame frame : Desktop.desktop.getAllFrames())
483 if (frame instanceof StructureViewerBase)
485 ((StructureViewerBase) frame).closeViewer(closeExternal);
490 if (QuitHandler.gotQuitResponse() == QResponse.CANCEL_QUIT)
492 // Got to here by a SIGTERM signal.
493 // Note we will not actually cancel the quit from here -- it's too
494 // late -- but we can wait for saving files and close external viewers
496 // Close viewers/Leave viewers open
497 Console.debug("Checking for saving files");
498 QuitHandler.getQuitResponse(false);
502 Console.debug("Nothing more to do");
504 Console.debug("Exiting, bye!");
505 // shutdownHook cannot be cancelled, JVM will now halt
509 String usrPropsFile = bootstrapArgs.contains(Arg.PROPS)
510 ? bootstrapArgs.getValue(Arg.PROPS)
511 : aparser.getValue("props");
512 // if usrPropsFile == null, loadProperties will use the Channel
514 Cache.loadProperties(usrPropsFile);
515 if (usrPropsFile != null)
518 "CMD [-props " + usrPropsFile + "] executed successfully!");
519 testoutput(bootstrapArgs, Arg.PROPS,
520 "test/jalview/bin/testProps.jvprops", usrPropsFile);
523 // --argfile=... -- OVERRIDES ALL NON-BOOTSTRAP ARGS
524 if (bootstrapArgs.contains(Arg.ARGFILE))
526 argparser = ArgParser.parseArgFiles(
527 bootstrapArgs.getValueList(Arg.ARGFILE),
528 bootstrapArgs.getBoolean(Arg.INITSUBSTITUTIONS),
533 argparser = new ArgParser(args,
534 bootstrapArgs.getBoolean(Arg.INITSUBSTITUTIONS),
538 if (!Platform.isJS())
545 if (bootstrapArgs.contains(Arg.HELP))
547 List<Map.Entry<Type, String>> helpArgs = bootstrapArgs
549 Console.outPrintln(Arg.usage(helpArgs.stream().map(e -> e.getKey())
550 .collect(Collectors.toList())));
551 Jalview.exit(null, ExitCode.OK);
553 if (aparser.contains("help") || aparser.contains("h"))
556 * Now using new usage statement.
559 Console.outPrintln(Arg.usage());
560 Jalview.exit(null, ExitCode.OK);
564 headlessArg = bootstrapArgs.isHeadless();
567 System.setProperty("java.awt.headless", "true");
570 if (aparser.contains("nodisplay") || aparser.contains("nogui")
571 || aparser.contains("headless"))
573 System.setProperty("java.awt.headless", "true");
578 // allow https handshakes to download intermediate certs if necessary
579 System.setProperty("com.sun.security.enableAIAcaIssuers", "true");
581 String jabawsUrl = bootstrapArgs.getValue(Arg.JABAWS);
582 if (jabawsUrl == null)
583 jabawsUrl = aparser.getValue("jabaws");
584 if (jabawsUrl != null)
588 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
590 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
591 testoutput(bootstrapArgs, Arg.JABAWS,
592 "http://www.compbio.dundee.ac.uk/jabaws", jabawsUrl);
593 } catch (MalformedURLException e)
595 jalview.bin.Console.errPrintln(
596 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
601 List<String> setprops = new ArrayList<>();
602 if (bootstrapArgs.contains(Arg.SETPROP))
604 setprops = bootstrapArgs.getValueList(Arg.SETPROP);
608 String sp = aparser.getValue("setprop");
612 sp = aparser.getValue("setprop");
615 for (String setprop : setprops)
617 int p = setprop.indexOf('=');
621 .println("Ignoring invalid setprop argument : " + setprop);
626 .errPrintln("Executing setprop argument: " + setprop);
629 Cache.setProperty(setprop.substring(0, p),
630 setprop.substring(p + 1));
632 // DISABLED FOR SECURITY REASONS
633 // TODO: add a property to allow properties to be overriden by cli args
634 // Cache.setProperty(setprop.substring(0,p), setprop.substring(p+1));
637 if (System.getProperty("java.awt.headless") != null
638 && System.getProperty("java.awt.headless").equals("true"))
642 System.setProperty("http.agent", HttpUtils.getUserAgent());
646 Console.initLogger();
647 } catch (NoClassDefFoundError error)
649 error.printStackTrace();
650 String message = "\nEssential logging libraries not found."
651 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview";
652 Jalview.exit(message, ExitCode.NO_LOGGING);
656 if (!(headless || headlessArg))
660 * configure 'full' SO model if preferences say to, else use the default (full SO)
661 * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
663 boolean soDefault = !Platform.isJS();
664 if (Cache.getDefault("USE_FULL_SO", soDefault))
666 SequenceOntologyFactory.setInstance(new SequenceOntology());
669 if (!(headless || headlessArg))
671 Desktop.nosplash = "false".equals(bootstrapArgs.getValue(Arg.SPLASH))
672 || aparser.contains("nosplash")
673 || Cache.getDefault("SPLASH", "true").equals("false");
674 desktop = new Desktop();
675 desktop.setInBatchMode(true); // indicate we are starting up
681 JalviewTaskbar.setTaskbar(this);
682 } catch (Exception e)
684 Console.info("Cannot set Taskbar");
685 Console.error(e.getMessage());
686 // e.printStackTrace();
687 } catch (Throwable t)
689 Console.info("Cannot set Taskbar");
690 Console.error(t.getMessage());
691 // t.printStackTrace();
694 // set Proxy settings before all the internet calls
695 Cache.setProxyPropertiesFromPreferences();
697 desktop.setVisible(true);
699 if (!Platform.isJS())
708 * Check to see that the JVM version being run is suitable for the Java
709 * version this Jalview was compiled for. Popup a warning if not.
711 if (!LaunchUtils.checkJavaVersion())
713 Console.warn("The Java version being used (Java "
714 + LaunchUtils.getJavaVersion()
715 + ") may lead to problems. This installation of Jalview should be used with Java "
716 + LaunchUtils.getJavaCompileVersion() + ".");
719 .getBooleanUserPreference("IGNORE_JVM_WARNING_POPUP"))
722 MessageManager.getString("label.continue") };
723 JOptionPane.showOptionDialog(null,
724 MessageManager.formatMessage(
725 "warning.wrong_jvm_version_message",
726 LaunchUtils.getJavaVersion(),
727 LaunchUtils.getJavaCompileVersion()),
729 .getString("warning.wrong_jvm_version_title"),
730 JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
731 null, options, options[0]);
735 boolean webservicediscovery = bootstrapArgs
736 .getBoolean(Arg.WEBSERVICEDISCOVERY);
737 if (aparser.contains("nowebservicediscovery"))
738 webservicediscovery = false;
739 if (webservicediscovery)
741 desktop.startServiceDiscovery();
745 testoutput(argparser, Arg.WEBSERVICEDISCOVERY);
748 boolean usagestats = !bootstrapArgs.getBoolean(Arg.NOUSAGESTATS);
749 if (aparser.contains("nousagestats"))
753 startUsageStats(desktop);
754 testoutput(argparser, Arg.NOUSAGESTATS);
758 Console.outPrintln("CMD [-nousagestats] executed successfully!");
759 testoutput(argparser, Arg.NOUSAGESTATS);
762 boolean questionnaire = bootstrapArgs.getBoolean(Arg.QUESTIONNAIRE);
763 if (aparser.contains("noquestionnaire"))
764 questionnaire = false;
767 String url = aparser.getValue("questionnaire");
770 // Start the desktop questionnaire prompter with the specified
772 Console.debug("Starting questionnaire url at " + url);
773 desktop.checkForQuestionnaire(url);
774 Console.outPrintln("CMD questionnaire[-" + url
775 + "] executed successfully!");
779 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
781 // Start the desktop questionnaire prompter with the specified
784 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
786 String defurl = "https://www.jalview.org/cgi-bin/questionnaire.pl";
788 "Starting questionnaire with default url: " + defurl);
789 desktop.checkForQuestionnaire(defurl);
796 "CMD [-noquestionnaire] executed successfully!");
797 testoutput(argparser, Arg.QUESTIONNAIRE);
800 if ((!aparser.contains("nonews")
801 && Cache.getProperty("NONEWS") == null
802 && !"false".equals(bootstrapArgs.getValue(Arg.NEWS)))
803 || "true".equals(bootstrapArgs.getValue(Arg.NEWS)))
805 desktop.checkForNews();
808 if (!aparser.contains("nohtmltemplates")
809 && Cache.getProperty("NOHTMLTEMPLATES") == null)
811 BioJsHTMLOutput.updateBioJS();
818 if (getArgParser().isMixedStyle())
820 String warning = MessageManager.formatMessage(
821 "warning.using_mixed_command_line_arguments",
822 getArgParser().getMixedExamples());
823 Console.warn(warning);
825 "Exiting due to mixed old and new command line arguments",
826 ExitCode.INVALID_ARGUMENT);
828 if (getArgParser().isOldStyle())
830 String warning = MessageManager
831 .getString("warning.using_old_command_line_arguments")
833 + "https://www.jalview.org/help/html/features/commandline.html";
834 Console.warn(warning);
839 // Run Commands from cli
840 cmds = new Commands(argparser, headlessArg);
842 boolean commandsSuccess = cmds.argsWereParsed();
848 if (argparser.getBoolean(Arg.NOQUIT))
851 "Completed " + Arg.HEADLESS.getName() + " commands, but "
852 + Arg.NOQUIT + " is set so not quitting!");
856 Jalview.exit("Successfully completed commands in headless mode",
860 Console.info("Successfully completed commands");
866 Jalview.exit("Error when running Commands in headless mode",
867 ExitCode.ERROR_RUNNING_COMMANDS);
869 Console.warn("Error when running commands");
872 // Check if JVM and compile version might cause problems and log if it
874 if (headless && !Platform.isJS() && !LaunchUtils.checkJavaVersion())
876 Console.warn("The Java version being used (Java "
877 + LaunchUtils.getJavaVersion()
878 + ") may lead to problems. This installation of Jalview should be used with Java "
879 + LaunchUtils.getJavaCompileVersion() + ".");
882 String file = null, data = null;
884 FileFormatI format = null;
886 DataSourceType protocol = null;
888 FileLoader fileLoader = new FileLoader(!headless);
890 String groovyscript = null; // script to execute after all loading is
891 // completed one way or another
892 // extract groovy argument and execute if necessary
893 groovyscript = aparser.getValue("groovy", true);
894 file = aparser.getValue("open", true);
896 if (file == null && desktop == null && !commandsSuccess)
898 Jalview.exit("No files to open!", ExitCode.NO_FILES);
902 // Finally, deal with the remaining input data.
907 desktop.setProgressBar(
909 .getString("status.processing_commandline_args"),
910 progress = System.currentTimeMillis());
912 Console.outPrintln("CMD [-open " + file + "] executed successfully!");
914 if (!Platform.isJS())
916 * ignore in JavaScript -- can't just file existence - could load it?
921 if (!HttpUtils.startsWithHttpOrHttps(file))
923 if (!(new File(file)).exists())
928 "Can't find file '" + file + "' in headless mode",
929 ExitCode.FILE_NOT_FOUND);
931 Console.warn("Can't find file'" + file + "'");
936 protocol = AppletFormatAdapter.checkProtocol(file);
940 format = new IdentifyFile().identify(file, protocol);
941 } catch (FileFormatException e1)
946 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
950 Console.outPrintln("error");
954 setCurrentAlignFrame(af);
955 data = aparser.getValue("colour", true);
958 data.replaceAll("%20", " ");
960 ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
961 af.getViewport(), af.getViewport().getAlignment(), data);
966 "CMD [-colour " + data + "] executed successfully!");
971 // Must maintain ability to use the groups flag
972 data = aparser.getValue("groups", true);
975 af.parseFeaturesFile(data,
976 AppletFormatAdapter.checkProtocol(data));
977 // Console.outPrintln("Added " + data);
979 "CMD groups[-" + data + "] executed successfully!");
981 data = aparser.getValue("features", true);
984 af.parseFeaturesFile(data,
985 AppletFormatAdapter.checkProtocol(data));
986 // Console.outPrintln("Added " + data);
988 "CMD [-features " + data + "] executed successfully!");
991 data = aparser.getValue("annotations", true);
994 af.loadJalviewDataFile(data, null, null, null);
995 // Console.outPrintln("Added " + data);
997 "CMD [-annotations " + data + "] executed successfully!");
999 // set or clear the sortbytree flag.
1000 if (aparser.contains("sortbytree"))
1002 af.getViewport().setSortByTree(true);
1003 if (af.getViewport().getSortByTree())
1005 Console.outPrintln("CMD [-sortbytree] executed successfully!");
1008 if (aparser.contains("no-annotation"))
1010 af.getViewport().setShowAnnotation(false);
1011 if (!af.getViewport().isShowAnnotation())
1013 Console.outPrintln("CMD no-annotation executed successfully!");
1016 if (aparser.contains("nosortbytree"))
1018 af.getViewport().setSortByTree(false);
1019 if (!af.getViewport().getSortByTree())
1022 "CMD [-nosortbytree] executed successfully!");
1025 data = aparser.getValue("tree", true);
1031 "CMD [-tree " + data + "] executed successfully!");
1032 NewickFile nf = new NewickFile(data,
1033 AppletFormatAdapter.checkProtocol(data));
1035 .setCurrentTree(af.showNewickTree(nf, data).getTree());
1036 } catch (IOException ex)
1038 jalview.bin.Console.errPrintln("Couldn't add tree " + data);
1039 ex.printStackTrace(System.err);
1043 if (groovyscript != null)
1045 // Execute the groovy script after we've done all the rendering stuff
1046 // and before any images or figures are generated.
1047 Console.outPrintln("Executing script " + groovyscript);
1048 executeGroovyScript(groovyscript, af);
1049 Console.outPrintln("CMD groovy[" + groovyscript
1050 + "] executed successfully!");
1051 groovyscript = null;
1053 String imageName = "unnamed.png";
1054 while (aparser.getSize() > 1)
1058 String outputFormat = aparser.nextValue();
1059 file = aparser.nextValue();
1061 if (outputFormat.equalsIgnoreCase("png"))
1063 Console.outPrintln("Creating PNG image: " + file);
1064 af.createPNG(new File(file));
1065 imageName = (new File(file)).getName();
1068 else if (outputFormat.equalsIgnoreCase("svg"))
1070 Console.outPrintln("Creating SVG image: " + file);
1071 File imageFile = new File(file);
1072 imageName = imageFile.getName();
1073 af.createSVG(imageFile);
1076 else if (outputFormat.equalsIgnoreCase("html"))
1078 File imageFile = new File(file);
1079 imageName = imageFile.getName();
1080 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1082 Console.outPrintln("Creating HTML image: " + file);
1083 htmlSVG.exportHTML(file);
1086 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
1090 jalview.bin.Console.errPrintln(
1091 "The output html file must not be null");
1096 BioJsHTMLOutput.refreshVersionInfo(
1097 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1098 } catch (URISyntaxException e)
1100 e.printStackTrace();
1102 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1104 "Creating BioJS MSA Viwer HTML file: " + file);
1105 bjs.exportHTML(file);
1108 else if (outputFormat.equalsIgnoreCase("imgMap"))
1110 Console.outPrintln("Creating image map: " + file);
1111 af.createImageMap(new File(file), imageName);
1114 else if (outputFormat.equalsIgnoreCase("eps"))
1116 File outputFile = new File(file);
1118 "Creating EPS file: " + outputFile.getAbsolutePath());
1119 af.createEPS(outputFile);
1123 FileFormatI outFormat = null;
1126 outFormat = FileFormats.getInstance().forName(outputFormat);
1127 } catch (Exception formatP)
1129 Console.outPrintln("Couldn't parse " + outFormat
1130 + " as a valid Jalview format string.");
1132 if (outFormat != null)
1134 if (!outFormat.isWritable())
1137 "This version of Jalview does not support alignment export as "
1142 af.saveAlignment(file, outFormat);
1143 if (af.isSaveAlignmentSuccessful())
1145 Console.outPrintln("Written alignment in "
1146 + outFormat.getName() + " format to " + file);
1150 Console.outPrintln("Error writing file " + file + " in "
1151 + outFormat.getName() + " format!!");
1155 } catch (ImageOutputException ioexc)
1158 "Unexpected error whilst exporting image to " + file);
1159 ioexc.printStackTrace();
1164 while (aparser.getSize() > 0)
1166 Console.outPrintln("Unknown arg: " + aparser.nextValue());
1171 AlignFrame startUpAlframe = null;
1172 // We'll only open the default file if the desktop is visible.
1174 // ////////////////////
1176 if (!Platform.isJS() && !headless && file == null
1177 && Cache.getDefault("SHOW_STARTUP_FILE", true)
1178 && !cmds.commandArgsProvided()
1179 && !bootstrapArgs.getBoolean(Arg.NOSTARTUPFILE))
1180 // don't open the startup file if command line args have been processed
1181 // (&& !Commands.commandArgsProvided())
1188 file = Cache.getDefault("STARTUP_FILE",
1189 Cache.getDefault("www.jalview.org", "https://www.jalview.org")
1190 + "/examples/exampleFile_2_7.jvp");
1191 if (file.equals("http://www.jalview.org/examples/exampleFile_2_3.jar")
1193 "http://www.jalview.org/examples/exampleFile_2_7.jar"))
1195 file.replace("http:", "https:");
1196 // hardwire upgrade of the startup file
1197 file.replace("_2_3", "_2_7");
1198 file.replace("2_7.jar", "2_7.jvp");
1199 // and remove the stale setting
1200 Cache.removeProperty("STARTUP_FILE");
1203 protocol = AppletFormatAdapter.checkProtocol(file);
1205 if (file.endsWith(".jar"))
1207 format = FileFormat.Jalview;
1213 format = new IdentifyFile().identify(file, protocol);
1214 } catch (FileFormatException e)
1220 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
1222 // don't ask to save when quitting if only the startup file has been
1224 Console.debug("Resetting up-to-date flag for startup file");
1225 startUpAlframe.getViewport().setSavedUpToDate(true);
1226 // extract groovy arguments before anything else.
1229 // Once all other stuff is done, execute any groovy scripts (in order)
1230 if (groovyscript != null)
1232 if (Cache.groovyJarsPresent())
1234 Console.outPrintln("Executing script " + groovyscript);
1235 executeGroovyScript(groovyscript, startUpAlframe);
1239 jalview.bin.Console.errPrintln(
1240 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
1244 // and finally, turn off batch mode indicator - if the desktop still exists
1245 if (desktop != null)
1249 desktop.setProgressBar(null, progress);
1251 desktop.setInBatchMode(false);
1257 private static void setLookAndFeel()
1259 if (!Platform.isJS())
1266 // property laf = "crossplatform", "system", "gtk", "metal", "nimbus",
1268 // If not set (or chosen laf fails), use the normal SystemLaF and if on
1270 // try Quaqua/Vaqua.
1271 String lafProp = System.getProperty("laf");
1272 String lafSetting = Cache.getDefault("PREFERRED_LAF", null);
1273 String laf = "none";
1274 if (lafProp != null)
1278 else if (lafSetting != null)
1282 boolean lafSet = false;
1285 case "crossplatform":
1286 lafSet = setCrossPlatformLookAndFeel();
1289 Console.error("Could not set requested laf=" + laf);
1293 lafSet = setSystemLookAndFeel();
1296 Console.error("Could not set requested laf=" + laf);
1300 lafSet = setGtkLookAndFeel();
1303 Console.error("Could not set requested laf=" + laf);
1307 lafSet = setMetalLookAndFeel();
1310 Console.error("Could not set requested laf=" + laf);
1314 lafSet = setNimbusLookAndFeel();
1317 Console.error("Could not set requested laf=" + laf);
1321 lafSet = setFlatLookAndFeel();
1324 Console.error("Could not set requested laf=" + laf);
1328 lafSet = setMacLookAndFeel();
1331 Console.error("Could not set requested laf=" + laf);
1337 Console.error("Requested laf=" + laf + " not implemented");
1341 // Flatlaf default for everyone!
1342 lafSet = setFlatLookAndFeel();
1345 setSystemLookAndFeel();
1347 if (Platform.isLinux())
1349 setLinuxLookAndFeel();
1351 if (Platform.isMac())
1353 setMacLookAndFeel();
1359 private static boolean setCrossPlatformLookAndFeel()
1361 boolean set = false;
1364 UIManager.setLookAndFeel(
1365 UIManager.getCrossPlatformLookAndFeelClassName());
1367 } catch (Exception ex)
1369 Console.error("Unexpected Look and Feel Exception");
1370 Console.error(ex.getMessage());
1371 Console.debug(Cache.getStackTraceString(ex));
1376 private static boolean setSystemLookAndFeel()
1378 boolean set = false;
1381 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
1383 } catch (Exception ex)
1385 Console.error("Unexpected Look and Feel Exception");
1386 Console.error(ex.getMessage());
1387 Console.debug(Cache.getStackTraceString(ex));
1392 private static boolean setSpecificLookAndFeel(String name,
1393 String className, boolean nameStartsWith)
1395 boolean set = false;
1398 for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels())
1400 if (info.getName() != null && nameStartsWith
1401 ? info.getName().toLowerCase(Locale.ROOT)
1402 .startsWith(name.toLowerCase(Locale.ROOT))
1403 : info.getName().toLowerCase(Locale.ROOT)
1404 .equals(name.toLowerCase(Locale.ROOT)))
1406 className = info.getClassName();
1410 UIManager.setLookAndFeel(className);
1412 } catch (Exception ex)
1414 Console.error("Unexpected Look and Feel Exception");
1415 Console.error(ex.getMessage());
1416 Console.debug(Cache.getStackTraceString(ex));
1421 private static boolean setGtkLookAndFeel()
1423 return setSpecificLookAndFeel("gtk",
1424 "com.sun.java.swing.plaf.gtk.GTKLookAndFeel", true);
1427 private static boolean setMetalLookAndFeel()
1429 return setSpecificLookAndFeel("metal",
1430 "javax.swing.plaf.metal.MetalLookAndFeel", false);
1433 private static boolean setNimbusLookAndFeel()
1435 return setSpecificLookAndFeel("nimbus",
1436 "javax.swing.plaf.nimbus.NimbusLookAndFeel", false);
1439 private static boolean setFlatLookAndFeel()
1441 boolean set = false;
1442 if (SystemInfo.isMacOS)
1446 UIManager.setLookAndFeel(
1447 "com.formdev.flatlaf.themes.FlatMacLightLaf");
1449 Console.debug("Using FlatMacLightLaf");
1450 } catch (ClassNotFoundException | InstantiationException
1451 | IllegalAccessException | UnsupportedLookAndFeelException e)
1453 Console.debug("Exception loading FlatLightLaf", e);
1455 System.setProperty("apple.laf.useScreenMenuBar", "true");
1456 System.setProperty("apple.awt.application.name",
1457 ChannelProperties.getProperty("app_name"));
1458 System.setProperty("apple.awt.application.appearance", "system");
1459 if (SystemInfo.isMacFullWindowContentSupported
1460 && Desktop.desktop != null)
1462 Console.debug("Setting transparent title bar");
1463 Desktop.desktop.getRootPane()
1464 .putClientProperty("apple.awt.fullWindowContent", true);
1465 Desktop.desktop.getRootPane()
1466 .putClientProperty("apple.awt.transparentTitleBar", true);
1467 Desktop.desktop.getRootPane()
1468 .putClientProperty("apple.awt.fullscreenable", true);
1470 SwingUtilities.invokeLater(() -> {
1471 FlatMacLightLaf.setup();
1473 Console.debug("Using FlatMacLightLaf");
1480 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1482 Console.debug("Using FlatLightLaf");
1483 } catch (ClassNotFoundException | InstantiationException
1484 | IllegalAccessException | UnsupportedLookAndFeelException e)
1486 Console.debug("Exception loading FlatLightLaf", e);
1488 // Windows specific properties here
1489 SwingUtilities.invokeLater(() -> {
1490 FlatLightLaf.setup();
1492 Console.debug("Using FlatLightLaf");
1495 else if (SystemInfo.isLinux)
1499 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1501 Console.debug("Using FlatLightLaf");
1502 } catch (ClassNotFoundException | InstantiationException
1503 | IllegalAccessException | UnsupportedLookAndFeelException e)
1505 Console.debug("Exception loading FlatLightLaf", e);
1507 // enable custom window decorations
1508 JFrame.setDefaultLookAndFeelDecorated(true);
1509 JDialog.setDefaultLookAndFeelDecorated(true);
1510 SwingUtilities.invokeLater(() -> {
1511 FlatLightLaf.setup();
1513 Console.debug("Using FlatLightLaf");
1521 UIManager.setLookAndFeel("com.formdev.flatlaf.FlatLightLaf");
1523 Console.debug("Using FlatLightLaf");
1524 } catch (ClassNotFoundException | InstantiationException
1525 | IllegalAccessException | UnsupportedLookAndFeelException e)
1527 Console.debug("Exception loading FlatLightLaf", e);
1533 UIManager.put("TabbedPane.tabType", "card");
1534 UIManager.put("TabbedPane.showTabSeparators", true);
1535 UIManager.put("TabbedPane.showContentSeparator", true);
1536 // UIManager.put("TabbedPane.tabSeparatorsFullHeight", true);
1537 UIManager.put("TabbedPane.tabsOverlapBorder", true);
1538 UIManager.put("TabbedPane.hasFullBorder", true);
1539 UIManager.put("TabbedPane.tabLayoutPolicy", "scroll");
1540 UIManager.put("TabbedPane.scrollButtonsPolicy", "asNeeded");
1541 UIManager.put("TabbedPane.smoothScrolling", true);
1542 UIManager.put("TabbedPane.tabWidthMode", "compact");
1543 UIManager.put("TabbedPane.selectedBackground", Color.white);
1544 UIManager.put("TabbedPane.background", new Color(236, 236, 236));
1545 UIManager.put("TabbedPane.hoverColor", Color.lightGray);
1548 Desktop.setLiveDragMode(Cache.getDefault("FLAT_LIVE_DRAG_MODE", true));
1552 private static boolean setMacLookAndFeel()
1554 boolean set = false;
1555 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
1556 ChannelProperties.getProperty("app_name"));
1557 System.setProperty("apple.laf.useScreenMenuBar", "true");
1559 * broken native LAFs on (ARM?) macbooks
1560 set = setQuaquaLookAndFeel();
1561 if ((!set) || !UIManager.getLookAndFeel().getClass().toString()
1562 .toLowerCase(Locale.ROOT).contains("quaqua"))
1564 set = setVaquaLookAndFeel();
1567 set = setFlatLookAndFeel();
1571 private static boolean setLinuxLookAndFeel()
1573 boolean set = false;
1574 set = setFlatLookAndFeel();
1576 set = setMetalLookAndFeel();
1577 // avoid GtkLookAndFeel -- not good results especially on HiDPI
1579 set = setNimbusLookAndFeel();
1584 private static void showUsage()
1586 jalview.bin.Console.outPrintln(
1587 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1588 + "-nodisplay\tRun Jalview without User Interface.\n"
1589 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1590 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1591 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1592 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1593 + "-features FILE\tUse the given file to mark features on the alignment.\n"
1594 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1595 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1596 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1597 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1598 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1599 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1600 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1601 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1602 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1603 + "-png FILE\tCreate PNG image FILE from alignment.\n"
1604 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1605 + "-html FILE\tCreate HTML file from alignment.\n"
1606 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1607 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1608 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1609 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1610 + "-noquestionnaire\tTurn off questionnaire check.\n"
1611 + "-nonews\tTurn off check for Jalview news.\n"
1612 + "-nousagestats\tTurn off analytics tracking for this session.\n"
1613 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1615 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1616 // after all other properties files have been read\n\t
1617 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1618 // passed in correctly)"
1619 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1620 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1621 + "-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"
1622 + "-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"
1623 + "-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"
1624 + "\n~Read documentation in Application or visit https://www.jalview.org for description of Features and Annotations file~\n\n");
1628 private static void startUsageStats(final Desktop desktop)
1631 * start a User Config prompt asking if we can log usage statistics.
1633 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1635 MessageManager.getString("prompt.analytics_title"),
1636 MessageManager.getString("prompt.analytics"), new Runnable()
1641 Console.debug("Initialising analytics for usage stats.");
1642 Cache.initAnalytics();
1643 Console.debug("Tracking enabled.");
1650 Console.debug("Not enabling analytics.");
1653 desktop.addDialogThread(prompter);
1657 * Locate the given string as a file and pass it to the groovy interpreter.
1659 * @param groovyscript
1660 * the script to execute
1661 * @param jalviewContext
1662 * the Jalview Desktop object passed in to the groovy binding as the
1665 protected void executeGroovyScript(String groovyscript, AlignFrame af)
1668 * for scripts contained in files
1675 if (groovyscript.trim().equals("STDIN"))
1677 // read from stdin into a tempfile and execute it
1680 tfile = File.createTempFile("jalview", "groovy");
1681 PrintWriter outfile = new PrintWriter(
1682 new OutputStreamWriter(new FileOutputStream(tfile)));
1683 BufferedReader br = new BufferedReader(
1684 new InputStreamReader(System.in));
1686 while ((line = br.readLine()) != null)
1688 outfile.write(line + "\n");
1694 } catch (Exception ex)
1697 .errPrintln("Failed to read from STDIN into tempfile "
1698 + ((tfile == null) ? "(tempfile wasn't created)"
1699 : tfile.toString()));
1700 ex.printStackTrace();
1705 sfile = tfile.toURI().toURL();
1706 } catch (Exception x)
1708 jalview.bin.Console.errPrintln(
1709 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1711 x.printStackTrace();
1719 sfile = new URI(groovyscript).toURL();
1720 } catch (Exception x)
1722 tfile = new File(groovyscript);
1723 if (!tfile.exists())
1725 jalview.bin.Console.errPrintln(
1726 "File '" + groovyscript + "' does not exist.");
1729 if (!tfile.canRead())
1731 jalview.bin.Console.errPrintln(
1732 "File '" + groovyscript + "' cannot be read.");
1735 if (tfile.length() < 1)
1738 .errPrintln("File '" + groovyscript + "' is empty.");
1743 sfile = tfile.getAbsoluteFile().toURI().toURL();
1744 } catch (Exception ex)
1746 jalview.bin.Console.errPrintln("Failed to create a file URL for "
1747 + tfile.getAbsoluteFile());
1754 JalviewObjectI j = new JalviewObject(this);
1755 Map<String, java.lang.Object> vbinding = new HashMap<>();
1756 vbinding.put(JalviewObjectI.jalviewObjectName, j);
1757 vbinding.put(JalviewObjectI.currentAlFrameName,
1758 af != null ? af : getCurrentAlignFrame());
1759 Binding gbinding = new Binding(vbinding);
1760 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1761 gse.run(sfile.toString(), gbinding);
1762 if ("STDIN".equals(groovyscript))
1764 // delete temp file that we made -
1765 // only if it was successfully executed
1768 } catch (Exception e)
1771 .errPrintln("Exception Whilst trying to execute file " + sfile
1772 + " as a groovy script.");
1773 e.printStackTrace(System.err);
1777 public static boolean isHeadlessMode()
1779 String isheadless = System.getProperty("java.awt.headless");
1780 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1788 public AlignFrame[] getAlignFrames()
1790 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1791 : Desktop.getDesktopAlignFrames();
1795 * jalview.bin.Jalview.quit() will just run the non-GUI shutdownHook and exit
1800 // System.exit will run the shutdownHook first
1801 Jalview.exit("Quitting now. Bye!", ExitCode.OK);
1805 public AlignFrame getCurrentAlignFrame()
1807 return currentAlignFrame;
1810 public void setCurrentAlignFrame(AlignFrame af)
1812 this.currentAlignFrame = af;
1815 public Commands getCommands()
1820 public static void exit(String message, ExitCode ec)
1822 int exitcode = ec == ExitCode.OK ? 0 : ec.ordinal() + 1;
1823 if (Console.log == null)
1825 // Don't start the logger just to exit!
1826 if (message != null)
1830 Console.outPrintln(message);
1834 jalview.bin.Console.errPrintln(message);
1840 Console.debug("Using Jalview.exit");
1841 if (message != null)
1845 Console.info(message);
1849 Console.error(message);
1855 System.exit(exitcode);
1859 public enum ExitCode
1861 // only add new ones to the end of the list (to preserve ordinal values)
1862 OK, FILE_NOT_FOUND, FILE_NOT_READABLE, NO_FILES, INVALID_FORMAT,
1863 INVALID_ARGUMENT, INVALID_VALUE, MIXED_CLI_ARGUMENTS,
1864 ERROR_RUNNING_COMMANDS, NO_LOGGING, GROOVY_ERROR;
1867 /******************************
1869 * TEST OUTPUT METHODS
1871 * these operate only when Arg.TESTOUTPUT has been passed, and variously check
1872 * if an expected value / arg was set and report it to the test framework.
1874 ******************************/
1876 * report string values parsed/processed during tests When the Bootstrap
1877 * argument Arg.TESTOUTPUT is present - reports on debug if given s1 is not
1878 * null and not equals s2, warns if given argument is not set, and calls
1879 * testoutput(true,a,s1,s2) to report processing progress.
1882 * - ArgParser handling parsing
1884 * - Arg currently being processed
1889 protected static void testoutput(ArgParser ap, Arg a, String s1,
1892 BootstrapArgs bsa = ap.getBootstrapArgs();
1893 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1895 if (!((s1 == null && s2 == null) || (s1 != null && s1.equals(s2))))
1897 Console.debug("testoutput with unmatching values '" + s1 + "' and '"
1898 + s2 + "' for arg " + a.argString());
1901 boolean isset = a.hasOption(Opt.BOOTSTRAP) ? bsa.contains(a)
1905 Console.warn("Arg '" + a.getName() + "' not set at all");
1908 testoutput(true, a, s1, s2);
1912 * report values passed via bootstrap arguments
1914 * TODO: significant code duplication with testouput(Argparser...) - move it
1917 protected static void testoutput(BootstrapArgs bsa, Arg a, String s1,
1920 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1922 if (!((s1 == null && s2 == null) || (s1 != null && s1.equals(s2))))
1924 Console.debug("testoutput with unmatching values '" + s1 + "' and '"
1925 + s2 + "' for arg " + a.argString());
1928 if (!a.hasOption(Opt.BOOTSTRAP))
1930 Console.error("Non-bootstrap Arg '" + a.getName()
1931 + "' given to testoutput(BootstrapArgs bsa, Arg a, String s1, String s2) with only BootstrapArgs");
1933 if (!bsa.contains(a))
1935 Console.warn("Arg '" + a.getName() + "' not set at all");
1938 testoutput(true, a, s1, s2);
1942 * conditionally (on @param yes) report that expected value s1 was set during
1943 * CommandsTest tests
1945 private static void testoutput(boolean yes, Arg a, String s1, String s2)
1947 if (yes && ((s1 == null && s2 == null)
1948 || (s1 != null && s1.equals(s2))))
1950 Console.outPrintln("[TESTOUTPUT] arg " + a.argString() + "='" + s1
1956 * testoutput for boolean and unary values
1958 protected static void testoutput(ArgParser ap, Arg a)
1962 BootstrapArgs bsa = ap.getBootstrapArgs();
1965 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1967 boolean val = a.hasOption(Opt.BOOTSTRAP) ? bsa.getBoolean(a)
1969 boolean isset = a.hasOption(Opt.BOOTSTRAP) ? bsa.contains(a)
1973 Console.warn("Arg '" + a.getName() + "' not set at all");
1979 protected static void testoutput(BootstrapArgs bsa, Arg a)
1981 if (!bsa.getBoolean(Arg.TESTOUTPUT))
1983 if (!a.hasOption(Opt.BOOTSTRAP))
1985 Console.warn("Non-bootstrap Arg '" + a.getName()
1986 + "' given to testoutput(BootstrapArgs bsa, Arg a) with only BootstrapArgs");
1989 if (!bsa.contains(a))
1991 Console.warn("Arg '" + a.getName() + "' not set at all");
1994 testoutput(bsa.getBoolean(a), a);
1997 private static void testoutput(boolean yes, Arg a)
1999 String message = null;
2000 if (a.hasOption(Opt.BOOLEAN))
2002 message = (yes ? a.argString() : a.negateArgString()) + " was set";
2004 else if (a.hasOption(Opt.UNARY))
2006 message = a.argString() + (yes ? " was set" : " was not set");
2008 Console.outPrintln("[TESTOUTPUT] arg " + message);
2011 public ArgParser getArgParser()
2016 public BootstrapArgs getBootstrapArgs()
2018 return bootstrapArgs;
2021 public static boolean isBatchMode()
2023 return getInstance() != null && (getInstance().desktop == null
2024 || getInstance().desktop.isInBatchMode());
2028 * Warning about old or mixed command line arguments
2030 private void mixedCliWarning()
2032 Jalview j = Jalview.getInstance();
2033 boolean mixedStyle = j.getArgParser() != null
2034 && j.getArgParser().isMixedStyle();
2035 String title = MessageManager.getString("label.command_line_arguments");
2038 String warning = MessageManager.formatMessage(
2039 "warning.using_mixed_command_line_arguments",
2040 j.getArgParser().getMixedExamples());
2041 String quit = MessageManager.getString("action.quit");
2043 Desktop.instance.nonBlockingDialog(title, warning, null, quit,
2044 JvOptionPane.WARNING_MESSAGE, false, false, true, 30000);
2047 "Exiting due to mixed old and new command line arguments.",
2048 ExitCode.MIXED_CLI_ARGUMENTS);
2052 private void cliWarning()
2054 Jalview j = Jalview.getInstance();
2055 Commands c = j.getCommands();
2056 boolean oldStyle = j.getArgParser() != null
2057 && j.getArgParser().isOldStyle();
2058 String title = MessageManager.getString("label.command_line_arguments");
2061 String warning = MessageManager
2062 .getString("warning.using_old_command_line_arguments");
2063 String url = "<a href=\"https://www.jalview.org/help/html/features/commandline.html\">https://www.jalview.org/help/html/features/commandline.html</a>";
2064 if (Desktop.instance != null)
2066 String cont = MessageManager.getString("label.continue");
2068 Desktop.instance.nonBlockingDialog(title, warning, url, cont,
2069 JvOptionPane.WARNING_MESSAGE, false, true, true, 30000);
2072 if (j.getCommands() != null && j.getCommands().getErrors().size() > 0)
2074 if (Desktop.instance != null)
2076 String message = MessageManager
2077 .getString("warning.the_following_errors");
2078 String ok = MessageManager.getString("action.ok");
2080 List<String> errors = j.getCommands().getErrors();
2081 for (int i = 0; i < errors.size(); i++)
2083 shortest = Math.min(shortest, errors.get(i).length());
2085 Desktop.instance.nonBlockingDialog(
2086 Math.max(message.length(), Math.min(60, shortest)),
2087 Math.min(errors.size(), 20), title, message,
2088 j.getCommands().errorsToString(), ok,
2089 JvOptionPane.WARNING_MESSAGE, true, false, true, -1);