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