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

Last change on this file since 6546 was 6546, checked in by Don-vip, 10 years ago

fix #9482, see #9423, see #6853 - fix regression from r6542: irregular behaviour drawing ways

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