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
30 import jalview.util.ChannelProperties;
31 import jalview.util.LaunchUtils;
32
33 /**
34  * A Launcher class for Jalview. This class is used to launch Jalview from the
35  * shadowJar when Getdown is not used or available. It attempts to take all the
36  * command line arguments to pass on to the jalview.bin.Jalview class, but to
37  * insert a -Xmx memory setting to a sensible default, using the -jvmmempc and
38  * -jvmmemmax application arguments if specified. If not specified then system
39  * properties will be looked for by jalview.bin.MemorySetting. If the user has
40  * provided the JVM with a -Xmx setting directly and not set -jvmmempc or
41  * -jvmmemmax then this setting will be used and system properties ignored. If
42  * -Xmx is set as well as -jvmmempc or -jvmmemmax as argument(s) then the -Xmx
43  * argument will NOT be passed on to the main application launch.
44  * 
45  * @author bsoares
46  *
47  */
48 public class Launcher
49 {
50   private final static String startClass = "jalview.bin.Jalview";
51
52   private final static String dockIconPath = ChannelProperties
53           .getProperty("logo.512");
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     final String javaBin = System.getProperty("java.home") + File.separator
74             + "bin" + File.separator + "java";
75
76     List<String> command = new ArrayList<>();
77     command.add(javaBin);
78
79     String memSetting = null;
80
81     boolean isAMac = System.getProperty("os.name").indexOf("Mac") > -1;
82
83     for (String jvmArg : ManagementFactory.getRuntimeMXBean()
84             .getInputArguments())
85     {
86       command.add(jvmArg);
87     }
88     command.add("-cp");
89     command.add(ManagementFactory.getRuntimeMXBean().getClassPath());
90
91     String jvmmempc = null;
92     String jvmmemmax = null;
93     boolean debug = false;
94     boolean help = false;
95     boolean quiet = false;
96     boolean launcherstop = false;
97     boolean launcherprint = false;
98     ArrayList<String> arguments = new ArrayList<>();
99     for (String arg : args)
100     {
101       if (arg.equals("--debug"))
102       {
103         debug = true;
104       }
105       if (arg.equals("--quiet"))
106       {
107         quiet = true;
108       }
109       if (arg.equals("--help") || arg.startsWith("--help-"))
110       {
111         help = true;
112       }
113       if (arg.equals("--launcherprint"))
114       {
115         launcherprint = true;
116       }
117       if (arg.equals("--launcherstop"))
118       {
119         launcherstop = true;
120       }
121       // jvmmempc and jvmmemmax args used to set memory and are not passed on to
122       // startClass
123       if (arg.startsWith(
124               "-" + MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "="))
125       {
126         jvmmempc = arg.substring(
127                 MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.length()
128                         + 2);
129       }
130       else if (arg.startsWith(
131               "-" + MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME + "="))
132       {
133         jvmmemmax = arg.substring(
134                 MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME.length() + 2);
135       }
136       // --doubledash versions
137       else if (arg.startsWith("--"
138               + MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME + "="))
139       {
140         jvmmempc = arg.substring(
141                 MemorySetting.MAX_HEAPSIZE_PERCENT_PROPERTY_NAME.length()
142                         + 3);
143       }
144       else if (arg.startsWith(
145               "--" + MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME + "="))
146       {
147         jvmmemmax = arg.substring(
148                 MemorySetting.MAX_HEAPSIZE_PROPERTY_NAME.length() + 3);
149       }
150       // retain arg
151       else
152       {
153         arguments.add(arg);
154       }
155     }
156
157     // use saved preferences if no cmdline args
158     boolean useCustomisedSettings = LaunchUtils
159             .getBooleanUserPreference(MemorySetting.CUSTOMISED_SETTINGS);
160     if (useCustomisedSettings)
161     {
162       if (jvmmempc == null)
163       {
164         jvmmempc = LaunchUtils
165                 .getUserPreference(MemorySetting.MEMORY_JVMMEMPC);
166       }
167       if (jvmmemmax == null)
168       {
169         jvmmemmax = LaunchUtils
170                 .getUserPreference(MemorySetting.MEMORY_JVMMEMMAX);
171       }
172     }
173
174     // add these settings if not already specified
175     boolean memSet = false;
176     boolean dockIcon = false;
177     boolean dockName = false;
178     for (int i = 0; i < command.size(); i++)
179     {
180       String arg = command.get(i);
181       if (arg.startsWith("-Xmx"))
182       {
183         // only use -Xmx if jvmmemmax and jvmmempc have not been set
184         if (jvmmempc == null && jvmmemmax == null)
185         {
186           memSetting = arg;
187           memSet = true;
188         }
189       }
190       else if (arg.startsWith("-Xdock:icon"))
191       {
192         dockIcon = true;
193       }
194       else if (arg.startsWith("-Xdock:name"))
195       {
196         dockName = true;
197       }
198     }
199
200     if (!memSet)
201     {
202       long maxMemLong = MemorySetting.getMemorySetting(jvmmemmax, jvmmempc);
203
204       if (maxMemLong > 0)
205       {
206         memSetting = "-Xmx" + Long.toString(maxMemLong);
207         memSet = true;
208         command.add(memSetting);
209       }
210     }
211
212     if (isAMac)
213     {
214       if (!dockIcon)
215       {
216         command.add("-Xdock:icon=" + dockIconPath);
217       }
218       if (!dockName)
219       {
220         // -Xdock:name=... doesn't actually work :(
221         // Leaving it in in case it gets fixed
222         command.add(
223                 "-Xdock:name=" + ChannelProperties.getProperty("app_name"));
224         // this launches WITHOUT an icon in the macOS dock. Could be useful for
225         // getdown?
226         // command.add("-Dapple.awt.UIElement=false");
227         // This also does not work for the dock
228         command.add("-Dcom.apple.mrj.application.apple.menu.about.name="
229                 + ChannelProperties.getProperty("app_name"));
230       }
231     }
232
233     String scalePropertyArg = HiDPISetting.getScalePropertyArg();
234     if (scalePropertyArg != null)
235     {
236       if (debug && !quiet)
237       {
238         System.out.println("Running " + startClass + " with scale setting "
239                 + scalePropertyArg);
240       }
241       command.add(scalePropertyArg);
242     }
243
244     command.add(startClass);
245     command.addAll(arguments);
246
247     final ProcessBuilder builder = new ProcessBuilder(command);
248
249     if (!quiet && (Boolean
250             .parseBoolean(System.getProperty("launcherprint", "false"))
251             || (debug && launcherprint)))
252     {
253       System.out.println(
254               "LAUNCHER COMMAND: " + String.join(" ", builder.command()));
255     }
256     if (debug && !quiet)
257     {
258       System.out.println("Running " + startClass + " with "
259               + (memSetting == null ? "no memory setting"
260                       : ("memory setting " + memSetting)));
261     }
262
263     if (Boolean.parseBoolean(System.getProperty("launcherstop", "false"))
264             || (debug && launcherstop))
265     {
266       if (!quiet)
267       {
268         System.out.println(
269                 "System property 'launcherstop' is set and not 'false'. Exiting.");
270       }
271       System.exit(0);
272     }
273     try
274     {
275       builder.inheritIO();
276       Process process = builder.start();
277       process.waitFor();
278     } catch (IOException e)
279     {
280       if (e.getMessage().toLowerCase(Locale.ROOT).contains("memory"))
281       {
282         System.err.println("Caught a memory exception: " + e.getMessage());
283         // Probably the "Cannot allocate memory" error, try without the memory
284         // setting
285         ArrayList<String> commandNoMem = new ArrayList<>();
286         for (int i = 0; i < command.size(); i++)
287         {
288           if (!command.get(i).startsWith("-Xmx"))
289           {
290             commandNoMem.add(command.get(i));
291           }
292         }
293         final ProcessBuilder builderNoMem = new ProcessBuilder(
294                 commandNoMem);
295         System.err.println("Command without memory setting: "
296                 + String.join(" ", builderNoMem.command()));
297         try
298         {
299           builderNoMem.inheritIO();
300           Process processNoMem = builderNoMem.start();
301           processNoMem.waitFor();
302         } catch (Exception ex)
303         {
304           ex.printStackTrace();
305         }
306       }
307       else
308       {
309         e.printStackTrace();
310       }
311     } catch (Exception e)
312     {
313       e.printStackTrace();
314     }
315   }
316
317 }