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