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

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

update license/copyright information

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