SafetyMutex and rocket optimization updates
[debian/openrocket] / src / net / sf / openrocket / startup / Startup.java
1 package net.sf.openrocket.startup;
2
3 import java.awt.GraphicsEnvironment;
4 import java.awt.event.ActionEvent;
5 import java.awt.event.ActionListener;
6 import java.io.File;
7 import java.io.PrintStream;
8 import java.util.List;
9 import java.util.concurrent.atomic.AtomicInteger;
10
11 import javax.swing.JOptionPane;
12 import javax.swing.SwingUtilities;
13 import javax.swing.Timer;
14 import javax.swing.ToolTipManager;
15
16 import net.sf.openrocket.communication.UpdateInfo;
17 import net.sf.openrocket.communication.UpdateInfoRetriever;
18 import net.sf.openrocket.database.Databases;
19 import net.sf.openrocket.database.ThrustCurveMotorSet;
20 import net.sf.openrocket.database.ThrustCurveMotorSetDatabase;
21 import net.sf.openrocket.file.iterator.DirectoryIterator;
22 import net.sf.openrocket.file.iterator.FileIterator;
23 import net.sf.openrocket.file.motor.MotorLoaderHelper;
24 import net.sf.openrocket.gui.dialogs.UpdateInfoDialog;
25 import net.sf.openrocket.gui.main.BasicFrame;
26 import net.sf.openrocket.gui.main.ExceptionHandler;
27 import net.sf.openrocket.gui.main.SimpleFileFilter;
28 import net.sf.openrocket.gui.main.Splash;
29 import net.sf.openrocket.logging.DelegatorLogger;
30 import net.sf.openrocket.logging.LogHelper;
31 import net.sf.openrocket.logging.LogLevel;
32 import net.sf.openrocket.logging.LogLevelBufferLogger;
33 import net.sf.openrocket.logging.PrintStreamLogger;
34 import net.sf.openrocket.motor.Motor;
35 import net.sf.openrocket.motor.ThrustCurveMotor;
36 import net.sf.openrocket.util.GUIUtil;
37 import net.sf.openrocket.util.Prefs;
38
39
40 /**
41  * A startup class that checks that a suitable JRE environment is being run.
42  * If the environment is too old the execution is canceled, and if OpenJDK is being
43  * used warns the user of problems and confirms whether to continue.
44  * 
45  * @author Sampo Niskanen <sampo.niskanen@iki.fi>
46  */
47 public class Startup {
48         
49         private static LogHelper log;
50         
51         private static final String LOG_STDERR_PROPERTY = "openrocket.log.stderr";
52         private static final String LOG_STDOUT_PROPERTY = "openrocket.log.stdout";
53         
54         private static final int LOG_BUFFER_LENGTH = 50;
55         
56         private static final String THRUSTCURVE_DIRECTORY = "datafiles/thrustcurves/";
57         
58
59         /** Block motor loading for this many milliseconds */
60         private static AtomicInteger blockLoading = new AtomicInteger(Integer.MAX_VALUE);
61         
62         
63         public static void main(final String[] args) throws Exception {
64                 
65                 // Check for "openrocket.debug" property before anything else
66                 checkDebugStatus();
67                 
68                 // Initialize logging first so we can use it
69                 initializeLogging();
70                 
71                 // Check that we have a head
72                 checkHead();
73                 
74                 // Check that we're running a good version of a JRE
75                 log.info("Checking JRE compatibility");
76                 VersionHelper.checkVersion();
77                 VersionHelper.checkOpenJDK();
78                 
79                 // Run the actual startup method in the EDT since it can use progress dialogs etc.
80                 log.info("Running main");
81                 SwingUtilities.invokeAndWait(new Runnable() {
82                         @Override
83                         public void run() {
84                                 runMain(args);
85                         }
86                 });
87                 
88                 log.info("Startup complete");
89                 
90                 // Block motor loading for 1.5 seconds to allow window painting
91                 blockLoading.set(1500);
92         }
93         
94         
95
96
97         private static void checkDebugStatus() {
98                 if (System.getProperty("openrocket.debug") != null) {
99                         System.setProperty("openrocket.log.stdout", "VBOSE");
100                         System.setProperty("openrocket.log.tracelevel", "VBOSE");
101                         System.setProperty("openrocket.debug.menu", "true");
102                         System.setProperty("openrocket.debug.motordigest", "true");
103                 }
104         }
105         
106         
107
108
109         private static void runMain(String[] args) {
110                 
111                 // Initialize the splash screen with version info
112                 log.info("Initializing the splash screen");
113                 Splash.init();
114                 
115                 // Setup the uncaught exception handler
116                 log.info("Registering exception handler");
117                 ExceptionHandler.registerExceptionHandler();
118                 
119                 // Start update info fetching
120                 final UpdateInfoRetriever updateInfo;
121                 if (Prefs.getCheckUpdates()) {
122                         log.info("Starting update check");
123                         updateInfo = new UpdateInfoRetriever();
124                         updateInfo.start();
125                 } else {
126                         log.info("Update check disabled");
127                         updateInfo = null;
128                 }
129                 
130                 // Set the best available look-and-feel
131                 log.info("Setting best LAF");
132                 GUIUtil.setBestLAF();
133                 
134                 // Set tooltip delay time.  Tooltips are used in MotorChooserDialog extensively.
135                 ToolTipManager.sharedInstance().setDismissDelay(30000);
136                 
137                 // Load defaults
138                 Prefs.loadDefaultUnits();
139                 
140                 // Load motors etc.
141                 log.info("Loading databases");
142                 loadMotor();
143                 Databases.fakeMethod();
144                 
145                 // Starting action (load files or open new document)
146                 log.info("Opening main application window");
147                 if (!handleCommandLine(args)) {
148                         BasicFrame.newAction();
149                 }
150                 
151                 // Check whether update info has been fetched or whether it needs more time
152                 log.info("Checking update status");
153                 checkUpdateStatus(updateInfo);
154         }
155         
156         
157
158         private static void loadMotor() {
159                 
160                 log.info("Starting motor loading from " + THRUSTCURVE_DIRECTORY + " in background thread.");
161                 ThrustCurveMotorSetDatabase db = new ThrustCurveMotorSetDatabase(true) {
162                         
163                         @Override
164                         protected void loadMotors() {
165                                 
166                                 // Block loading until timeout occurs or database is taken into use
167                                 log.info("Blocking motor loading while starting up");
168                                 while (!inUse && blockLoading.addAndGet(-100) > 0) {
169                                         try {
170                                                 Thread.sleep(100);
171                                         } catch (InterruptedException e) {
172                                         }
173                                 }
174                                 log.info("Blocking ended, inUse=" + inUse + " slowLoadingCount=" + blockLoading.get());
175                                 
176                                 // Start loading
177                                 log.info("Loading motors from " + THRUSTCURVE_DIRECTORY);
178                                 long t0 = System.currentTimeMillis();
179                                 int fileCount;
180                                 int thrustCurveCount;
181                                 
182                                 // Load the packaged thrust curves
183                                 List<Motor> list;
184                                 FileIterator iterator = DirectoryIterator.findDirectory(THRUSTCURVE_DIRECTORY,
185                                                                 new SimpleFileFilter("", false, "eng", "rse"));
186                                 if (iterator == null) {
187                                         throw new IllegalStateException("Thrust curve directory " + THRUSTCURVE_DIRECTORY +
188                                                         "not found, distribution built wrong");
189                                 }
190                                 list = MotorLoaderHelper.load(iterator);
191                                 for (Motor m : list) {
192                                         this.addMotor((ThrustCurveMotor) m);
193                                 }
194                                 fileCount = iterator.getFileCount();
195                                 
196                                 thrustCurveCount = list.size();
197                                 
198                                 // Load the user-defined thrust curves
199                                 for (File file : Prefs.getUserThrustCurveFiles()) {
200                                         // TODO: LOW: This counts a directory as one file
201                                         log.info("Loading motors from " + file);
202                                         list = MotorLoaderHelper.load(file);
203                                         for (Motor m : list) {
204                                                 this.addMotor((ThrustCurveMotor) m);
205                                         }
206                                         fileCount++;
207                                         thrustCurveCount += list.size();
208                                 }
209                                 
210                                 long t1 = System.currentTimeMillis();
211                                 
212                                 // Count statistics
213                                 int distinctMotorCount = 0;
214                                 int distinctThrustCurveCount = 0;
215                                 distinctMotorCount = motorSets.size();
216                                 for (ThrustCurveMotorSet set : motorSets) {
217                                         distinctThrustCurveCount += set.getMotorCount();
218                                 }
219                                 log.info("Motor loading done, took " + (t1 - t0) + " ms to load "
220                                                 + fileCount + " files/directories containing "
221                                                 + thrustCurveCount + " thrust curves which contained "
222                                                 + distinctMotorCount + " distinct motors with "
223                                                 + distinctThrustCurveCount + " distinct thrust curves.");
224                         }
225                         
226                 };
227                 db.startLoading();
228                 Application.setMotorSetDatabase(db);
229         }
230         
231         
232
233         private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) {
234                 if (updateInfo == null)
235                         return;
236                 
237                 int delay = 1000;
238                 if (!updateInfo.isRunning())
239                         delay = 100;
240                 
241                 final Timer timer = new Timer(delay, null);
242                 
243                 ActionListener listener = new ActionListener() {
244                         private int count = 5;
245                         
246                         @Override
247                         public void actionPerformed(ActionEvent e) {
248                                 if (!updateInfo.isRunning()) {
249                                         timer.stop();
250                                         
251                                         String current = Prefs.getVersion();
252                                         String last = Prefs.getString(Prefs.LAST_UPDATE, "");
253                                         
254                                         UpdateInfo info = updateInfo.getUpdateInfo();
255                                         if (info != null && info.getLatestVersion() != null &&
256                                                         !current.equals(info.getLatestVersion()) &&
257                                                         !last.equals(info.getLatestVersion())) {
258                                                 
259                                                 UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
260                                                 infoDialog.setVisible(true);
261                                                 if (infoDialog.isReminderSelected()) {
262                                                         Prefs.putString(Prefs.LAST_UPDATE, "");
263                                                 } else {
264                                                         Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
265                                                 }
266                                         }
267                                 }
268                                 count--;
269                                 if (count <= 0)
270                                         timer.stop();
271                         }
272                 };
273                 timer.addActionListener(listener);
274                 timer.start();
275         }
276         
277         
278         /**
279          * Handles arguments passed from the command line.  This may be used either
280          * when starting the first instance of OpenRocket or later when OpenRocket is
281          * executed again while running.
282          * 
283          * @param args  the command-line arguments.
284          * @return              whether a new frame was opened or similar user desired action was
285          *                              performed as a result.
286          */
287         public static boolean handleCommandLine(String[] args) {
288                 
289                 // Check command-line for files
290                 boolean opened = false;
291                 for (String file : args) {
292                         if (BasicFrame.open(new File(file), null)) {
293                                 opened = true;
294                         }
295                 }
296                 return opened;
297         }
298         
299         
300
301         /**
302          * Check that the JRE is not running headless.
303          */
304         private static void checkHead() {
305                 
306                 log.info("Checking for graphics head");
307                 
308                 if (GraphicsEnvironment.isHeadless()) {
309                         log.error("Application is headless.");
310                         System.err.println();
311                         System.err.println("OpenRocket cannot currently be run without the graphical " +
312                                         "user interface.");
313                         System.err.println();
314                         System.exit(1);
315                 }
316                 
317         }
318         
319         
320         ///////////  Logging  ///////////
321         
322         private static void initializeLogging() {
323                 DelegatorLogger delegator = new DelegatorLogger();
324                 
325                 // Log buffer
326                 LogLevelBufferLogger buffer = new LogLevelBufferLogger(LOG_BUFFER_LENGTH);
327                 delegator.addLogger(buffer);
328                 
329                 // Check whether to log to stdout/stderr
330                 PrintStreamLogger printer = new PrintStreamLogger();
331                 boolean logout = setLogOutput(printer, System.out, System.getProperty(LOG_STDOUT_PROPERTY), null);
332                 boolean logerr = setLogOutput(printer, System.err, System.getProperty(LOG_STDERR_PROPERTY), LogLevel.WARN);
333                 if (logout || logerr) {
334                         delegator.addLogger(printer);
335                 }
336                 
337                 // Set the loggers
338                 Application.setLogger(delegator);
339                 Application.setLogBuffer(buffer);
340                 
341                 // Initialize the log for this class
342                 log = Application.getLogger();
343                 log.info("Logging subsystem initialized for OpenRocket " + Prefs.getVersion());
344                 String str = "Console logging output:";
345                 for (LogLevel l : LogLevel.values()) {
346                         PrintStream ps = printer.getOutput(l);
347                         str += " " + l.name() + ":";
348                         if (ps == System.err) {
349                                 str += "stderr";
350                         } else if (ps == System.out) {
351                                 str += "stdout";
352                         } else {
353                                 str += "none";
354                         }
355                 }
356                 str += " (" + LOG_STDOUT_PROPERTY + "=" + System.getProperty(LOG_STDOUT_PROPERTY) +
357                                 " " + LOG_STDERR_PROPERTY + "=" + System.getProperty(LOG_STDERR_PROPERTY) + ")";
358                 log.info(str);
359         }
360         
361         private static boolean setLogOutput(PrintStreamLogger logger, PrintStream stream, String level, LogLevel defaultLevel) {
362                 LogLevel minLevel = LogLevel.fromString(level, defaultLevel);
363                 if (minLevel == null) {
364                         return false;
365                 }
366                 
367                 for (LogLevel l : LogLevel.values()) {
368                         if (l.atLeast(minLevel)) {
369                                 logger.setOutput(l, stream);
370                         }
371                 }
372                 return true;
373         }
374         
375         
376         ///////////  Helper methods  //////////
377         
378         /**
379          * Presents an error message to the user and exits the application.
380          * 
381          * @param message       an array of messages to present.
382          */
383         static void error(String[] message) {
384                 
385                 System.err.println();
386                 System.err.println("Error starting OpenRocket:");
387                 System.err.println();
388                 for (int i = 0; i < message.length; i++) {
389                         System.err.println(message[i]);
390                 }
391                 System.err.println();
392                 
393
394                 if (!GraphicsEnvironment.isHeadless()) {
395                         
396                         JOptionPane.showMessageDialog(null, message, "Error starting OpenRocket",
397                                         JOptionPane.ERROR_MESSAGE);
398                         
399                 }
400                 
401                 System.exit(1);
402         }
403         
404         
405         /**
406          * Presents the user with a message dialog and asks whether to continue.
407          * If the user does not select "Yes" the the application exits.
408          * 
409          * @param message       the message Strings to show.
410          */
411         static void confirm(String[] message) {
412                 
413                 if (!GraphicsEnvironment.isHeadless()) {
414                         
415                         if (JOptionPane.showConfirmDialog(null, message, "Error starting OpenRocket",
416                                         JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
417                                 System.exit(1);
418                         }
419                 }
420         }
421         
422 }