1 | // License: GPL. Copyright 2007 by Immanuel Scholz and others
|
---|
2 | package org.openstreetmap.josm;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.awt.BorderLayout;
|
---|
7 | import java.awt.Component;
|
---|
8 | import java.awt.GridBagConstraints;
|
---|
9 | import java.awt.GridBagLayout;
|
---|
10 | import java.awt.Window;
|
---|
11 | import java.awt.event.ComponentEvent;
|
---|
12 | import java.awt.event.ComponentListener;
|
---|
13 | import java.awt.event.KeyEvent;
|
---|
14 | import java.awt.event.WindowAdapter;
|
---|
15 | import java.awt.event.WindowEvent;
|
---|
16 | import java.io.File;
|
---|
17 | import java.lang.ref.WeakReference;
|
---|
18 | import java.net.URI;
|
---|
19 | import java.net.URISyntaxException;
|
---|
20 | import java.text.MessageFormat;
|
---|
21 | import java.util.ArrayList;
|
---|
22 | import java.util.Arrays;
|
---|
23 | import java.util.Collection;
|
---|
24 | import java.util.Iterator;
|
---|
25 | import java.util.List;
|
---|
26 | import java.util.Map;
|
---|
27 | import java.util.StringTokenizer;
|
---|
28 | import java.util.concurrent.Callable;
|
---|
29 | import java.util.concurrent.ExecutorService;
|
---|
30 | import java.util.concurrent.Executors;
|
---|
31 | import java.util.concurrent.Future;
|
---|
32 |
|
---|
33 | import javax.swing.Action;
|
---|
34 | import javax.swing.InputMap;
|
---|
35 | import javax.swing.JComponent;
|
---|
36 | import javax.swing.JFrame;
|
---|
37 | import javax.swing.JLabel;
|
---|
38 | import javax.swing.JOptionPane;
|
---|
39 | import javax.swing.JPanel;
|
---|
40 | import javax.swing.JTextArea;
|
---|
41 | import javax.swing.KeyStroke;
|
---|
42 | import javax.swing.UIManager;
|
---|
43 |
|
---|
44 | import org.openstreetmap.gui.jmapviewer.FeatureAdapter;
|
---|
45 | import org.openstreetmap.josm.actions.JosmAction;
|
---|
46 | import org.openstreetmap.josm.actions.OpenFileAction;
|
---|
47 | import org.openstreetmap.josm.actions.downloadtasks.DownloadGpsTask;
|
---|
48 | import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
|
---|
49 | import org.openstreetmap.josm.actions.downloadtasks.DownloadTask;
|
---|
50 | import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
|
---|
51 | import org.openstreetmap.josm.actions.mapmode.MapMode;
|
---|
52 | import org.openstreetmap.josm.actions.search.SearchAction;
|
---|
53 | import org.openstreetmap.josm.data.Bounds;
|
---|
54 | import org.openstreetmap.josm.data.Preferences;
|
---|
55 | import org.openstreetmap.josm.data.UndoRedoHandler;
|
---|
56 | import org.openstreetmap.josm.data.coor.CoordinateFormat;
|
---|
57 | import org.openstreetmap.josm.data.coor.LatLon;
|
---|
58 | import org.openstreetmap.josm.data.osm.DataSet;
|
---|
59 | import org.openstreetmap.josm.data.osm.PrimitiveDeepCopy;
|
---|
60 | import org.openstreetmap.josm.data.projection.Projection;
|
---|
61 | import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
|
---|
62 | import org.openstreetmap.josm.data.validation.OsmValidator;
|
---|
63 | import org.openstreetmap.josm.gui.GettingStarted;
|
---|
64 | import org.openstreetmap.josm.gui.MainApplication.Option;
|
---|
65 | import org.openstreetmap.josm.gui.MainMenu;
|
---|
66 | import org.openstreetmap.josm.gui.MapFrame;
|
---|
67 | import org.openstreetmap.josm.gui.MapView;
|
---|
68 | import org.openstreetmap.josm.gui.NavigatableComponent.ViewportData;
|
---|
69 | import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
|
---|
70 | import org.openstreetmap.josm.gui.io.SaveLayersDialog;
|
---|
71 | import org.openstreetmap.josm.gui.layer.Layer;
|
---|
72 | import org.openstreetmap.josm.gui.layer.OsmDataLayer;
|
---|
73 | import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
|
---|
74 | import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
|
---|
75 | import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
|
---|
76 | import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
|
---|
77 | import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
|
---|
78 | import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
|
---|
79 | import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
|
---|
80 | import org.openstreetmap.josm.gui.progress.ProgressMonitorExecutor;
|
---|
81 | import org.openstreetmap.josm.gui.util.RedirectInputMap;
|
---|
82 | import org.openstreetmap.josm.io.OsmApi;
|
---|
83 | import org.openstreetmap.josm.plugins.PluginHandler;
|
---|
84 | import org.openstreetmap.josm.tools.CheckParameterUtil;
|
---|
85 | import org.openstreetmap.josm.tools.I18n;
|
---|
86 | import org.openstreetmap.josm.tools.ImageProvider;
|
---|
87 | import org.openstreetmap.josm.tools.OpenBrowser;
|
---|
88 | import org.openstreetmap.josm.tools.OsmUrlToBounds;
|
---|
89 | import org.openstreetmap.josm.tools.PlatformHook;
|
---|
90 | import org.openstreetmap.josm.tools.PlatformHookOsx;
|
---|
91 | import org.openstreetmap.josm.tools.PlatformHookUnixoid;
|
---|
92 | import org.openstreetmap.josm.tools.PlatformHookWindows;
|
---|
93 | import org.openstreetmap.josm.tools.Shortcut;
|
---|
94 | import org.openstreetmap.josm.tools.Utils;
|
---|
95 | import org.openstreetmap.josm.tools.WindowGeometry;
|
---|
96 |
|
---|
97 | abstract 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 | // Implementation part
|
---|
516 | ///////////////////////////////////////////////////////////////////////////
|
---|
517 |
|
---|
518 | public static final JPanel panel = new JPanel(new BorderLayout());
|
---|
519 |
|
---|
520 | protected static WindowGeometry geometry;
|
---|
521 | protected static int windowState = JFrame.NORMAL;
|
---|
522 |
|
---|
523 | private final CommandQueueListener redoUndoListener = new CommandQueueListener(){
|
---|
524 | public void commandChanged(final int queueSize, final int redoSize) {
|
---|
525 | menu.undo.setEnabled(queueSize > 0);
|
---|
526 | menu.redo.setEnabled(redoSize > 0);
|
---|
527 | }
|
---|
528 | };
|
---|
529 |
|
---|
530 | /**
|
---|
531 | * Should be called before the main constructor to setup some parameter stuff
|
---|
532 | * @param args The parsed argument list.
|
---|
533 | */
|
---|
534 | public static void preConstructorInit(Map<Option, Collection<String>> args) {
|
---|
535 | ProjectionPreference.setProjection();
|
---|
536 |
|
---|
537 | try {
|
---|
538 | String defaultlaf = platform.getDefaultStyle();
|
---|
539 | String laf = Main.pref.get("laf", defaultlaf);
|
---|
540 | try {
|
---|
541 | UIManager.setLookAndFeel(laf);
|
---|
542 | }
|
---|
543 | catch (final java.lang.ClassNotFoundException e) {
|
---|
544 | System.out.println("Look and Feel not found: " + laf);
|
---|
545 | Main.pref.put("laf", defaultlaf);
|
---|
546 | }
|
---|
547 | catch (final javax.swing.UnsupportedLookAndFeelException e) {
|
---|
548 | System.out.println("Look and Feel not supported: " + laf);
|
---|
549 | Main.pref.put("laf", defaultlaf);
|
---|
550 | }
|
---|
551 | toolbar = new ToolbarPreferences();
|
---|
552 | contentPanePrivate.updateUI();
|
---|
553 | panel.updateUI();
|
---|
554 | } catch (final Exception e) {
|
---|
555 | e.printStackTrace();
|
---|
556 | }
|
---|
557 | UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
|
---|
558 | UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
|
---|
559 | UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
|
---|
560 | UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
|
---|
561 |
|
---|
562 | I18n.translateJavaInternalMessages();
|
---|
563 |
|
---|
564 | // init default coordinate format
|
---|
565 | //
|
---|
566 | try {
|
---|
567 | //CoordinateFormat format = CoordinateFormat.valueOf(Main.pref.get("coordinates"));
|
---|
568 | CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
|
---|
569 | } catch (IllegalArgumentException iae) {
|
---|
570 | CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
|
---|
571 | }
|
---|
572 |
|
---|
573 | geometry = WindowGeometry.mainWindow("gui.geometry",
|
---|
574 | (args.containsKey(Option.GEOMETRY) ? args.get(Option.GEOMETRY).iterator().next() : null),
|
---|
575 | !args.containsKey(Option.NO_MAXIMIZE) && Main.pref.getBoolean("gui.maximized", false));
|
---|
576 | }
|
---|
577 |
|
---|
578 | public void postConstructorProcessCmdLine(Map<Option, Collection<String>> args) {
|
---|
579 | if (args.containsKey(Option.DOWNLOAD)) {
|
---|
580 | List<File> fileList = new ArrayList<File>();
|
---|
581 | for (String s : args.get(Option.DOWNLOAD)) {
|
---|
582 | File f = null;
|
---|
583 | switch(paramType(s)) {
|
---|
584 | case httpUrl:
|
---|
585 | downloadFromParamHttp(false, s);
|
---|
586 | break;
|
---|
587 | case bounds:
|
---|
588 | downloadFromParamBounds(false, s);
|
---|
589 | break;
|
---|
590 | case fileUrl:
|
---|
591 | try {
|
---|
592 | f = new File(new URI(s));
|
---|
593 | } catch (URISyntaxException e) {
|
---|
594 | JOptionPane.showMessageDialog(
|
---|
595 | Main.parent,
|
---|
596 | tr("Ignoring malformed file URL: \"{0}\"", s),
|
---|
597 | tr("Warning"),
|
---|
598 | JOptionPane.WARNING_MESSAGE
|
---|
599 | );
|
---|
600 | }
|
---|
601 | if (f!=null) {
|
---|
602 | fileList.add(f);
|
---|
603 | }
|
---|
604 | break;
|
---|
605 | case fileName:
|
---|
606 | f = new File(s);
|
---|
607 | fileList.add(f);
|
---|
608 | break;
|
---|
609 | }
|
---|
610 | }
|
---|
611 | if(!fileList.isEmpty())
|
---|
612 | {
|
---|
613 | OpenFileAction.openFiles(fileList, true);
|
---|
614 | }
|
---|
615 | }
|
---|
616 | if (args.containsKey(Option.DOWNLOADGPS)) {
|
---|
617 | for (String s : args.get(Option.DOWNLOADGPS)) {
|
---|
618 | switch(paramType(s)) {
|
---|
619 | case httpUrl:
|
---|
620 | downloadFromParamHttp(true, s);
|
---|
621 | break;
|
---|
622 | case bounds:
|
---|
623 | downloadFromParamBounds(true, s);
|
---|
624 | break;
|
---|
625 | case fileUrl:
|
---|
626 | case fileName:
|
---|
627 | JOptionPane.showMessageDialog(
|
---|
628 | Main.parent,
|
---|
629 | tr("Parameter \"downloadgps\" does not accept file names or file URLs"),
|
---|
630 | tr("Warning"),
|
---|
631 | JOptionPane.WARNING_MESSAGE
|
---|
632 | );
|
---|
633 | }
|
---|
634 | }
|
---|
635 | }
|
---|
636 | if (args.containsKey(Option.SELECTION)) {
|
---|
637 | for (String s : args.get(Option.SELECTION)) {
|
---|
638 | SearchAction.search(s, SearchAction.SearchMode.add);
|
---|
639 | }
|
---|
640 | }
|
---|
641 | }
|
---|
642 |
|
---|
643 | /**
|
---|
644 | * 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.
|
---|
645 | * @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.
|
---|
646 | * @since 2025
|
---|
647 | */
|
---|
648 | public static boolean saveUnsavedModifications() {
|
---|
649 | if (map == null || map.mapView == null) return true;
|
---|
650 | return saveUnsavedModifications(map.mapView.getLayersOfType(OsmDataLayer.class), true);
|
---|
651 | }
|
---|
652 |
|
---|
653 | /**
|
---|
654 | * Asks user to perform "save layer" operations (save .osm on disk and/or upload osm data to server) before osm layers deletion.
|
---|
655 | *
|
---|
656 | * @param selectedLayers The layers to check. Only instances of {@link OsmDataLayer} are considered.
|
---|
657 | * @param exit {@code true} if JOSM is exiting, {@code false} otherwise.
|
---|
658 | * @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.
|
---|
659 | * @since 5519
|
---|
660 | */
|
---|
661 | public static boolean saveUnsavedModifications(List<? extends Layer> selectedLayers, boolean exit) {
|
---|
662 | SaveLayersDialog dialog = new SaveLayersDialog(parent);
|
---|
663 | List<OsmDataLayer> layersWithUnmodifiedChanges = new ArrayList<OsmDataLayer>();
|
---|
664 | for (Layer l: selectedLayers) {
|
---|
665 | if (!(l instanceof OsmDataLayer)) {
|
---|
666 | continue;
|
---|
667 | }
|
---|
668 | OsmDataLayer odl = (OsmDataLayer)l;
|
---|
669 | if ((odl.requiresSaveToFile() || (odl.requiresUploadToServer() && !odl.isUploadDiscouraged())) && odl.data.isModified()) {
|
---|
670 | layersWithUnmodifiedChanges.add(odl);
|
---|
671 | }
|
---|
672 | }
|
---|
673 | if (exit) {
|
---|
674 | dialog.prepareForSavingAndUpdatingLayersBeforeExit();
|
---|
675 | } else {
|
---|
676 | dialog.prepareForSavingAndUpdatingLayersBeforeDelete();
|
---|
677 | }
|
---|
678 | if (!layersWithUnmodifiedChanges.isEmpty()) {
|
---|
679 | dialog.getModel().populate(layersWithUnmodifiedChanges);
|
---|
680 | dialog.setVisible(true);
|
---|
681 | switch(dialog.getUserAction()) {
|
---|
682 | case CANCEL: return false;
|
---|
683 | case PROCEED: return true;
|
---|
684 | default: return false;
|
---|
685 | }
|
---|
686 | }
|
---|
687 |
|
---|
688 | return true;
|
---|
689 | }
|
---|
690 |
|
---|
691 | public static boolean exitJosm(boolean exit) {
|
---|
692 | if (Main.saveUnsavedModifications()) {
|
---|
693 | geometry.remember("gui.geometry");
|
---|
694 | if (map != null) {
|
---|
695 | map.rememberToggleDialogWidth();
|
---|
696 | }
|
---|
697 | pref.put("gui.maximized", (windowState & JFrame.MAXIMIZED_BOTH) != 0);
|
---|
698 | // Remove all layers because somebody may rely on layerRemoved events (like AutosaveTask)
|
---|
699 | if (Main.isDisplayingMapView()) {
|
---|
700 | Collection<Layer> layers = new ArrayList<Layer>(Main.map.mapView.getAllLayers());
|
---|
701 | for (Layer l: layers) {
|
---|
702 | Main.map.mapView.removeLayer(l);
|
---|
703 | }
|
---|
704 | }
|
---|
705 | if (exit) {
|
---|
706 | System.exit(0);
|
---|
707 | return true;
|
---|
708 | } else
|
---|
709 | return true;
|
---|
710 | } else
|
---|
711 | return false;
|
---|
712 | }
|
---|
713 |
|
---|
714 | /**
|
---|
715 | * The type of a command line parameter, to be used in switch statements.
|
---|
716 | * @see #paramType
|
---|
717 | */
|
---|
718 | private enum DownloadParamType { httpUrl, fileUrl, bounds, fileName }
|
---|
719 |
|
---|
720 | /**
|
---|
721 | * Guess the type of a parameter string specified on the command line with --download= or --downloadgps.
|
---|
722 | * @param s A parameter string
|
---|
723 | * @return The guessed parameter type
|
---|
724 | */
|
---|
725 | private DownloadParamType paramType(String s) {
|
---|
726 | if(s.startsWith("http:")) return DownloadParamType.httpUrl;
|
---|
727 | if(s.startsWith("file:")) return DownloadParamType.fileUrl;
|
---|
728 | String coorPattern = "\\s*[+-]?[0-9]+(\\.[0-9]+)?\\s*";
|
---|
729 | if(s.matches(coorPattern+"(,"+coorPattern+"){3}")) return DownloadParamType.bounds;
|
---|
730 | // everything else must be a file name
|
---|
731 | return DownloadParamType.fileName;
|
---|
732 | }
|
---|
733 |
|
---|
734 | /**
|
---|
735 | * Download area specified on the command line as OSM URL.
|
---|
736 | * @param rawGps Flag to download raw GPS tracks
|
---|
737 | * @param s The URL parameter
|
---|
738 | */
|
---|
739 | private static void downloadFromParamHttp(final boolean rawGps, String s) {
|
---|
740 | final Bounds b = OsmUrlToBounds.parse(s);
|
---|
741 | if (b == null) {
|
---|
742 | JOptionPane.showMessageDialog(
|
---|
743 | Main.parent,
|
---|
744 | tr("Ignoring malformed URL: \"{0}\"", s),
|
---|
745 | tr("Warning"),
|
---|
746 | JOptionPane.WARNING_MESSAGE
|
---|
747 | );
|
---|
748 | } else {
|
---|
749 | downloadFromParamBounds(rawGps, b);
|
---|
750 | }
|
---|
751 | }
|
---|
752 |
|
---|
753 | /**
|
---|
754 | * Download area specified on the command line as bounds string.
|
---|
755 | * @param rawGps Flag to download raw GPS tracks
|
---|
756 | * @param s The bounds parameter
|
---|
757 | */
|
---|
758 | private static void downloadFromParamBounds(final boolean rawGps, String s) {
|
---|
759 | final StringTokenizer st = new StringTokenizer(s, ",");
|
---|
760 | if (st.countTokens() == 4) {
|
---|
761 | Bounds b = new Bounds(
|
---|
762 | new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken())),
|
---|
763 | new LatLon(Double.parseDouble(st.nextToken()),Double.parseDouble(st.nextToken()))
|
---|
764 | );
|
---|
765 | downloadFromParamBounds(rawGps, b);
|
---|
766 | }
|
---|
767 | }
|
---|
768 |
|
---|
769 | /**
|
---|
770 | * Download area specified as Bounds value.
|
---|
771 | * @param rawGps Flag to download raw GPS tracks
|
---|
772 | * @param b The bounds value
|
---|
773 | * @see #downloadFromParamBounds(boolean, String)
|
---|
774 | * @see #downloadFromParamHttp
|
---|
775 | */
|
---|
776 | private static void downloadFromParamBounds(final boolean rawGps, Bounds b) {
|
---|
777 | DownloadTask task = rawGps ? new DownloadGpsTask() : new DownloadOsmTask();
|
---|
778 | // asynchronously launch the download task ...
|
---|
779 | Future<?> future = task.download(true, b, null);
|
---|
780 | // ... and the continuation when the download is finished (this will wait for the download to finish)
|
---|
781 | Main.worker.execute(new PostDownloadHandler(task, future));
|
---|
782 | }
|
---|
783 |
|
---|
784 | public static void determinePlatformHook() {
|
---|
785 | String os = System.getProperty("os.name");
|
---|
786 | if (os == null) {
|
---|
787 | System.err.println("Your operating system has no name, so I'm guessing its some kind of *nix.");
|
---|
788 | platform = new PlatformHookUnixoid();
|
---|
789 | } else if (os.toLowerCase().startsWith("windows")) {
|
---|
790 | platform = new PlatformHookWindows();
|
---|
791 | } else if (os.equals("Linux") || os.equals("Solaris") ||
|
---|
792 | os.equals("SunOS") || os.equals("AIX") ||
|
---|
793 | os.equals("FreeBSD") || os.equals("NetBSD") || os.equals("OpenBSD")) {
|
---|
794 | platform = new PlatformHookUnixoid();
|
---|
795 | } else if (os.toLowerCase().startsWith("mac os x")) {
|
---|
796 | platform = new PlatformHookOsx();
|
---|
797 | } else {
|
---|
798 | System.err.println("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
|
---|
799 | platform = new PlatformHookUnixoid();
|
---|
800 | }
|
---|
801 | }
|
---|
802 |
|
---|
803 | private static class WindowPositionSizeListener extends WindowAdapter implements
|
---|
804 | ComponentListener {
|
---|
805 | @Override
|
---|
806 | public void windowStateChanged(WindowEvent e) {
|
---|
807 | Main.windowState = e.getNewState();
|
---|
808 | }
|
---|
809 |
|
---|
810 | @Override
|
---|
811 | public void componentHidden(ComponentEvent e) {
|
---|
812 | }
|
---|
813 |
|
---|
814 | @Override
|
---|
815 | public void componentMoved(ComponentEvent e) {
|
---|
816 | handleComponentEvent(e);
|
---|
817 | }
|
---|
818 |
|
---|
819 | @Override
|
---|
820 | public void componentResized(ComponentEvent e) {
|
---|
821 | handleComponentEvent(e);
|
---|
822 | }
|
---|
823 |
|
---|
824 | @Override
|
---|
825 | public void componentShown(ComponentEvent e) {
|
---|
826 | }
|
---|
827 |
|
---|
828 | private void handleComponentEvent(ComponentEvent e) {
|
---|
829 | Component c = e.getComponent();
|
---|
830 | if (c instanceof JFrame && c.isVisible()) {
|
---|
831 | if(Main.windowState == JFrame.NORMAL) {
|
---|
832 | Main.geometry = new WindowGeometry((JFrame) c);
|
---|
833 | } else {
|
---|
834 | Main.geometry.fixScreen((JFrame) c);
|
---|
835 | }
|
---|
836 | }
|
---|
837 | }
|
---|
838 | }
|
---|
839 | public static void addListener() {
|
---|
840 | parent.addComponentListener(new WindowPositionSizeListener());
|
---|
841 | ((JFrame)parent).addWindowStateListener(new WindowPositionSizeListener());
|
---|
842 | }
|
---|
843 |
|
---|
844 | public static void checkJava6() {
|
---|
845 | String version = System.getProperty("java.version");
|
---|
846 | if (version != null) {
|
---|
847 | if (version.startsWith("1.6") || version.startsWith("6") ||
|
---|
848 | version.startsWith("1.7") || version.startsWith("7"))
|
---|
849 | return;
|
---|
850 | if (version.startsWith("1.5") || version.startsWith("5")) {
|
---|
851 | JLabel ho = new JLabel("<html>"+
|
---|
852 | tr("<h2>JOSM requires Java version 6.</h2>"+
|
---|
853 | "Detected Java version: {0}.<br>"+
|
---|
854 | "You can <ul><li>update your Java (JRE) or</li>"+
|
---|
855 | "<li>use an earlier (Java 5 compatible) version of JOSM.</li></ul>"+
|
---|
856 | "More Info:", version)+"</html>");
|
---|
857 | JTextArea link = new JTextArea("http://josm.openstreetmap.de/wiki/Help/SystemRequirements");
|
---|
858 | link.setEditable(false);
|
---|
859 | link.setBackground(panel.getBackground());
|
---|
860 | JPanel panel = new JPanel(new GridBagLayout());
|
---|
861 | GridBagConstraints gbc = new GridBagConstraints();
|
---|
862 | gbc.gridwidth = GridBagConstraints.REMAINDER;
|
---|
863 | gbc.anchor = GridBagConstraints.WEST;
|
---|
864 | gbc.weightx = 1.0;
|
---|
865 | panel.add(ho, gbc);
|
---|
866 | panel.add(link, gbc);
|
---|
867 | final String EXIT = tr("Exit JOSM");
|
---|
868 | final String CONTINUE = tr("Continue, try anyway");
|
---|
869 | int ret = JOptionPane.showOptionDialog(null, panel, tr("Error"), JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new String[] {EXIT, CONTINUE}, EXIT);
|
---|
870 | if (ret == 0) {
|
---|
871 | System.exit(0);
|
---|
872 | }
|
---|
873 | return;
|
---|
874 | }
|
---|
875 | }
|
---|
876 | System.err.println("Error: Could not recognize Java Version: "+version);
|
---|
877 | }
|
---|
878 |
|
---|
879 | /* ----------------------------------------------------------------------------------------- */
|
---|
880 | /* projection handling - Main is a registry for a single, global projection instance */
|
---|
881 | /* */
|
---|
882 | /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
|
---|
883 | /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
|
---|
884 | /* ----------------------------------------------------------------------------------------- */
|
---|
885 | /**
|
---|
886 | * The projection method used.
|
---|
887 | * use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
|
---|
888 | * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
|
---|
889 | */
|
---|
890 | private static Projection proj;
|
---|
891 |
|
---|
892 | /**
|
---|
893 | * Replies the current projection.
|
---|
894 | *
|
---|
895 | * @return the currently active projection
|
---|
896 | */
|
---|
897 | public static Projection getProjection() {
|
---|
898 | return proj;
|
---|
899 | }
|
---|
900 |
|
---|
901 | /**
|
---|
902 | * Sets the current projection
|
---|
903 | *
|
---|
904 | * @param p the projection
|
---|
905 | */
|
---|
906 | public static void setProjection(Projection p) {
|
---|
907 | CheckParameterUtil.ensureParameterNotNull(p);
|
---|
908 | Projection oldValue = proj;
|
---|
909 | Bounds b = isDisplayingMapView() ? map.mapView.getRealBounds() : null;
|
---|
910 | proj = p;
|
---|
911 | fireProjectionChanged(oldValue, proj, b);
|
---|
912 | }
|
---|
913 |
|
---|
914 | /*
|
---|
915 | * Keep WeakReferences to the listeners. This relieves clients from the burden of
|
---|
916 | * explicitly removing the listeners and allows us to transparently register every
|
---|
917 | * created dataset as projection change listener.
|
---|
918 | */
|
---|
919 | private static final ArrayList<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<WeakReference<ProjectionChangeListener>>();
|
---|
920 |
|
---|
921 | private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
|
---|
922 | if (newValue == null ^ oldValue == null
|
---|
923 | || (newValue != null && oldValue != null && !Utils.equal(newValue.toCode(), oldValue.toCode()))) {
|
---|
924 |
|
---|
925 | synchronized(Main.class) {
|
---|
926 | Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
|
---|
927 | while (it.hasNext()){
|
---|
928 | WeakReference<ProjectionChangeListener> wr = it.next();
|
---|
929 | ProjectionChangeListener listener = wr.get();
|
---|
930 | if (listener == null) {
|
---|
931 | it.remove();
|
---|
932 | continue;
|
---|
933 | }
|
---|
934 | listener.projectionChanged(oldValue, newValue);
|
---|
935 | }
|
---|
936 | }
|
---|
937 | if (newValue != null && oldBounds != null) {
|
---|
938 | Main.map.mapView.zoomTo(oldBounds);
|
---|
939 | }
|
---|
940 | /* TODO - remove layers with fixed projection */
|
---|
941 | }
|
---|
942 | }
|
---|
943 |
|
---|
944 | /**
|
---|
945 | * Register a projection change listener.
|
---|
946 | *
|
---|
947 | * @param listener the listener. Ignored if <code>null</code>.
|
---|
948 | */
|
---|
949 | public static void addProjectionChangeListener(ProjectionChangeListener listener) {
|
---|
950 | if (listener == null) return;
|
---|
951 | synchronized (Main.class) {
|
---|
952 | for (WeakReference<ProjectionChangeListener> wr : listeners) {
|
---|
953 | // already registered ? => abort
|
---|
954 | if (wr.get() == listener) return;
|
---|
955 | }
|
---|
956 | listeners.add(new WeakReference<ProjectionChangeListener>(listener));
|
---|
957 | }
|
---|
958 | }
|
---|
959 |
|
---|
960 | /**
|
---|
961 | * Removes a projection change listener.
|
---|
962 | *
|
---|
963 | * @param listener the listener. Ignored if <code>null</code>.
|
---|
964 | */
|
---|
965 | public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
|
---|
966 | if (listener == null) return;
|
---|
967 | synchronized(Main.class){
|
---|
968 | Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
|
---|
969 | while (it.hasNext()){
|
---|
970 | WeakReference<ProjectionChangeListener> wr = it.next();
|
---|
971 | // remove the listener - and any other listener which got garbage
|
---|
972 | // collected in the meantime
|
---|
973 | if (wr.get() == null || wr.get() == listener) {
|
---|
974 | it.remove();
|
---|
975 | }
|
---|
976 | }
|
---|
977 | }
|
---|
978 | }
|
---|
979 |
|
---|
980 | /**
|
---|
981 | * Listener for window switch events.
|
---|
982 | *
|
---|
983 | * These are events, when the user activates a window of another application
|
---|
984 | * or comes back to JOSM. Window switches from one JOSM window to another
|
---|
985 | * are not reported.
|
---|
986 | */
|
---|
987 | public static interface WindowSwitchListener {
|
---|
988 | /**
|
---|
989 | * Called when the user activates a window of another application.
|
---|
990 | */
|
---|
991 | void toOtherApplication();
|
---|
992 | /**
|
---|
993 | * Called when the user comes from a window of another application
|
---|
994 | * back to JOSM.
|
---|
995 | */
|
---|
996 | void fromOtherApplication();
|
---|
997 | }
|
---|
998 |
|
---|
999 | private static final ArrayList<WeakReference<WindowSwitchListener>> windowSwitchListeners = new ArrayList<WeakReference<WindowSwitchListener>>();
|
---|
1000 |
|
---|
1001 | /**
|
---|
1002 | * Register a window switch listener.
|
---|
1003 | *
|
---|
1004 | * @param listener the listener. Ignored if <code>null</code>.
|
---|
1005 | */
|
---|
1006 | public static void addWindowSwitchListener(WindowSwitchListener listener) {
|
---|
1007 | if (listener == null) return;
|
---|
1008 | synchronized (Main.class) {
|
---|
1009 | for (WeakReference<WindowSwitchListener> wr : windowSwitchListeners) {
|
---|
1010 | // already registered ? => abort
|
---|
1011 | if (wr.get() == listener) return;
|
---|
1012 | }
|
---|
1013 | boolean wasEmpty = windowSwitchListeners.isEmpty();
|
---|
1014 | windowSwitchListeners.add(new WeakReference<WindowSwitchListener>(listener));
|
---|
1015 | if (wasEmpty) {
|
---|
1016 | // The following call will have no effect, when there is no window
|
---|
1017 | // at the time. Therefore, MasterWindowListener.setup() will also be
|
---|
1018 | // called, as soon as the main window is shown.
|
---|
1019 | MasterWindowListener.setup();
|
---|
1020 | }
|
---|
1021 | }
|
---|
1022 | }
|
---|
1023 |
|
---|
1024 | /**
|
---|
1025 | * Removes a window switch listener.
|
---|
1026 | *
|
---|
1027 | * @param listener the listener. Ignored if <code>null</code>.
|
---|
1028 | */
|
---|
1029 | public static void removeWindowSwitchListener(WindowSwitchListener listener) {
|
---|
1030 | if (listener == null) return;
|
---|
1031 | synchronized (Main.class){
|
---|
1032 | Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
|
---|
1033 | while (it.hasNext()){
|
---|
1034 | WeakReference<WindowSwitchListener> wr = it.next();
|
---|
1035 | // remove the listener - and any other listener which got garbage
|
---|
1036 | // collected in the meantime
|
---|
1037 | if (wr.get() == null || wr.get() == listener) {
|
---|
1038 | it.remove();
|
---|
1039 | }
|
---|
1040 | }
|
---|
1041 | if (windowSwitchListeners.isEmpty()) {
|
---|
1042 | MasterWindowListener.teardown();
|
---|
1043 | }
|
---|
1044 | }
|
---|
1045 | }
|
---|
1046 |
|
---|
1047 | /**
|
---|
1048 | * WindowListener, that is registered on all Windows of the application.
|
---|
1049 | *
|
---|
1050 | * Its purpose is to notify WindowSwitchListeners, that the user switches to
|
---|
1051 | * another application, e.g. a browser, or back to JOSM.
|
---|
1052 | *
|
---|
1053 | * When changing from JOSM to another application and back (e.g. two times
|
---|
1054 | * alt+tab), the active Window within JOSM may be different.
|
---|
1055 | * Therefore, we need to register listeners to <strong>all</strong> (visible)
|
---|
1056 | * Windows in JOSM, and it does not suffice to monitor the one that was
|
---|
1057 | * deactivated last.
|
---|
1058 | *
|
---|
1059 | * This class is only "active" on demand, i.e. when there is at least one
|
---|
1060 | * WindowSwitchListener registered.
|
---|
1061 | */
|
---|
1062 | protected static class MasterWindowListener extends WindowAdapter {
|
---|
1063 |
|
---|
1064 | private static MasterWindowListener INSTANCE;
|
---|
1065 |
|
---|
1066 | public static MasterWindowListener getInstance() {
|
---|
1067 | if (INSTANCE == null) {
|
---|
1068 | INSTANCE = new MasterWindowListener();
|
---|
1069 | }
|
---|
1070 | return INSTANCE;
|
---|
1071 | }
|
---|
1072 |
|
---|
1073 | /**
|
---|
1074 | * Register listeners to all non-hidden windows.
|
---|
1075 | *
|
---|
1076 | * Windows that are created later, will be cared for in {@link #windowDeactivated(WindowEvent)}.
|
---|
1077 | */
|
---|
1078 | public static void setup() {
|
---|
1079 | if (!windowSwitchListeners.isEmpty()) {
|
---|
1080 | for (Window w : Window.getWindows()) {
|
---|
1081 | if (w.isShowing()) {
|
---|
1082 | if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
|
---|
1083 | w.addWindowListener(getInstance());
|
---|
1084 | }
|
---|
1085 | }
|
---|
1086 | }
|
---|
1087 | }
|
---|
1088 | }
|
---|
1089 |
|
---|
1090 | /**
|
---|
1091 | * Unregister all listeners.
|
---|
1092 | */
|
---|
1093 | public static void teardown() {
|
---|
1094 | for (Window w : Window.getWindows()) {
|
---|
1095 | w.removeWindowListener(getInstance());
|
---|
1096 | }
|
---|
1097 | }
|
---|
1098 |
|
---|
1099 | @Override
|
---|
1100 | public void windowActivated(WindowEvent e) {
|
---|
1101 | if (e.getOppositeWindow() == null) { // we come from a window of a different application
|
---|
1102 | // fire WindowSwitchListeners
|
---|
1103 | synchronized (Main.class) {
|
---|
1104 | Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
|
---|
1105 | while (it.hasNext()){
|
---|
1106 | WeakReference<WindowSwitchListener> wr = it.next();
|
---|
1107 | WindowSwitchListener listener = wr.get();
|
---|
1108 | if (listener == null) {
|
---|
1109 | it.remove();
|
---|
1110 | continue;
|
---|
1111 | }
|
---|
1112 | listener.fromOtherApplication();
|
---|
1113 | }
|
---|
1114 | }
|
---|
1115 | }
|
---|
1116 | }
|
---|
1117 |
|
---|
1118 | @Override
|
---|
1119 | public void windowDeactivated(WindowEvent e) {
|
---|
1120 | // set up windows that have been created in the meantime
|
---|
1121 | for (Window w : Window.getWindows()) {
|
---|
1122 | if (!w.isShowing()) {
|
---|
1123 | w.removeWindowListener(getInstance());
|
---|
1124 | } else {
|
---|
1125 | if (!Arrays.asList(w.getWindowListeners()).contains(getInstance())) {
|
---|
1126 | w.addWindowListener(getInstance());
|
---|
1127 | }
|
---|
1128 | }
|
---|
1129 | }
|
---|
1130 | if (e.getOppositeWindow() == null) { // we go to a window of a different application
|
---|
1131 | // fire WindowSwitchListeners
|
---|
1132 | synchronized (Main.class) {
|
---|
1133 | Iterator<WeakReference<WindowSwitchListener>> it = windowSwitchListeners.iterator();
|
---|
1134 | while (it.hasNext()){
|
---|
1135 | WeakReference<WindowSwitchListener> wr = it.next();
|
---|
1136 | WindowSwitchListener listener = wr.get();
|
---|
1137 | if (listener == null) {
|
---|
1138 | it.remove();
|
---|
1139 | continue;
|
---|
1140 | }
|
---|
1141 | listener.toOtherApplication();
|
---|
1142 | }
|
---|
1143 | }
|
---|
1144 | }
|
---|
1145 | }
|
---|
1146 | }
|
---|
1147 |
|
---|
1148 | }
|
---|