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