c76c727728f457feb0df68ff499fead68807026a
[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     try {
111       StatusPanel.i4jVersion = com.install4j.api.launcher.Variables.getCompilerVariable("sys.install4jVersion");
112     } catch (IOException e) {
113       System.err.println("install4j version not available");
114     } catch (Throwable t) {
115       System.err.println("install4j not available");
116       t.printStackTrace();
117     }
118     // record a few things for posterity
119     log.info("------------------ VM Info ------------------");
120     log.info("-- OS Name: " + System.getProperty("os.name"));
121     log.info("-- OS Arch: " + System.getProperty("os.arch"));
122     log.info("-- OS Vers: " + System.getProperty("os.version"));
123     log.info("-- Java Vers: " + System.getProperty("java.version"));
124     log.info("-- Java Home: " + System.getProperty("java.home"));
125     log.info("-- Install4j Vers: " + StatusPanel.i4jVersion);
126     log.info("-- Install4j Template Vers: " + System.getProperty("installer_template_version"));
127     log.info("-- User Name: " + System.getProperty("user.name"));
128     log.info("-- User Home: " + System.getProperty("user.home"));
129     log.info("-- Cur dir: " + System.getProperty("user.dir"));
130     log.info("-- Launcher version: "+Build.version());
131     log.info("-- startupFilesParameterString: " + startupFilesParameterString);
132     log.info("---------------------------------------------");
133
134     Getdown app = new Getdown(envc) {
135       @Override
136       protected Container createContainer () {
137         // create our user interface, and display it
138         if (_frame == null) {
139           _frame = new JFrame("");
140           _frame.addWindowListener(new WindowAdapter() {
141             @Override
142             public void windowClosing (WindowEvent evt) {
143               handleWindowClose();
144             }
145           });
146           
147           // keep_on_top
148           try {
149                   readConfig(false);
150           } catch (Exception e) {
151                   log.warning("Error reading config for keep_on_top");
152           }
153           // move window to top, always on top
154           if (_ifc.keepOnTop) {
155                   log.info("Keep on top set to ", "keep_on_top", _ifc.keepOnTop);
156                           _frame.setAlwaysOnTop(true);
157           }
158
159           // handle close on ESC
160           String cancelId = "Cancel"; // $NON-NLS-1$
161           _frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
162                   KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), cancelId);
163           _frame.getRootPane().getActionMap().put(cancelId, new AbstractAction() {
164             public void actionPerformed (ActionEvent e) {
165               handleWindowClose();
166             }
167           });
168           // this cannot be called in configureContainer as it is only allowed before the
169           // frame has been displayed for the first time
170           _frame.setUndecorated(_ifc.hideDecorations);
171           _frame.setResizable(false);
172         } else {
173           _frame.getContentPane().removeAll();
174         }
175         _frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
176         return _frame.getContentPane();
177       }
178
179       @Override
180       protected void configureContainer () {
181         if (_frame == null) return;
182
183         _frame.setTitle(_ifc.name);
184
185         try {
186           _frame.setBackground(new Color(_ifc.background, true));
187         } catch (Exception e) {
188           log.warning("Failed to set background", "bg", _ifc.background, e);
189         }
190
191         if (_ifc.iconImages != null && _ifc.iconImages.size() > 0) {
192           ArrayList<Image> icons = new ArrayList<>();
193           for (String path : _ifc.iconImages) {
194             Image img = loadImage(path);
195             if (img == null) {
196               log.warning("Error loading icon image", "path", path);
197             } else {
198               icons.add(img);
199             }
200           }
201           if (icons.isEmpty()) {
202             log.warning("Failed to load any icons", "iconImages", _ifc.iconImages);
203           } else {
204             _frame.setIconImages(icons);
205           }
206         }
207       }
208
209       @Override
210       protected void showContainer () {
211         if (_frame != null) {
212           _frame.pack();
213           SwingUtil.centerWindow(_frame);
214           _frame.setVisible(true);
215         }
216         _shownContainer = true;
217       }
218
219       @Override
220       protected void disposeContainer () {
221         if (_frame != null) {
222           _frame.dispose();
223           _frame = null;
224         }
225       }
226
227       @Override
228       protected void showDocument (String url) {
229         if (!StringUtil.couldBeValidUrl(url)) {
230           // command injection would be possible if we allowed e.g. spaces and double quotes
231           log.warning("Invalid document URL.", "url", url);
232           return;
233         }
234         String[] cmdarray;
235         if (LaunchUtil.isWindows()) {
236           String osName = System.getProperty("os.name", "");
237           if (osName.indexOf("9") != -1 || osName.indexOf("Me") != -1) {
238             cmdarray = new String[] {
239                 "command.com", "/c", "start", "\"" + url + "\"" };
240           } else {
241             cmdarray = new String[] {
242                 "cmd.exe", "/c", "start", "\"\"", "\"" + url + "\"" };
243           }
244         } else if (LaunchUtil.isMacOS()) {
245           cmdarray = new String[] { "open", url };
246         } else { // Linux, Solaris, etc.
247           cmdarray = new String[] { "firefox", url };
248         }
249         try {
250           Runtime.getRuntime().exec(cmdarray);
251         } catch (Exception e) {
252           log.warning("Failed to open browser.", "cmdarray", cmdarray, e);
253         }
254       }
255
256       @Override
257       protected void exit (int exitCode) {
258         // if we're running the app in the same JVM, don't call System.exit, but do
259         // make double sure that the download window is closed.
260         if (invokeDirect()) {
261           disposeContainer();
262         } else {
263           System.exit(exitCode);
264         }
265       }
266
267       @Override
268       protected void fail (String message) {
269         super.fail(message);
270         // super.fail causes the UI to be created (if needed) on the next UI tick, so we
271         // want to wait until that happens before we attempt to redecorate the window
272         EQinvoke(new Runnable() {
273           @Override
274           public void run() {
275             // if the frame was set to be undecorated, make window decoration available
276             // to allow the user to close the window
277             if (_frame != null && _frame.isUndecorated()) {
278               _frame.dispose();
279               Color bg = _frame.getBackground();
280               if (bg != null && bg.getAlpha() < 255) {
281                 // decorated windows do not allow alpha backgrounds
282                 _frame.setBackground(
283                         new Color(bg.getRed(), bg.getGreen(), bg.getBlue()));
284               }
285               _frame.setUndecorated(false);
286               showContainer();
287             }
288           }
289         });
290       }
291
292       protected JFrame _frame;
293     };
294     
295     String startupFile = getStartupFilesParameterString();
296     if (!StringUtil.isBlank(startupFile)) {
297       Application.setStartupFilesFromParameterString(startupFile);
298     }
299  
300     app.start();
301     return app;
302   }
303   
304   public static void setStartupFilesParameterString(String parameters) {
305     startupFilesParameterString = parameters;
306   }
307   
308   public static String getStartupFilesParameterString() {
309     return startupFilesParameterString;
310   }
311 }