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