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