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