source: josm/trunk/src/org/openstreetmap/josm/Main.java@ 5340

Last change on this file since 5340 was 5279, checked in by bastiK, 12 years ago

use gnu getopt for command line processing

improvements:

  • long options can be separated by space from the argument (currently

only "=" works as seperator)

  • short options can be grouped (there aren't many short options at the moment, this is for later)
  • Property svn:eol-style set to native
File size: 33.1 KB
Line 
1// License: GPL. Copyright 2007 by Immanuel Scholz and others
2package org.openstreetmap.josm;
3import static org.openstreetmap.josm.tools.I18n.tr;
4
5import java.awt.BorderLayout;
6import java.awt.Component;
7import java.awt.GridBagConstraints;
8import java.awt.GridBagLayout;
9import java.awt.event.ComponentEvent;
10import java.awt.event.ComponentListener;
11import java.awt.event.KeyEvent;
12import java.awt.event.WindowAdapter;
13import java.awt.event.WindowEvent;
14import java.io.File;
15import java.lang.ref.WeakReference;
16import java.net.URI;
17import java.net.URISyntaxException;
18import java.util.ArrayList;
19import java.util.Collection;
20import java.util.Iterator;
21import java.util.List;
22import java.util.Map;
23import java.util.StringTokenizer;
24import java.util.concurrent.Callable;
25import java.util.concurrent.ExecutorService;
26import java.util.concurrent.Executors;
27import java.util.concurrent.Future;
28
29import javax.swing.Action;
30import javax.swing.InputMap;
31import javax.swing.JComponent;
32import javax.swing.JFrame;
33import javax.swing.JLabel;
34import javax.swing.JOptionPane;
35import javax.swing.JPanel;
36import javax.swing.JTextArea;
37import javax.swing.KeyStroke;
38import javax.swing.UIManager;
39
40import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
41import org.openstreetmap.josm.actions.JosmAction;
42import org.openstreetmap.josm.actions.OpenFileAction;
43import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
44import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
45import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
46import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
47import org.openstreetmap.josm.actions.mapmode.MapMode;
48import org.openstreetmap.josm.actions.search.SearchAction;
49import org.openstreetmap.josm.data.Bounds;
50import org.openstreetmap.josm.data.Preferences;
51import org.openstreetmap.josm.data.UndoRedoHandler;
52import org.openstreetmap.josm.data.coor.CoordinateFormat;
53import org.openstreetmap.josm.data.coor.LatLon;
54import org.openstreetmap.josm.data.osm.DataSet;
55import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
56import org.openstreetmap.josm.data.projection.Projection;
57import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
58import org.openstreetmap.josm.data.validation.OsmValidator;
59import org.openstreetmap.josm.gui.GettingStarted;
60import org.openstreetmap.josm.gui.MainApplication.Option;
61import org.openstreetmap.josm.gui.MainMenu;
62import org.openstreetmap.josm.gui.MapFrame;
63import org.openstreetmap.josm.gui.MapView;
64import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
65import org.openstreetmap.josm.gui.io.SaveLayersDialog;
66import org.openstreetmap.josm.gui.layer.Layer;
67import org.openstreetmap.josm.gui.layer.OsmDataLayer;
68import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
69import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
70import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
71import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
72import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
73import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
74import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
75import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
76import org.openstreetmap.josm.gui.util.RedirectInputMap;
77import org.openstreetmap.josm.io.OsmApi;
78import org.openstreetmap.josm.plugins.PluginHandler;
79import org.openstreetmap.josm.tools.CheckParameterUtil;
80import org.openstreetmap.josm.tools.I18n;
81import org.openstreetmap.josm.tools.ImageProvider;
82import org.openstreetmap.josm.tools.OpenBrowser;
83import org.openstreetmap.josm.tools.OsmUrlToBounds;
84import org.openstreetmap.josm.tools.PlatformHook;
85import org.openstreetmap.josm.tools.PlatformHookOsx;
86import org.openstreetmap.josm.tools.PlatformHookUnixoid;
87import org.openstreetmap.josm.tools.PlatformHookWindows;
88import org.openstreetmap.josm.tools.Shortcut;
89import org.openstreetmap.josm.tools.Utils;
90import org.openstreetmap.josm.tools.WindowGeometry;
91
92abstract public class Main {
93
94 /**
95 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
96 * it only shows the MOTD panel.
97 *
98 * @return true if JOSM currently displays a map view
99 */
100 static public boolean isDisplayingMapView() {
101 if (map == null) return false;
102 if (map.mapView == null) return false;
103 return true;
104 }
105 /**
106 * Global parent component for all dialogs and message boxes
107 */
108 public static Component parent;
109 /**
110 * Global application.
111 */
112 public static Main main;
113 /**
114 * The worker thread slave. This is for executing all long and intensive
115 * calculations. The executed runnables are guaranteed to be executed separately
116 * and sequential.
117 */
118 public final static ExecutorService worker = new ProgressMonitorExecutor();
119 /**
120 * Global application preferences
121 */
122 public static Preferences pref;
123
124 /**
125 * The global paste buffer.
126 */
127 public static final PrimitiveDeepCopy pasteBuffer = new PrimitiveDeepCopy();
128 public static Layer pasteSource;
129
130 /**
131 * The MapFrame. Use setMapFrame to set or clear it.
132 */
133 public static MapFrame map;
134 /**
135 * True, when in applet mode
136 */
137 public static boolean applet = false;
138
139 /**
140 * The toolbar preference control to register new actions.
141 */
142 public static ToolbarPreferences toolbar;
143
144 public UndoRedoHandler undoRedo = new UndoRedoHandler();
145
146 public static PleaseWaitProgressMonitor currentProgressMonitor;
147
148 /**
149 * The main menu bar at top of screen.
150 */
151 public MainMenu menu;
152
153 public OsmValidator validator;
154 /**
155 * The MOTD Layer.
156 */
157 private GettingStarted gettingStarted = new GettingStarted();
158
159 /**
160 * Print a message if logging is on.
161 */
162 static public int log_level = 2;
163 static public void warn(String msg) {
164 if (log_level < 1)
165 return;
166 System.out.println(msg);
167 }
168 static public void info(String msg) {
169 if (log_level < 2)
170 return;
171 System.out.println(msg);
172 }
173 static public void debug(String msg) {
174 if (log_level < 3)
175 return;
176 System.out.println(msg);
177 }
178
179 /**
180 * Platform specific code goes in here.
181 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
182 * So if you need to hook into those early ones, split your class and send the one with the early hooks
183 * to the JOSM team for inclusion.
184 */
185 public static PlatformHook platform;
186
187 /**
188 * Whether or not the java vm is openjdk
189 * We use this to work around openjdk bugs
190 */
191 public static boolean isOpenjdk;
192
193 /**
194 * Set or clear (if passed <code>null</code>) the map.
195 */
196 public final void setMapFrame(final MapFrame map) {
197 MapFrame old = Main.map;
198 panel.setVisible(false);
199 panel.removeAll();
200 if (map != null) {
201 map.fillPanel(panel);
202 } else {
203 old.destroy();
204 panel.add(gettingStarted, BorderLayout.CENTER);
205 }
206 panel.setVisible(true);
207 redoUndoListener.commandChanged(0,0);
208
209 Main.map = map;
210
211 PluginHandler.notifyMapFrameChanged(old, map);
212 if (map == null && currentProgressMonitor != null) {
213 currentProgressMonitor.showForegroundDialog();
214 }
215 }
216
217 /**
218 * Remove the specified layer from the map. If it is the last layer,
219 * remove the map as well.
220 */
221 public final void removeLayer(final Layer layer) {
222 if (map != null) {
223 map.mapView.removeLayer(layer);
224 if (map != null && map.mapView.getAllLayers().isEmpty()) {
225 setMapFrame(null);
226 }
227 }
228 }
229
230 private static InitStatusListener initListener = null;
231
232 public static interface InitStatusListener {
233
234 void updateStatus(String event);
235 }
236
237 public static void setInitStatusListener(InitStatusListener listener) {
238 initListener = listener;
239 }
240
241 public Main() {
242 main = this;
243 isOpenjdk = System.getProperty("java.vm.name").toUpperCase().indexOf("OPENJDK") != -1;
244
245 if (initListener != null) {
246 initListener.updateStatus(tr("Executing platform startup hook"));
247 }
248 platform.startupHook();
249
250 if (initListener != null) {
251 initListener.updateStatus(tr("Building main menu"));
252 }
253 contentPanePrivate.add(panel, BorderLayout.CENTER);
254 panel.add(gettingStarted, BorderLayout.CENTER);
255 menu = new MainMenu();
256
257 undoRedo.addCommandQueueListener(redoUndoListener);
258
259 // creating toolbar
260 contentPanePrivate.add(toolbar.control, BorderLayout.NORTH);
261
262 registerActionShortcut(menu.help, Shortcut.registerShortcut("system:help", tr("Help"),
263 KeyEvent.VK_F1, Shortcut.DIRECT));
264
265 // contains several initialization tasks to be executed (in parallel) by a ExecutorService
266 List<Callable<Void>> tasks = new ArrayList<Callable<Void>>();
267
268 tasks.add(new Callable<Void>() {
269
270 @Override
271 public Void call() throws Exception {
272 // We try to establish an API connection early, so that any API
273 // capabilities are already known to the editor instance. However
274 // if it goes wrong that's not critical at this stage.
275 if (initListener != null) {
276 initListener.updateStatus(tr("Initializing OSM API"));
277 }
278 try {
279 OsmApi.getOsmApi().initialize(null, true);
280 } catch (Exception x) {
281 // ignore any exception here.
282 }
283 return null;
284 }
285 });
286
287 tasks.add(new Callable<Void>() {
288
289 @Override
290 public Void call() throws Exception {
291 if (initListener != null) {
292 initListener.updateStatus(tr("Initializing presets"));
293 }
294 TaggingPresetPreference.initialize();
295 // some validator tests require the presets to be initialized
296 // TODO remove this dependency for parallel initialization
297 if (initListener != null) {
298 initListener.updateStatus(tr("Initializing validator"));
299 }
300 validator = new OsmValidator();
301 MapView.addLayerChangeListener(validator);
302 return null;
303 }
304 });
305
306 tasks.add(new Callable<Void>() {
307
308 @Override
309 public Void call() throws Exception {
310 if (initListener != null) {
311 initListener.updateStatus(tr("Initializing map styles"));
312 }
313 MapPaintPreference.initialize();
314 return null;
315 }
316 });
317
318 tasks.add(new Callable<Void>() {
319
320 @Override
321 public Void call() throws Exception {
322 if (initListener != null) {
323 initListener.updateStatus(tr("Loading imagery preferences"));
324 }
325 ImageryPreference.initialize();
326 return null;
327 }
328 });
329
330 try {
331 for (Future<Void> i : Executors.newFixedThreadPool(
332 Runtime.getRuntime().availableProcessors()).invokeAll(tasks)) {
333 i.get();
334 }
335 } catch (Exception ex) {
336 throw new RuntimeException(ex);
337 }
338
339 // hooks for the jmapviewer component
340 FeatureAdapter.registerBrowserAdapter(new FeatureAdapter.BrowserAdapter() {
341 @Override
342 public void openLink(String url) {
343 OpenBrowser.displayUrl(url);
344 }
345 });
346 FeatureAdapter.registerTranslationAdapter(I18n.getTranslationAdapter());
347
348 if (initListener != null) {
349 initListener.updateStatus(tr("Updating user interface"));
350 }
351
352 toolbar.refreshToolbarControl();
353
354 toolbar.control.updateUI();
355 contentPanePrivate.updateUI();
356
357 }
358
359 /**
360 * Add a new layer to the map. If no map exists, create one.
361 */
362 public final synchronized void addLayer(final Layer layer) {
363 if (map == null) {
364 final MapFrame mapFrame = new MapFrame(contentPanePrivate);
365 setMapFrame(mapFrame);
366 mapFrame.selectMapMode((MapMode)mapFrame.getDefaultButtonAction(), layer);
367 mapFrame.setVisible(true);
368 mapFrame.initializeDialogsPane();
369 // bootstrapping problem: make sure the layer list dialog is going to
370 // listen to change events of the very first layer
371 //
372 layer.addPropertyChangeListener(LayerListDialog.getInstance().getModel());
373 }
374 map.mapView.addLayer(layer);
375 }
376
377 /**
378 * Replies true if there is an edit layer
379 *
380 * @return true if there is an edit layer
381 */
382 public boolean hasEditLayer() {
383 if (getEditLayer() == null) return false;
384 return true;
385 }
386
387 /**
388 * Replies the current edit layer
389 *
390 * @return the current edit layer. null, if no current edit layer exists
391 */
392 public OsmDataLayer getEditLayer() {
393 if (map == null) return null;
394 if (map.mapView == null) return null;
395 return map.mapView.getEditLayer();
396 }
397
398 /**
399 * Replies the current data set.
400 *
401 * @return the current data set. null, if no current data set exists
402 */
403 public DataSet getCurrentDataSet() {
404 if (!hasEditLayer()) return null;
405 return getEditLayer().data;
406 }
407
408 /**
409 * Returns the currently active layer
410 *
411 * @return the currently active layer. null, if currently no active layer exists
412 */
413 public Layer getActiveLayer() {
414 if (map == null) return null;
415 if (map.mapView == null) return null;
416 return map.mapView.getActiveLayer();
417 }
418
419 protected static final JPanel contentPanePrivate = new JPanel(new BorderLayout());
420
421 public static void redirectToMainContentPane(JComponent source) {
422 RedirectInputMap.redirect(source, contentPanePrivate);
423 }
424
425 public static void registerActionShortcut(JosmAction action) {
426 registerActionShortcut(action, action.getShortcut());
427 }
428
429 public static void registerActionShortcut(Action action, Shortcut shortcut) {
430 KeyStroke keyStroke = shortcut.getKeyStroke();
431 if (keyStroke == null)
432 return;
433
434 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
435 Object existing = inputMap.get(keyStroke);
436 if (existing != null && !existing.equals(action)) {
437 System.out.println(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
438 }
439 inputMap.put(keyStroke, action);
440
441 contentPanePrivate.getActionMap().put(action, action);
442 }
443
444 public static void unregisterActionShortcut(Shortcut shortcut) {
445 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
446 }
447
448 public static void unregisterActionShortcut(JosmAction action) {
449 unregisterActionShortcut(action, action.getShortcut());
450 }
451
452 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
453 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
454 contentPanePrivate.getActionMap().remove(action);
455 }
456
457 ///////////////////////////////////////////////////////////////////////////
458 // Implementation part
459 ///////////////////////////////////////////////////////////////////////////
460
461 public static final JPanel panel = new JPanel(new BorderLayout());
462
463 protected static WindowGeometry geometry;
464 protected static int windowState = JFrame.NORMAL;
465
466 private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
467 public void commandChanged(final int queueSize, final int redoSize) {
468 menu.undo.setEnabled(queueSize > 0);
469 menu.redo.setEnabled(redoSize > 0);
470 }
471 };
472
473 /**
474 * Should be called before the main constructor to setup some parameter stuff
475 * @param args The parsed argument list.
476 */
477 public static void preConstructorInit(Map<Option, Collection<String>> args) {
478 ProjectionPreference.setProjection();
479
480 try {
481 String defaultlaf = platform.getDefaultStyle();
482 String laf = Main.pref.get("laf", defaultlaf);
483 try {
484 UIManager.setLookAndFeel(laf);
485 }
486 catch (final java.lang.ClassNotFoundException e) {
487 System.out.println("Look and Feel not found: " + laf);
488 Main.pref.put("laf", defaultlaf);
489 }
490 catch (final javax.swing.UnsupportedLookAndFeelException e) {
491 System.out.println("Look and Feel not supported: " + laf);
492 Main.pref.put("laf", defaultlaf);
493 }
494 toolbar = new ToolbarPreferences();
495 contentPanePrivate.updateUI();
496 panel.updateUI();
497 } catch (final Exception e) {
498 e.printStackTrace();
499 }
500 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
501 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
502 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
503 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
504
505 I18n.translateJavaInternalMessages();
506
507 // init default coordinate format
508 //
509 try {
510 //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
511 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
512 } catch (IllegalArgumentException iae) {
513 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
514 }
515
516 geometry = WindowGeometry.mainWindow("gui.geometry",
517 (args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null),
518 !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
519 }
520
521 public void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
522 if (args.containsKey(Option.DOWNLOAD)) {
523 List<File> fileList = new ArrayList<File>();
524 for (String s : args.get(Option.DOWNLOAD)) {
525 File f = null;
526 switch(paramType(s)) {
527 case httpUrl:
528 downloadFromParamHttp(false, s);
529 break;
530 case bounds:
531 downloadFromParamBounds(false, s);
532 break;
533 case fileUrl:
534 try {
535 f = new File(new URI(s));
536 } catch (URISyntaxException e) {
537 JOptionPane.showMessageDialog(
538 Main.parent,
539 tr("Ignoring malformed file URL: \"{0}\"", s),
540 tr("Warning"),
541 JOptionPane.WARNING_MESSAGE
542 );
543 }
544 if (f!=null) {
545 fileList.add(f);
546 }
547 break;
548 case fileName:
549 f = new File(s);
550 fileList.add(f);
551 break;
552 }
553 }
554 if(!fileList.isEmpty())
555 {
556 OpenFileAction.openFiles(fileList, true);
557 }
558 }
559 if (args.containsKey(Option.DOWNLOADGPS)) {
560 for (String s : args.get(Option.DOWNLOADGPS)) {
561 switch(paramType(s)) {
562 case httpUrl:
563 downloadFromParamHttp(true, s);
564 break;
565 case bounds:
566 downloadFromParamBounds(true, s);
567 break;
568 case fileUrl:
569 case fileName:
570 JOptionPane.showMessageDialog(
571 Main.parent,
572 tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
573 tr("Warning"),
574 JOptionPane.WARNING_MESSAGE
575 );
576 }
577 }
578 }
579 if (args.containsKey(Option.SELECTION)) {
580 for (String s : args.get(Option.SELECTION)) {
581 SearchAction.search(s, SearchAction.SearchMode.add);
582 }
583 }
584 }
585
586 public static boolean saveUnsavedModifications() {
587 if (map == null) return true;
588 SaveLayersDialog dialog = new SaveLayersDialog(Main.parent);
589 List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
590 for (OsmDataLayer l: Main.map.mapView.getLayersOfType(OsmDataLayer.class)) {
591 if ((l.requiresSaveToFile() || l.requiresUploadToServer()) && l.data.isModified()) {
592 layersWithUnmodifiedChanges.add(l);
593 }
594 }
595 dialog.prepareForSavingAndUpdatingLayersBeforeExit();
596 if (!layersWithUnmodifiedChanges.isEmpty()) {
597 dialog.getModel().populate(layersWithUnmodifiedChanges);
598 dialog.setVisible(true);
599 switch(dialog.getUserAction()) {
600 case CANCEL: return false;
601 case PROCEED: return true;
602 default: return false;
603 }
604 }
605
606 return true;
607 }
608
609 public static boolean exitJosm(boolean exit) {
610 if (Main.saveUnsavedModifications()) {
611 geometry.remember("gui.geometry");
612 if (map != null) {
613 map.rememberToggleDialogWidth();
614 }
615 pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
616 // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
617 if (Main.isDisplayingMapView()) {
618 Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
619 for (Layer l: layers) {
620 Main.map.mapView.removeLayer(l);
621 }
622 }
623 if (exit) {
624 System.exit(0);
625 return true;
626 } else
627 return true;
628 } else
629 return false;
630 }
631
632 /**
633 * The type of a command line parameter, to be used in switch statements.
634 * @see #paramType
635 */
636 private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
637
638 /**
639 * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
640 * @param s A parameter string
641 * @return The guessed parameter type
642 */
643 private DownloadParamType paramType(String s) {
644 if(s.startsWith("http:")) return DownloadParamType.httpUrl;
645 if(s.startsWith("file:")) return DownloadParamType.fileUrl;
646 String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
647 if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
648 // everything else must be a file name
649 return DownloadParamType.fileName;
650 }
651
652 /**
653 * Download area specified on the command line as OSM URL.
654 * @param rawGps Flag to download raw GPS tracks
655 * @param s The URL parameter
656 */
657 private static void downloadFromParamHttp(final boolean rawGps, String s) {
658 final Bounds b = OsmUrlToBounds.parse(s);
659 if (b == null) {
660 JOptionPane.showMessageDialog(
661 Main.parent,
662 tr("Ignoring malformed URL: \"{0}\"", s),
663 tr("Warning"),
664 JOptionPane.WARNING_MESSAGE
665 );
666 } else {
667 downloadFromParamBounds(rawGps, b);
668 }
669 }
670
671 /**
672 * Download area specified on the command line as bounds string.
673 * @param rawGps Flag to download raw GPS tracks
674 * @param s The bounds parameter
675 */
676 private static void downloadFromParamBounds(final boolean rawGps, String s) {
677 final StringTokenizer st = new StringTokenizer(s, ",");
678 if (st.countTokens() == 4) {
679 Bounds b = new Bounds(
680 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
681 new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
682 );
683 downloadFromParamBounds(rawGps, b);
684 }
685 }
686
687 /**
688 * Download area specified as Bounds value.
689 * @param rawGps Flag to download raw GPS tracks
690 * @param b The bounds value
691 * @see #downloadFromParamBounds(boolean, String)
692 * @see #downloadFromParamHttp
693 */
694 private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
695 DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
696 // asynchronously launch the download task ...
697 Future<?> future = task.download(true, b, null);
698 // ... and the continuation when the download is finished (this will wait for the download to finish)
699 Main.worker.execute(new PostDownloadHandler(task, future));
700 }
701
702 public static void determinePlatformHook() {
703 String os = System.getProperty("os.name");
704 if (os == null) {
705 System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
706 platform = new PlatformHookUnixoid();
707 } else if (os.toLowerCase().startsWith("windows")) {
708 platform = new PlatformHookWindows();
709 } else if (os.equals("Linux") || os.equals("Solaris") ||
710 os.equals("SunOS") || os.equals("AIX") ||
711 os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
712 platform = new PlatformHookUnixoid();
713 } else if (os.toLowerCase().startsWith("mac os x")) {
714 platform = new PlatformHookOsx();
715 } else {
716 System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
717 platform = new PlatformHookUnixoid();
718 }
719 }
720
721 private static class WindowPositionSizeListener extends WindowAdapter implements
722 ComponentListener {
723 @Override
724 public void windowStateChanged(WindowEvent e) {
725 Main.windowState = e.getNewState();
726 }
727
728 @Override
729 public void componentHidden(ComponentEvent e) {
730 }
731
732 @Override
733 public void componentMoved(ComponentEvent e) {
734 handleComponentEvent(e);
735 }
736
737 @Override
738 public void componentResized(ComponentEvent e) {
739 handleComponentEvent(e);
740 }
741
742 @Override
743 public void componentShown(ComponentEvent e) {
744 }
745
746 private void handleComponentEvent(ComponentEvent e) {
747 Component c = e.getComponent();
748 if (c instanceof JFrame && c.isVisible() && Main.windowState == JFrame.NORMAL) {
749 Main.geometry = new WindowGeometry((JFrame) c);
750 }
751 }
752 }
753 public static void addListener() {
754 parent.addComponentListener(new WindowPositionSizeListener());
755 ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
756 }
757
758 public static void checkJava6() {
759 String version = System.getProperty("java.version");
760 if (version != null) {
761 if (version.startsWith("1.6") || version.startsWith("6") ||
762 version.startsWith("1.7") || version.startsWith("7"))
763 return;
764 if (version.startsWith("1.5") || version.startsWith("5")) {
765 JLabel ho = new JLabel("<html>"+
766 tr("<h2>JOSM requires Java version 6.</h2>"+
767 "Detected Java version: {0}.<br>"+
768 "You can <ul><li>update your Java (JRE) or</li>"+
769 "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
770 "More Info:", version)+"</html>");
771 JTextArea link = new JTextArea("http://josm.openstreetmap.de/wiki/Help/SystemRequirements");
772 link.setEditable(false);
773 link.setBackground(panel.getBackground());
774 JPanel panel = new JPanel(new GridBagLayout());
775 GridBagConstraints gbc = new GridBagConstraints();
776 gbc.gridwidth = GridBagConstraints.REMAINDER;
777 gbc.anchor = GridBagConstraints.WEST;
778 gbc.weightx = 1.0;
779 panel.add(ho, gbc);
780 panel.add(link, gbc);
781 final String EXIT = tr("Exit JOSM");
782 final String CONTINUE = tr("Continue, try anyway");
783 int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
784 if (ret == 0) {
785 System.exit(0);
786 }
787 return;
788 }
789 }
790 System.err.println("Error: Could not recognize Java Version: "+version);
791 }
792
793 /* ----------------------------------------------------------------------------------------- */
794 /* projection handling - Main is a registry for a single, global projection instance */
795 /* */
796 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
797 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
798 /* ----------------------------------------------------------------------------------------- */
799 /**
800 * The projection method used.
801 * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
802 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
803 */
804 private static Projection proj;
805
806 /**
807 * Replies the current projection.
808 *
809 * @return
810 */
811 public static Projection getProjection() {
812 return proj;
813 }
814
815 /**
816 * Sets the current projection
817 *
818 * @param p the projection
819 */
820 public static void setProjection(Projection p) {
821 CheckParameterUtil.ensureParameterNotNull(p);
822 Projection oldValue = proj;
823 Bounds b = (Main.map != null && Main.map.mapView != null) ? Main.map.mapView.getRealBounds() : null;
824 proj = p;
825 fireProjectionChanged(oldValue, proj, b);
826 }
827
828 /*
829 * Keep WeakReferences to the listeners. This relieves clients from the burden of
830 * explicitly removing the listeners and allows us to transparently register every
831 * created dataset as projection change listener.
832 */
833 private static final ArrayList<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
834
835 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
836 if (newValue == null ^ oldValue == null
837 || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
838
839 synchronized(Main.class) {
840 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
841 while(it.hasNext()){
842 WeakReference<ProjectionChangeListener> wr = it.next();
843 ProjectionChangeListener listener = wr.get();
844 if (listener == null) {
845 it.remove();
846 continue;
847 }
848 listener.projectionChanged(oldValue, newValue);
849 }
850 }
851 if (newValue != null && oldBounds != null) {
852 Main.map.mapView.zoomTo(oldBounds);
853 }
854 /* TODO - remove layers with fixed projection */
855 }
856 }
857
858 /**
859 * Register a projection change listener
860 *
861 * @param listener the listener. Ignored if null.
862 */
863 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
864 if (listener == null) return;
865 synchronized (Main.class) {
866 for (WeakReference<ProjectionChangeListener> wr : listeners) {
867 // already registered ? => abort
868 if (wr.get() == listener) return;
869 }
870 listeners.add(new WeakReference<ProjectionChangeListener>(listener));
871 }
872 }
873
874 /**
875 * Removes a projection change listener
876 *
877 * @param listener the listener. Ignored if null.
878 */
879 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
880 if (listener == null) return;
881 synchronized(Main.class){
882 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
883 while(it.hasNext()){
884 WeakReference<ProjectionChangeListener> wr = it.next();
885 // remove the listener - and any other listener which god garbage
886 // collected in the meantime
887 if (wr.get() == null || wr.get() == listener) {
888 it.remove();
889 }
890 }
891 }
892 }
893}
Note: See TracBrowser for help on using the repository browser.