JAL-3830 Take account of --gui taking precedence over --headless
[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   private final static String headlessProperty = "java.awt.headless";
54
55   private static boolean checkJVMSymlink(String testBin)
56   {
57     File testBinFile = new File(testBin);
58     if (!testBinFile.exists())
59     {
60       return false;
61     }
62     File targetFile = null;
63     try
64     {
65       targetFile = testBinFile.getCanonicalFile();
66     } catch (IOException e)
67     {
68       return false;
69     }
70     if (targetFile != null && ("java".equals(targetFile.getName())
71             || "java.exe".equals(targetFile.getName())))
72     {
73       return true;
74     }
75     return false;
76   }
77
78   /**
79    * main method for jalview.bin.Launcher. This restarts the same JRE's JVM with
80    * the same arguments but with memory adjusted based on extracted -jvmmempc
81    * and -jvmmemmax application arguments. If on a Mac then extra dock:icon and
82    * dock:name arguments are also set.
83    * 
84    * @param args
85    */
86   public static void main(String[] args)
87   {
88     if (!LaunchUtils.checkJavaVersion())
89     {
90       System.err.println("WARNING - The Java version being used (Java "
91               + LaunchUtils.getJavaVersion()
92               + ") may lead to problems. This installation of Jalview should be used with Java "
93               + LaunchUtils.getJavaCompileVersion() + ".");
94     }
95     final String appName = ChannelProperties.getProperty("app_name");
96     final String javaBinDir = System.getProperty("java.home")
97             + File.separator + "bin" + File.separator;
98     String javaBin = null;
99     if (javaBin == null && checkJVMSymlink(javaBinDir + appName))
100     {
101       javaBin = javaBinDir + appName;
102     }
103     if (javaBin == null && checkJVMSymlink(javaBinDir + "Jalview"))
104     {
105       javaBin = javaBinDir + "Jalview";
106     }
107     if (javaBin == null)
108     {
109       javaBin = "java";
110     }
111
112     List<String> command = new ArrayList<>();
113     command.add(javaBin);
114
115     String memSetting = null;
116
117     boolean isAMac = System.getProperty("os.name").indexOf("Mac") > -1;
118
119     for (String jvmArg : ManagementFactory.getRuntimeMXBean()
120             .getInputArguments())
121     {
122       command.add(jvmArg);
123     }
124     command.add("-cp");
125     command.add(ManagementFactory.getRuntimeMXBean().getClassPath());
126
127     String jvmmempc = null;
128     String jvmmemmax = null;
129     boolean debug = false;
130     boolean wait = true;
131     boolean quiet = false;
132     boolean headless = false;
133     boolean gui = false;
134     // must set --debug before --launcher...
135     boolean launcherstop = false;
136     boolean launcherprint = false;
137     boolean launcherwait = false;
138     ArrayList<String> arguments = new ArrayList<>();
139     for (String arg : args)
140     {
141       if (arg.equals("--debug"))
142       {
143         debug = true;
144       }
145       if (arg.equals("--quiet"))
146       {
147         quiet = true;
148       }
149       if (arg.equals("--headless"))
150       {
151         headless = true;
152       }
153       if (arg.equals("--gui"))
154       {
155         gui = true;
156       }
157       if (debug && arg.equals("--launcherprint"))
158       {
159         launcherprint = true;
160       }
161       if (debug && arg.equals("--launcherstop"))
162       {
163         launcherstop = true;
164       }
165       if (debug && arg.equals("--launcherwait"))
166       {
167         launcherwait = true;
168       }
169       // this ends the launcher immediately
170       if (debug && arg.equals("--launchernowait"))
171       {
172         wait = false;
173       }
174       // Don't add the --launcher... args to Jalview launch
175       if (arg.startsWith("--launcher"))
176       {
177         continue;
178       }
179       // jvmmempc and jvmmemmax args used to set memory and are not passed on to
180       // startClass
181       if (arg.startsWith(
182               "-" + MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "="))
183       {
184         jvmmempc = arg.substring(
185                 MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.length()
186                         + 2);
187       }
188       else if (arg.startsWith(
189               "-" + MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME + "="))
190       {
191         jvmmemmax = arg.substring(
192                 MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME.length() + 2);
193       }
194       // --doubledash versions
195       else if (arg.startsWith("--"
196               + MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "="))
197       {
198         jvmmempc = arg.substring(
199                 MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.length()
200                         + 3);
201       }
202       else if (arg.startsWith(
203               "--" + MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME + "="))
204       {
205         jvmmemmax = arg.substring(
206                 MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME.length() + 3);
207       }
208       // retain arg
209       else
210       {
211         arguments.add(arg);
212       }
213     }
214     if (gui)
215     {
216       // --gui takes precedence over --headless
217       headless = false;
218     }
219
220     // use saved preferences if no cmdline args
221     boolean useCustomisedSettings = LaunchUtils
222             .getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS);
223     if (useCustomisedSettings)
224     {
225       if (jvmmempc == null)
226       {
227         jvmmempc = LaunchUtils
228                 .getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
229       }
230       if (jvmmemmax == null)
231       {
232         jvmmemmax = LaunchUtils
233                 .getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
234       }
235     }
236
237     // add these settings if not already specified
238     boolean memSet = false;
239     boolean dockIcon = false;
240     boolean dockName = false;
241     boolean headlessProp = false;
242     for (int i = 0; i < command.size(); i++)
243     {
244       String arg = command.get(i);
245       if (arg.startsWith("-Xmx"))
246       {
247         // only use -Xmx if jvmmemmax and jvmmempc have not been set
248         if (jvmmempc == null && jvmmemmax == null)
249         {
250           memSetting = arg;
251           memSet = true;
252         }
253       }
254       else if (arg.startsWith("-Xdock:icon"))
255       {
256         dockIcon = true;
257       }
258       else if (arg.startsWith("-Xdock:name"))
259       {
260         dockName = true;
261       }
262       else if (arg.startsWith("-D" + headlessProperty + "="))
263       {
264         headlessProp = true;
265       }
266     }
267
268     if (!memSet)
269     {
270       long maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
271
272       if (maxMemLong > 0)
273       {
274         memSetting = "-Xmx" + Long.toString(maxMemLong);
275         memSet = true;
276         command.add(memSetting);
277       }
278     }
279
280     if (isAMac)
281     {
282       if (!dockIcon)
283       {
284         String dockIconPath = System.getProperty("getdownappdir", ".")
285                 + File.separator + "resource/jalview_logo.png";
286         command.add("-Xdock:icon=" + dockIconPath);
287       }
288       if (!dockName)
289       {
290         // -Xdock:name=... doesn't actually work :(
291         // Leaving it in in case it gets fixed
292         command.add("-Xdock:name=" + appName);
293         // this launches WITHOUT an icon in the macOS dock. Could be useful for
294         // getdown?
295         // command.add("-Dapple.awt.UIElement=false");
296         // This also does not work for the dock
297         command.add("-Dcom.apple.mrj.application.apple.menu.about.name="
298                 + appName);
299       }
300     }
301     if (headless && !headlessProp)
302     {
303       System.setProperty(headlessProperty, "true");
304       command.add("-D" + headlessProperty + "=true");
305     }
306
307     String scalePropertyArg = HiDPISetting.getScalePropertyArg();
308     if (scalePropertyArg != null)
309     {
310       sysout(debug, quiet, "Running " + startClass + " with scale setting "
311               + scalePropertyArg);
312       command.add(scalePropertyArg);
313     }
314
315     command.add(startClass);
316     command.addAll(arguments);
317
318     final ProcessBuilder builder = new ProcessBuilder(command);
319
320     if ((Boolean.parseBoolean(System.getProperty("launcherprint", "false"))
321             || launcherprint))
322     {
323       sysout(debug, quiet,
324               "LAUNCHER COMMAND: " + String.join(" ", builder.command()));
325     }
326     sysout(debug, quiet,
327             "Running " + startClass + " with "
328                     + (memSetting == null ? "no memory setting"
329                             : ("memory setting " + memSetting)));
330
331     if (Boolean.parseBoolean(System.getProperty("launcherstop", "false"))
332             || (debug && launcherstop))
333     {
334       sysout(debug, quiet,
335               "System property 'launcherstop' is set and not 'false'. Exiting.");
336       System.exit(0);
337     }
338     try
339     {
340       builder.inheritIO();
341       Process process = builder.start();
342       if (wait || launcherwait)
343       {
344         sysout(debug, quiet, "Launching application process");
345         process.waitFor();
346       }
347       else
348       {
349         int waitInt = 0;
350         sysout(debug, quiet,
351                 "Wait time for application process is " + waitInt + "ms");
352         process.waitFor(waitInt, TimeUnit.MILLISECONDS);
353       }
354       sysout(debug, quiet, "Launcher process ending");
355     } catch (IOException e)
356     {
357       if (e.getMessage().toLowerCase(Locale.ROOT).contains("memory"))
358       {
359         System.err.println("Caught a memory exception: " + e.getMessage());
360         // Probably the "Cannot allocate memory" error, try without the memory
361         // setting
362         ArrayList<String> commandNoMem = new ArrayList<>();
363         for (int i = 0; i < command.size(); i++)
364         {
365           if (!command.get(i).startsWith("-Xmx"))
366           {
367             commandNoMem.add(command.get(i));
368           }
369         }
370         final ProcessBuilder builderNoMem = new ProcessBuilder(
371                 commandNoMem);
372         System.err.println("Command without memory setting: "
373                 + String.join(" ", builderNoMem.command()));
374         try
375         {
376           builderNoMem.inheritIO();
377           Process processNoMem = builderNoMem.start();
378           processNoMem.waitFor();
379         } catch (Exception ex)
380         {
381           ex.printStackTrace();
382         }
383       }
384       else
385       {
386         e.printStackTrace();
387       }
388     } catch (Exception e)
389     {
390       e.printStackTrace();
391     }
392   }
393
394   private static void sysout(boolean debug, boolean quiet, String message)
395   {
396     if (debug && !quiet)
397     {
398       System.out.println("LAUNCHERDEBUG - " + message);
399     }
400   }
401
402 }