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

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

Rework console output:

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