Merge branch 'releases/Release_2_11_3_Branch'
[jalview.git] / getdown / src / getdown / launcher / src / main / java / com / threerings / getdown / launcher / GetdownApp.java
1 //
2 // Getdown - application installer, patcher and launcher
3 // Copyright (C) 2004-2018 Getdown authors
4 // https://github.com/threerings/getdown/blob/master/LICENSE
5
6 package com.threerings.getdown.launcher;
7
8 import java.awt.Color;
9 import java.awt.Container;
10 import java.awt.Image;
11 import java.awt.event.ActionEvent;
12 import java.awt.event.KeyEvent;
13 import java.awt.event.WindowAdapter;
14 import java.awt.event.WindowEvent;
15 import java.io.BufferedOutputStream;
16 import java.io.File;
17 import java.io.FileOutputStream;
18 import java.io.IOException;
19 import java.io.PrintStream;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import javax.swing.AbstractAction;
24 import javax.swing.JComponent;
25 import javax.swing.JFrame;
26 import javax.swing.KeyStroke;
27 import javax.swing.WindowConstants;
28
29 import com.samskivert.swing.util.SwingUtil;
30 import com.threerings.getdown.data.Application;
31 import com.threerings.getdown.data.Build;
32 import com.threerings.getdown.data.EnvConfig;
33 import com.threerings.getdown.data.SysProps;
34 import com.threerings.getdown.util.LaunchUtil;
35 import com.threerings.getdown.util.StringUtil;
36 import static com.threerings.getdown.Log.log;
37 import jalview.bin.StartupNotificationListener;
38
39 /**
40  * The main application entry point for Getdown.
41  */
42 public class GetdownApp
43 {
44   public static String startupFilesParameterString = "";
45   /**
46    * The main entry point of the Getdown launcher application.
47    */
48   public static void main (String[] argv) {
49     try {
50       start(argv);
51     } catch (Exception e) {
52       log.warning("main() failed.", e);
53     }
54   }
55
56   /**
57    * Runs Getdown as an application, using the arguments supplie as {@code argv}.
58    * @return the {@code Getdown} instance that is running. {@link Getdown#start} will have been
59    * called on it.
60    * @throws Exception if anything goes wrong starting Getdown.
61    */
62   public static Getdown start (String[] argv) throws Exception {
63     List<EnvConfig.Note> notes = new ArrayList<>();
64     EnvConfig envc = EnvConfig.create(argv, notes);
65     if (envc == null) {
66       if (!notes.isEmpty()) for (EnvConfig.Note n : notes) System.err.println(n.message);
67       else System.err.println("Usage: java -jar getdown.jar [app_dir] [app_id] [app args]");
68       System.exit(-1);
69     }
70
71     // pipe our output into a file in the application directory
72     if (!SysProps.noLogRedir()) {
73       File logFile = new File(envc.appDir, "launcher.log");
74       try {
75         PrintStream logOut = new PrintStream(
76                 new BufferedOutputStream(new FileOutputStream(logFile)), true);
77         System.setOut(logOut);
78         System.setErr(logOut);
79       } catch (IOException ioe) {
80         log.warning("Unable to redirect output to '" + logFile + "': " + ioe);
81       }
82     }
83
84     // report any notes from reading our env config, and abort if necessary
85     boolean abort = false;
86     for (EnvConfig.Note note : notes) {
87       switch (note.level) {
88       case INFO: log.info(note.message); break;
89       case WARN: log.warning(note.message); break;
90       case ERROR: log.error(note.message); abort = true; break;
91       }
92     }
93     if (abort) System.exit(-1);
94
95     log.info("Starting ...");
96     try
97     {
98       jalview.bin.StartupNotificationListener.setListener();
99     } catch (Exception e)
100     {
101       e.printStackTrace();
102     } catch (NoClassDefFoundError e)
103     {
104       log.warning("Starting without install4j classes");
105     } catch (Throwable t)
106     {
107       t.printStackTrace();
108     }
109     
110     // record a few things for posterity
111     log.info("------------------ VM Info ------------------");
112     log.info("-- OS Name: " + System.getProperty("os.name"));
113     log.info("-- OS Arch: " + System.getProperty("os.arch"));
114     log.info("-- OS Vers: " + System.getProperty("os.version"));
115     log.info("-- Java Vers: " + System.getProperty("java.version"));
116     log.info("-- Java Home: " + System.getProperty("java.home"));
117     log.info("-- Install4j Vers: " + Application.i4jVersion);
118     log.info("-- Install4j Template Vers: " + System.getProperty("installer_template_version"));
119     log.info("-- User Name: " + System.getProperty("user.name"));
120     log.info("-- User Home: " + System.getProperty("user.home"));
121     log.info("-- Cur dir: " + System.getProperty("user.dir"));
122     log.info("-- Launcher version: "+Build.version());
123     log.info("-- startupFilesParameterString: " + startupFilesParameterString);
124     log.info("---------------------------------------------");
125
126     Getdown app = new Getdown(envc) {
127       @Override
128       protected Container createContainer () {
129         // create our user interface, and display it
130         if (_frame == null) {
131           _frame = new JFrame("");
132           _frame.addWindowListener(new WindowAdapter() {
133             @Override
134             public void windowClosing (WindowEvent evt) {
135               handleWindowClose();
136             }
137           });
138           
139           // keep_on_top
140           try {
141                   readConfig(false);
142           } catch (Exception e) {
143                   log.warning("Error reading config for keep_on_top");
144           }
145           // move window to top, always on top
146           if (_ifc.keepOnTop) {
147                   log.info("Keep on top set to ", "keep_on_top", _ifc.keepOnTop);
148                           _frame.setAlwaysOnTop(true);
149           }
150
151           // handle close on ESC
152           String cancelId = "Cancel"; // $NON-NLS-1$
153           _frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
154                   KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelId);
155           _frame.getRootPane().getActionMap().put(cancelId, new AbstractAction() {
156             public void actionPerformed (ActionEvent e) {
157               handleWindowClose();
158             }
159           });
160           // this cannot be called in configureContainer as it is only allowed before the
161           // frame has been displayed for the first time
162           _frame.setUndecorated(_ifc.hideDecorations);
163           _frame.setResizable(false);
164         } else {
165           _frame.getContentPane().removeAll();
166         }
167         _frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
168         return _frame.getContentPane();
169       }
170
171       @Override
172       protected void configureContainer () {
173         if (_frame == null) return;
174
175         _frame.setTitle(_ifc.name);
176
177         try {
178           _frame.setBackground(new Color(_ifc.background, true));
179         } catch (Exception e) {
180           log.warning("Failed to set background", "bg", _ifc.background, e);
181         }
182
183         if (_ifc.iconImages != null && _ifc.iconImages.size() > 0) {
184           ArrayList<Image> icons = new ArrayList<>();
185           for (String path : _ifc.iconImages) {
186             Image img = loadImage(path);
187             if (img == null) {
188               log.warning("Error loading icon image", "path", path);
189             } else {
190               icons.add(img);
191             }
192           }
193           if (icons.isEmpty()) {
194             log.warning("Failed to load any icons", "iconImages", _ifc.iconImages);
195           } else {
196             _frame.setIconImages(icons);
197           }
198         }
199       }
200
201       @Override
202       protected void showContainer () {
203         if (_frame != null) {
204           _frame.pack();
205           SwingUtil.centerWindow(_frame);
206           _frame.setVisible(true);
207         }
208         _shownContainer = true;
209       }
210
211       @Override
212       protected void disposeContainer () {
213         if (_frame != null) {
214           _frame.dispose();
215           _frame = null;
216         }
217       }
218
219       @Override
220       protected void showDocument (String url) {
221         if (!StringUtil.couldBeValidUrl(url)) {
222           // command injection would be possible if we allowed e.g. spaces and double quotes
223           log.warning("Invalid document URL.", "url", url);
224           return;
225         }
226         String[] cmdarray;
227         if (LaunchUtil.isWindows()) {
228           String osName = System.getProperty("os.name", "");
229           if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) {
230             cmdarray = new String[] {
231                 "command.com", "/c", "start", "\"" + url + "\"" };
232           } else {
233             cmdarray = new String[] {
234                 "cmd.exe", "/c", "start", "\"\"", "\"" + url + "\"" };
235           }
236         } else if (LaunchUtil.isMacOS()) {
237           cmdarray = new String[] { "open", url };
238         } else { // Linux, Solaris, etc.
239           cmdarray = new String[] { "firefox", url };
240         }
241         try {
242           Runtime.getRuntime().exec(cmdarray);
243         } catch (Exception e) {
244           log.warning("Failed to open browser.", "cmdarray", cmdarray, e);
245         }
246       }
247
248       @Override
249       protected void exit (int exitCode) {
250         // if we're running the app in the same JVM, don't call System.exit, but do
251         // make double sure that the download window is closed.
252         if (invokeDirect()) {
253           disposeContainer();
254         } else {
255           System.exit(exitCode);
256         }
257       }
258
259       @Override
260       protected void fail (String message) {
261         super.fail(message);
262         // super.fail causes the UI to be created (if needed) on the next UI tick, so we
263         // want to wait until that happens before we attempt to redecorate the window
264         EQinvoke(new Runnable() {
265           @Override
266           public void run() {
267             // if the frame was set to be undecorated, make window decoration available
268             // to allow the user to close the window
269             if (_frame != null && _frame.isUndecorated()) {
270               _frame.dispose();
271               Color bg = _frame.getBackground();
272               if (bg != null && bg.getAlpha() < 255) {
273                 // decorated windows do not allow alpha backgrounds
274                 _frame.setBackground(
275                         new Color(bg.getRed(), bg.getGreen(), bg.getBlue()));
276               }
277               _frame.setUndecorated(false);
278               showContainer();
279             }
280           }
281         });
282       }
283
284       protected JFrame _frame;
285     };
286     
287     String startupFile = getStartupFilesParameterString();
288     if (!StringUtil.isBlank(startupFile)) {
289       Application.setStartupFilesFromParameterString(startupFile);
290     }
291  
292     app.start();
293     return app;
294   }
295   
296   public static void setStartupFilesParameterString(String parameters) {
297     startupFilesParameterString = parameters;
298   }
299   
300   public static String getStartupFilesParameterString() {
301     return startupFilesParameterString;
302   }
303 }