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