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