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