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