JAL-4344 careful application of -Djava.awt.headless=true to avoid Jmol problem. Using...
[jalview.git] / src / jalview / bin / Launcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
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.
11  *  
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.
16  * 
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.
20  */
21 package jalview.bin;
22
23 import java.io.File;
24 import java.io.IOException;
25 import java.lang.management.ManagementFactory;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Locale;
29 import java.util.concurrent.TimeUnit;
30
31 import jalview.util.ChannelProperties;
32 import jalview.util.LaunchUtils;
33
34 /**
35  * A Launcher class for Jalview. This class is used to launch Jalview from the
36  * shadowJar when Getdown is not used or available. It attempts to take all the
37  * command line arguments to pass on to the jalview.bin.Jalview class, but to
38  * insert a -Xmx memory setting to a sensible default, using the -jvmmempc and
39  * -jvmmemmax application arguments if specified. If not specified then system
40  * properties will be looked for by jalview.bin.MemorySetting. If the user has
41  * provided the JVM with a -Xmx setting directly and not set -jvmmempc or
42  * -jvmmemmax then this setting will be used and system properties ignored. If
43  * -Xmx is set as well as -jvmmempc or -jvmmemmax as argument(s) then the -Xmx
44  * argument will NOT be passed on to the main application launch.
45  * 
46  * @author bsoares
47  *
48  */
49 public class Launcher
50 {
51   private final static String startClass = "jalview.bin.Jalview";
52
53   // not setting this yet due to problem with Jmol
54   private final static String headlessProperty = "java.awt.headless";
55
56   // used for headless macOS
57   private final static String macosHeadlessProperty = "apple.awt.UIElement";
58
59   // arguments that assume headless mode
60   private final static String[] assumeHeadlessArgs = { "headless", "output",
61       "image", "structureimage" };
62
63   /**
64    * main method for jalview.bin.Launcher. This restarts the same JRE's JVM with
65    * the same arguments but with memory adjusted based on extracted -jvmmempc
66    * and -jvmmemmax application arguments. If on a Mac then extra dock:icon and
67    * dock:name arguments are also set.
68    * 
69    * @param args
70    */
71   public static void main(String[] args)
72   {
73     if (!LaunchUtils.checkJavaVersion())
74     {
75       jalview.bin.Console
76               .errPrintln("WARNING - The Java version being used (Java "
77                       + LaunchUtils.getJavaVersion()
78                       + ") may lead to problems. This installation of Jalview should be used with Java "
79                       + LaunchUtils.getJavaCompileVersion() + ".");
80     }
81
82     String jvmmempc = null;
83     String jvmmemmax = null;
84     boolean debug = false;
85     boolean wait = true;
86     boolean quiet = false;
87     boolean headless = false;
88     boolean assumeheadless = false;
89     boolean gui = false;
90     boolean help = false;
91     boolean stdout = false;
92     // must set --debug before --launcher...
93     boolean launcherstop = false;
94     boolean launcherprint = false;
95     boolean launcherwait = false;
96     ArrayList<String> arguments = new ArrayList<>();
97     String previousArg = null;
98     // set debug first
99     for (String arg : args)
100     {
101       if (arg.equals("--debug"))
102       {
103         debug = true;
104       }
105     }
106     for (String arg : args)
107     {
108       if (arg.equals("--quiet"))
109       {
110         quiet = true;
111       }
112       else if (arg.equals("--gui"))
113       {
114         gui = true;
115       }
116       else if (arg.equals("--help"))
117       {
118         help = true;
119       }
120       else if (arg.equals("--version"))
121       {
122         help = true;
123       }
124
125       if (!assumeheadless)
126       {
127         for (String a : assumeHeadlessArgs)
128         {
129           if (arg.equals("--" + a) || arg.startsWith("--" + a + "="))
130           {
131             assumeheadless = true;
132           }
133         }
134       }
135
136       if (arg.equals("--output=-")
137               || (arg.equals("-") && "--output".equals(previousArg)))
138       {
139         stdout = true;
140       }
141
142       if (debug)
143       {
144         if (arg.equals("--launcherprint"))
145         {
146           launcherprint = true;
147         }
148         else if (arg.equals("--launcherstop"))
149         {
150           launcherstop = true;
151         }
152         else if (arg.equals("--launcherwait"))
153         {
154           launcherwait = true;
155         }
156         else
157         // this ends the launcher immediately
158         if (arg.equals("--launchernowait"))
159         {
160           wait = false;
161         }
162       }
163       previousArg = arg;
164       // Don't add the --launcher... args to Jalview launch
165       if (arg.startsWith("--launcher"))
166       {
167         continue;
168       }
169       // jvmmempc and jvmmemmax args used to set memory and are not passed on to
170       // startClass
171       if (arg.startsWith(
172               "-" + MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "="))
173       {
174         jvmmempc = arg.substring(
175                 MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.length()
176                         + 2);
177       }
178       else if (arg.startsWith(
179               "-" + MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME + "="))
180       {
181         jvmmemmax = arg.substring(
182                 MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME.length() + 2);
183       }
184       // --doubledash versions
185       else if (arg.startsWith("--"
186               + MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "="))
187       {
188         jvmmempc = arg.substring(
189                 MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.length()
190                         + 3);
191       }
192       else if (arg.startsWith(
193               "--" + MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME + "="))
194       {
195         jvmmemmax = arg.substring(
196                 MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME.length() + 3);
197       }
198       // retain arg
199       else
200       {
201         arguments.add(arg);
202       }
203     }
204     if (help)
205     {
206       // --help takes precedence over --gui
207       headless = true;
208     }
209     else if (gui)
210     {
211       // --gui takes precedence over --headless
212       headless = false;
213     }
214     else
215     {
216       // --output arguments assume headless mode
217       headless = assumeheadless;
218     }
219
220     final String appName = ChannelProperties.getProperty("app_name");
221
222     // if we're using jalview.bin.Launcher we always assume a console is in use
223     final String javaBin = LaunchUtils.findJavaBin(true);
224
225     List<String> command = new ArrayList<>();
226     command.add(javaBin);
227
228     String memSetting = null;
229
230     for (String jvmArg : ManagementFactory.getRuntimeMXBean()
231             .getInputArguments())
232     {
233       command.add(jvmArg);
234     }
235     command.add("-cp");
236     command.add(ManagementFactory.getRuntimeMXBean().getClassPath());
237
238     // use saved preferences if no cmdline args
239     boolean useCustomisedSettings = LaunchUtils
240             .getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS);
241     if (useCustomisedSettings)
242     {
243       if (jvmmempc == null)
244       {
245         jvmmempc = LaunchUtils
246                 .getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
247       }
248       if (jvmmemmax == null)
249       {
250         jvmmemmax = LaunchUtils
251                 .getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
252       }
253     }
254
255     // add these settings if not already specified
256     boolean memSet = false;
257     boolean dockIcon = false;
258     boolean dockName = false;
259     boolean headlessProp = false;
260     boolean macosHeadlessProp = false;
261     for (int i = 0; i < command.size(); i++)
262     {
263       String arg = command.get(i);
264       if (arg.startsWith("-Xmx"))
265       {
266         // only use -Xmx if jvmmemmax and jvmmempc have not been set
267         if (jvmmempc == null && jvmmemmax == null)
268         {
269           memSetting = arg;
270           memSet = true;
271         }
272       }
273       else if (arg.startsWith("-Xdock:icon"))
274       {
275         dockIcon = true;
276       }
277       else if (arg.startsWith("-Xdock:name"))
278       {
279         dockName = true;
280       }
281       else if (arg.startsWith("-D" + headlessProperty + "="))
282       {
283         headlessProp = true;
284       }
285       else if (arg.startsWith("-D" + macosHeadlessProperty + "="))
286       {
287         macosHeadlessProp = true;
288       }
289     }
290
291     if (!memSet)
292     {
293       long maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
294
295       if (maxMemLong > 0)
296       {
297         memSetting = "-Xmx" + Long.toString(maxMemLong);
298         memSet = true;
299         command.add(memSetting);
300       }
301     }
302
303     if (LaunchUtils.isMac)
304     {
305       if (!dockIcon)
306       {
307         String dockIconPath = System.getProperty("getdownappdir", ".")
308                 + File.separator + "resource/jalview_logo.png";
309         command.add("-Xdock:icon=" + dockIconPath);
310       }
311       if (!dockName)
312       {
313         // -Xdock:name=... doesn't actually work :(
314         // Leaving it in in case it gets fixed
315         command.add("-Xdock:name=" + appName);
316         // This also does not work for the dock
317         command.add("-Dcom.apple.mrj.application.apple.menu.about.name="
318                 + appName);
319       }
320     }
321     if (headless && !headlessProp)
322     {
323       System.setProperty(headlessProperty, "true");
324       /* not setting this in java invocation of running jalview due to problem with Jmol */
325       if (help)
326       {
327         command.add("-D" + headlessProperty + "=true");
328       }
329     }
330     if (headless && LaunchUtils.isMac && !macosHeadlessProp)
331     {
332       System.setProperty(macosHeadlessProperty, "true");
333       command.add("-D" + macosHeadlessProperty + "=true");
334     }
335
336     String scalePropertyArg = HiDPISetting.getScalePropertyArg();
337     if (scalePropertyArg != null)
338     {
339       syserr(debug, quiet, "Running " + startClass + " with scale setting "
340               + scalePropertyArg);
341       command.add(scalePropertyArg);
342     }
343
344     command.add(startClass);
345     command.addAll(arguments);
346
347     final ProcessBuilder builder = new ProcessBuilder(command);
348
349     if ((Boolean.parseBoolean(System.getProperty("launcherprint", "false"))
350             || launcherprint))
351     {
352       syserr(debug, quiet,
353               "LAUNCHER COMMAND: " + String.join(" ", builder.command()));
354     }
355     syserr(debug, quiet,
356             "Running " + startClass + " with "
357                     + (memSetting == null ? "no memory setting"
358                             : ("memory setting " + memSetting)));
359
360     if (Boolean.parseBoolean(System.getProperty("launcherstop", "false"))
361             || (debug && launcherstop))
362     {
363       syserr(debug, quiet,
364               "System property 'launcherstop' is set and not 'false'. Exiting.");
365       System.exit(0);
366     }
367     try
368     {
369       builder.inheritIO();
370       Process process = builder.start();
371       if (wait || launcherwait)
372       {
373         syserr(debug, quiet, "Launching application process");
374         process.waitFor();
375       }
376       else
377       {
378         int waitInt = 0;
379         syserr(debug, quiet,
380                 "Wait time for application process is " + waitInt + "ms");
381         process.waitFor(waitInt, TimeUnit.MILLISECONDS);
382       }
383       syserr(debug, quiet, "Launcher process ending");
384     } catch (IOException e)
385     {
386       if (e.getMessage().toLowerCase(Locale.ROOT).contains("memory"))
387       {
388         jalview.bin.Console
389                 .errPrintln("Caught a memory exception: " + e.getMessage());
390         // Probably the "Cannot allocate memory" error, try without the memory
391         // setting
392         ArrayList<String> commandNoMem = new ArrayList<>();
393         for (int i = 0; i < command.size(); i++)
394         {
395           if (!command.get(i).startsWith("-Xmx"))
396           {
397             commandNoMem.add(command.get(i));
398           }
399         }
400         final ProcessBuilder builderNoMem = new ProcessBuilder(
401                 commandNoMem);
402         jalview.bin.Console.errPrintln("Command without memory setting: "
403                 + String.join(" ", builderNoMem.command()));
404         try
405         {
406           builderNoMem.inheritIO();
407           Process processNoMem = builderNoMem.start();
408           processNoMem.waitFor();
409         } catch (Exception ex)
410         {
411           ex.printStackTrace();
412         }
413       }
414       else
415       {
416         e.printStackTrace();
417       }
418     } catch (Exception e)
419     {
420       e.printStackTrace();
421     }
422   }
423
424   private static void syserr(boolean debug, boolean quiet, String message)
425   {
426     if (debug && !quiet)
427     {
428       jalview.bin.Console.errPrintln("LAUNCHERDEBUG - " + message);
429     }
430   }
431
432 }