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