Merged l10n branch to trunk
[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                         setPropertyIfNotSet("openrocket.log.stdout", "VBOSE");
108                         setPropertyIfNotSet("openrocket.log.tracelevel", "VBOSE");
109                         setPropertyIfNotSet("openrocket.debug.menu", "true");
110                         setPropertyIfNotSet("openrocket.debug.mutexlocation", "true");
111                         setPropertyIfNotSet("openrocket.debug.motordigest", "true");
112                 }
113         }
114         
115         private static void setPropertyIfNotSet(String key, String value) {
116                 if (System.getProperty(key) == null) {
117                         System.setProperty(key, value);
118                 }
119         }
120         
121         
122         /**
123          * Initializes the localization system.
124          */
125         private static void initializeL10n() {
126                 String locale = System.getProperty("openrocket.locale");
127                 if (locale != null) {
128                         Locale l;
129                         String[] split = locale.split("[_-]", 3);
130                         if (split.length == 1) {
131                                 l = new Locale(split[0]);
132                         } else if (split.length == 2) {
133                                 l = new Locale(split[0], split[1]);
134                         } else {
135                                 l = new Locale(split[0], split[1], split[2]);
136                         }
137                         log.info("Setting custom locale " + l);
138                         Locale.setDefault(l);
139                 }
140                 
141                 Translator t;
142                 t = new ResourceBundleTranslator("l10n.messages");
143                 if (Locale.getDefault().getLanguage().equals("xx")) {
144                         t = new DebugTranslator(t);
145                 }
146                 
147                 log.info("Set up translation for locale " + Locale.getDefault() +
148                                 ", debug.currentFile=" + t.get("debug.currentFile"));
149                 
150                 Application.setBaseTranslator(t);
151         }
152         
153         
154
155         private static void runMain(String[] args) {
156                 
157                 // Initialize the splash screen with version info
158                 log.info("Initializing the splash screen");
159                 Splash.init();
160                 
161                 // Setup the uncaught exception handler
162                 log.info("Registering exception handler");
163                 ExceptionHandler.registerExceptionHandler();
164                 
165                 // Start update info fetching
166                 final UpdateInfoRetriever updateInfo;
167                 if (Prefs.getCheckUpdates()) {
168                         log.info("Starting update check");
169                         updateInfo = new UpdateInfoRetriever();
170                         updateInfo.start();
171                 } else {
172                         log.info("Update check disabled");
173                         updateInfo = null;
174                 }
175                 
176                 // Set the best available look-and-feel
177                 log.info("Setting best LAF");
178                 GUIUtil.setBestLAF();
179                 
180                 // Set tooltip delay time.  Tooltips are used in MotorChooserDialog extensively.
181                 ToolTipManager.sharedInstance().setDismissDelay(30000);
182                 
183                 // Load defaults
184                 Prefs.loadDefaultUnits();
185                 
186                 // Load motors etc.
187                 log.info("Loading databases");
188                 loadMotor();
189                 Databases.fakeMethod();
190                 
191                 // Starting action (load files or open new document)
192                 log.info("Opening main application window");
193                 if (!handleCommandLine(args)) {
194                         BasicFrame.newAction();
195                 }
196                 
197                 // Check whether update info has been fetched or whether it needs more time
198                 log.info("Checking update status");
199                 checkUpdateStatus(updateInfo);
200         }
201         
202         
203
204         private static void loadMotor() {
205                 
206                 log.info("Starting motor loading from " + THRUSTCURVE_DIRECTORY + " in background thread.");
207                 ThrustCurveMotorSetDatabase db = new ThrustCurveMotorSetDatabase(true) {
208                         
209                         @Override
210                         protected void loadMotors() {
211                                 
212                                 // Block loading until timeout occurs or database is taken into use
213                                 log.info("Blocking motor loading while starting up");
214                                 while (!inUse && blockLoading.addAndGet(-100) > 0) {
215                                         try {
216                                                 Thread.sleep(100);
217                                         } catch (InterruptedException e) {
218                                         }
219                                 }
220                                 log.info("Blocking ended, inUse=" + inUse + " slowLoadingCount=" + blockLoading.get());
221                                 
222                                 // Start loading
223                                 log.info("Loading motors from " + THRUSTCURVE_DIRECTORY);
224                                 long t0 = System.currentTimeMillis();
225                                 int fileCount;
226                                 int thrustCurveCount;
227                                 
228                                 // Load the packaged thrust curves
229                                 List<Motor> list;
230                                 FileIterator iterator = DirectoryIterator.findDirectory(THRUSTCURVE_DIRECTORY,
231                                                                 new SimpleFileFilter("", false, "eng", "rse"));
232                                 if (iterator == null) {
233                                         throw new IllegalStateException("Thrust curve directory " + THRUSTCURVE_DIRECTORY +
234                                                         "not found, distribution built wrong");
235                                 }
236                                 list = MotorLoaderHelper.load(iterator);
237                                 for (Motor m : list) {
238                                         this.addMotor((ThrustCurveMotor) m);
239                                 }
240                                 fileCount = iterator.getFileCount();
241                                 
242                                 thrustCurveCount = list.size();
243                                 
244                                 // Load the user-defined thrust curves
245                                 for (File file : Prefs.getUserThrustCurveFiles()) {
246                                         // TODO: LOW: This counts a directory as one file
247                                         log.info("Loading motors from " + file);
248                                         list = MotorLoaderHelper.load(file);
249                                         for (Motor m : list) {
250                                                 this.addMotor((ThrustCurveMotor) m);
251                                         }
252                                         fileCount++;
253                                         thrustCurveCount += list.size();
254                                 }
255                                 
256                                 long t1 = System.currentTimeMillis();
257                                 
258                                 // Count statistics
259                                 int distinctMotorCount = 0;
260                                 int distinctThrustCurveCount = 0;
261                                 distinctMotorCount = motorSets.size();
262                                 for (ThrustCurveMotorSet set : motorSets) {
263                                         distinctThrustCurveCount += set.getMotorCount();
264                                 }
265                                 log.info("Motor loading done, took " + (t1 - t0) + " ms to load "
266                                                 + fileCount + " files/directories containing "
267                                                 + thrustCurveCount + " thrust curves which contained "
268                                                 + distinctMotorCount + " distinct motors with "
269                                                 + distinctThrustCurveCount + " distinct thrust curves.");
270                         }
271                         
272                 };
273                 db.startLoading();
274                 Application.setMotorSetDatabase(db);
275         }
276         
277         
278
279         private static void checkUpdateStatus(final UpdateInfoRetriever updateInfo) {
280                 if (updateInfo == null)
281                         return;
282                 
283                 int delay = 1000;
284                 if (!updateInfo.isRunning())
285                         delay = 100;
286                 
287                 final Timer timer = new Timer(delay, null);
288                 
289                 ActionListener listener = new ActionListener() {
290                         private int count = 5;
291                         
292                         @Override
293                         public void actionPerformed(ActionEvent e) {
294                                 if (!updateInfo.isRunning()) {
295                                         timer.stop();
296                                         
297                                         String current = Prefs.getVersion();
298                                         String last = Prefs.getString(Prefs.LAST_UPDATE, "");
299                                         
300                                         UpdateInfo info = updateInfo.getUpdateInfo();
301                                         if (info != null && info.getLatestVersion() != null &&
302                                                         !current.equals(info.getLatestVersion()) &&
303                                                         !last.equals(info.getLatestVersion())) {
304                                                 
305                                                 UpdateInfoDialog infoDialog = new UpdateInfoDialog(info);
306                                                 infoDialog.setVisible(true);
307                                                 if (infoDialog.isReminderSelected()) {
308                                                         Prefs.putString(Prefs.LAST_UPDATE, "");
309                                                 } else {
310                                                         Prefs.putString(Prefs.LAST_UPDATE, info.getLatestVersion());
311                                                 }
312                                         }
313                                 }
314                                 count--;
315                                 if (count <= 0)
316                                         timer.stop();
317                         }
318                 };
319                 timer.addActionListener(listener);
320                 timer.start();
321         }
322         
323         
324         /**
325          * Handles arguments passed from the command line.  This may be used either
326          * when starting the first instance of OpenRocket or later when OpenRocket is
327          * executed again while running.
328          * 
329          * @param args  the command-line arguments.
330          * @return              whether a new frame was opened or similar user desired action was
331          *                              performed as a result.
332          */
333         public static boolean handleCommandLine(String[] args) {
334                 
335                 // Check command-line for files
336                 boolean opened = false;
337                 for (String file : args) {
338                         if (BasicFrame.open(new File(file), null)) {
339                                 opened = true;
340                         }
341                 }
342                 return opened;
343         }
344         
345         
346
347         /**
348          * Check that the JRE is not running headless.
349          */
350         private static void checkHead() {
351                 
352                 log.info("Checking for graphics head");
353                 
354                 if (GraphicsEnvironment.isHeadless()) {
355                         log.error("Application is headless.");
356                         System.err.println();
357                         System.err.println("OpenRocket cannot currently be run without the graphical " +
358                                         "user interface.");
359                         System.err.println();
360                         System.exit(1);
361                 }
362                 
363         }
364         
365         
366         ///////////  Logging  ///////////
367         
368         private static void initializeLogging() {
369                 DelegatorLogger delegator = new DelegatorLogger();
370                 
371                 // Log buffer
372                 LogLevelBufferLogger buffer = new LogLevelBufferLogger(LOG_BUFFER_LENGTH);
373                 delegator.addLogger(buffer);
374                 
375                 // Check whether to log to stdout/stderr
376                 PrintStreamLogger printer = new PrintStreamLogger();
377                 boolean logout = setLogOutput(printer, System.out, System.getProperty(LOG_STDOUT_PROPERTY), null);
378                 boolean logerr = setLogOutput(printer, System.err, System.getProperty(LOG_STDERR_PROPERTY), LogLevel.ERROR);
379                 if (logout || logerr) {
380                         delegator.addLogger(printer);
381                 }
382                 
383                 // Set the loggers
384                 Application.setLogger(delegator);
385                 Application.setLogBuffer(buffer);
386                 
387                 // Initialize the log for this class
388                 log = Application.getLogger();
389                 log.info("Logging subsystem initialized for OpenRocket " + Prefs.getVersion());
390                 String str = "Console logging output:";
391                 for (LogLevel l : LogLevel.values()) {
392                         PrintStream ps = printer.getOutput(l);
393                         str += " " + l.name() + ":";
394                         if (ps == System.err) {
395                                 str += "stderr";
396                         } else if (ps == System.out) {
397                                 str += "stdout";
398                         } else {
399                                 str += "none";
400                         }
401                 }
402                 str += " (" + LOG_STDOUT_PROPERTY + "=" + System.getProperty(LOG_STDOUT_PROPERTY) +
403                                 " " + LOG_STDERR_PROPERTY + "=" + System.getProperty(LOG_STDERR_PROPERTY) + ")";
404                 log.info(str);
405         }
406         
407         private static boolean setLogOutput(PrintStreamLogger logger, PrintStream stream, String level, LogLevel defaultLevel) {
408                 LogLevel minLevel = LogLevel.fromString(level, defaultLevel);
409                 if (minLevel == null) {
410                         return false;
411                 }
412                 
413                 for (LogLevel l : LogLevel.values()) {
414                         if (l.atLeast(minLevel)) {
415                                 logger.setOutput(l, stream);
416                         }
417                 }
418                 return true;
419         }
420         
421         
422         ///////////  Helper methods  //////////
423         
424         /**
425          * Presents an error message to the user and exits the application.
426          * 
427          * @param message       an array of messages to present.
428          */
429         static void error(String[] message) {
430                 
431                 System.err.println();
432                 System.err.println("Error starting OpenRocket:");
433                 System.err.println();
434                 for (int i = 0; i < message.length; i++) {
435                         System.err.println(message[i]);
436                 }
437                 System.err.println();
438                 
439
440                 if (!GraphicsEnvironment.isHeadless()) {
441                         
442                         JOptionPane.showMessageDialog(null, message, "Error starting OpenRocket",
443                                         JOptionPane.ERROR_MESSAGE);
444                         
445                 }
446                 
447                 System.exit(1);
448         }
449         
450         
451         /**
452          * Presents the user with a message dialog and asks whether to continue.
453          * If the user does not select "Yes" the the application exits.
454          * 
455          * @param message       the message Strings to show.
456          */
457         static void confirm(String[] message) {
458                 
459                 if (!GraphicsEnvironment.isHeadless()) {
460                         
461                         if (JOptionPane.showConfirmDialog(null, message, "Error starting OpenRocket",
462                                         JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) {
463                                 System.exit(1);
464                         }
465                 }
466         }
467         
468 }