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

Last change on this file since 5732 was 5696, checked in by Don-vip, 11 years ago

Disable single-char JOSM shortcuts when relation dialog filter textfield has focus (see r5616 comment)

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