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

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

see #15182 - deprecate Main.getLayerManager(). Replacement: gui.MainApplication.getLayerManager()

  • Property svn:eol-style set to native
File size: 41.5 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.awt.GraphicsEnvironment;
8import java.io.IOException;
9import java.lang.ref.WeakReference;
10import java.net.URL;
11import java.text.MessageFormat;
12import java.util.ArrayList;
13import java.util.Arrays;
14import java.util.Collection;
15import java.util.Collections;
16import java.util.EnumSet;
17import java.util.HashMap;
18import java.util.Iterator;
19import java.util.List;
20import java.util.Locale;
21import java.util.Map;
22import java.util.Objects;
23import java.util.Set;
24import java.util.concurrent.Callable;
25import java.util.concurrent.ExecutionException;
26import java.util.concurrent.ExecutorService;
27import java.util.concurrent.Executors;
28import java.util.concurrent.Future;
29
30import javax.swing.Action;
31import javax.swing.InputMap;
32import javax.swing.JComponent;
33import javax.swing.KeyStroke;
34import javax.swing.LookAndFeel;
35import javax.swing.UIManager;
36import javax.swing.UnsupportedLookAndFeelException;
37
38import org.openstreetmap.josm.actions.JosmAction;
39import org.openstreetmap.josm.data.Bounds;
40import org.openstreetmap.josm.data.Preferences;
41import org.openstreetmap.josm.data.UndoRedoHandler;
42import org.openstreetmap.josm.data.cache.JCSCacheManager;
43import org.openstreetmap.josm.data.coor.CoordinateFormat;
44import org.openstreetmap.josm.data.osm.DataSet;
45import org.openstreetmap.josm.data.osm.OsmPrimitive;
46import org.openstreetmap.josm.data.projection.Projection;
47import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
48import org.openstreetmap.josm.gui.MainApplication;
49import org.openstreetmap.josm.gui.MainMenu;
50import org.openstreetmap.josm.gui.MainPanel;
51import org.openstreetmap.josm.gui.MapFrame;
52import org.openstreetmap.josm.gui.MapFrameListener;
53import org.openstreetmap.josm.gui.layer.MainLayerManager;
54import org.openstreetmap.josm.gui.layer.OsmDataLayer.CommandQueueListener;
55import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
56import org.openstreetmap.josm.gui.preferences.display.LafPreference;
57import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
58import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
59import org.openstreetmap.josm.io.FileWatcher;
60import org.openstreetmap.josm.io.OnlineResource;
61import org.openstreetmap.josm.io.OsmApi;
62import org.openstreetmap.josm.plugins.PluginHandler;
63import org.openstreetmap.josm.tools.CheckParameterUtil;
64import org.openstreetmap.josm.tools.I18n;
65import org.openstreetmap.josm.tools.ImageProvider;
66import org.openstreetmap.josm.tools.JosmRuntimeException;
67import org.openstreetmap.josm.tools.Logging;
68import org.openstreetmap.josm.tools.PlatformHook;
69import org.openstreetmap.josm.tools.PlatformHookOsx;
70import org.openstreetmap.josm.tools.PlatformHookUnixoid;
71import org.openstreetmap.josm.tools.PlatformHookWindows;
72import org.openstreetmap.josm.tools.Shortcut;
73import org.openstreetmap.josm.tools.Utils;
74import org.openstreetmap.josm.tools.bugreport.BugReport;
75
76/**
77 * Abstract class holding various static global variables and methods used in large parts of JOSM application.
78 * @since 98
79 */
80public abstract class Main {
81
82 /**
83 * The JOSM website URL.
84 * @since 6897 (was public from 6143 to 6896)
85 */
86 private static final String JOSM_WEBSITE = "https://josm.openstreetmap.de";
87
88 /**
89 * The OSM website URL.
90 * @since 6897 (was public from 6453 to 6896)
91 */
92 private static final String OSM_WEBSITE = "https://www.openstreetmap.org";
93
94 /**
95 * Replies true if JOSM currently displays a map view. False, if it doesn't, i.e. if
96 * it only shows the MOTD panel.
97 * <p>
98 * You do not need this when accessing the layer manager. The layer manager will be empty if no map view is shown.
99 *
100 * @return <code>true</code> if JOSM currently displays a map view
101 * @deprecated use {@link org.openstreetmap.josm.gui.MainApplication#isDisplayingMapView()}
102 */
103 @Deprecated
104 public static boolean isDisplayingMapView() {
105 return MainApplication.isDisplayingMapView();
106 }
107
108 /**
109 * Global parent component for all dialogs and message boxes
110 */
111 public static Component parent;
112
113 /**
114 * Global application.
115 */
116 public static volatile Main main;
117
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 and sequential.
121 * @deprecated use {@link MainApplication#worker} instead
122 */
123 @Deprecated
124 public static final ExecutorService worker = MainApplication.worker;
125
126 /**
127 * Global application preferences
128 */
129 public static final Preferences pref = new Preferences();
130
131 /**
132 * The MapFrame.
133 * <p>
134 * There should be no need to access this to access any map data. Use {@link #layerManager} instead.
135 *
136 * @deprecated Use {@link org.openstreetmap.josm.gui.MainApplication#getMap()} instead
137 * @see MainPanel
138 */
139 @Deprecated
140 public static MapFrame map;
141
142 /**
143 * The toolbar preference control to register new actions.
144 */
145 public static volatile ToolbarPreferences toolbar;
146
147 /**
148 * The commands undo/redo handler.
149 */
150 public final UndoRedoHandler undoRedo = new UndoRedoHandler();
151
152 /**
153 * The progress monitor being currently displayed.
154 */
155 public static PleaseWaitProgressMonitor currentProgressMonitor;
156
157 /**
158 * The main menu bar at top of screen.
159 */
160 public MainMenu menu;
161
162 /**
163 * The main panel.
164 * @since 12125
165 */
166 public MainPanel panel;
167
168 /**
169 * The same main panel, required to be static for {@code MapFrameListener} handling.
170 */
171 protected static MainPanel mainPanel;
172
173 /**
174 * The private content pane of {@code MainFrame}, required to be static for shortcut handling.
175 */
176 protected static JComponent contentPanePrivate;
177
178 /**
179 * The file watcher service.
180 */
181 public static final FileWatcher fileWatcher = new FileWatcher();
182
183 private static final Map<String, Throwable> NETWORK_ERRORS = new HashMap<>();
184
185 private static final Set<OnlineResource> OFFLINE_RESOURCES = EnumSet.noneOf(OnlineResource.class);
186
187 /**
188 * Logging level (5 = trace, 4 = debug, 3 = info, 2 = warn, 1 = error, 0 = none).
189 * @since 6248
190 * @deprecated Use {@link Logging} class.
191 */
192 @Deprecated
193 public static int logLevel = 3;
194
195 /**
196 * Replies the first lines of last 5 error and warning messages, used for bug reports
197 * @return the first lines of last 5 error and warning messages
198 * @since 7420
199 * @deprecated Use {@link Logging#getLastErrorAndWarnings}.
200 */
201 @Deprecated
202 public static final Collection<String> getLastErrorAndWarnings() {
203 return Logging.getLastErrorAndWarnings();
204 }
205
206 /**
207 * Clears the list of last error and warning messages.
208 * @since 8959
209 * @deprecated Use {@link Logging#clearLastErrorAndWarnings}.
210 */
211 @Deprecated
212 public static void clearLastErrorAndWarnings() {
213 Logging.clearLastErrorAndWarnings();
214 }
215
216 /**
217 * Prints an error message if logging is on.
218 * @param msg The message to print.
219 * @since 6248
220 * @deprecated Use {@link Logging#error(String)}.
221 */
222 @Deprecated
223 public static void error(String msg) {
224 Logging.error(msg);
225 }
226
227 /**
228 * Prints a warning message if logging is on.
229 * @param msg The message to print.
230 * @deprecated Use {@link Logging#warn(String)}.
231 */
232 @Deprecated
233 public static void warn(String msg) {
234 Logging.warn(msg);
235 }
236
237 /**
238 * Prints an informational message if logging is on.
239 * @param msg The message to print.
240 * @deprecated Use {@link Logging#info(String)}.
241 */
242 @Deprecated
243 public static void info(String msg) {
244 Logging.info(msg);
245 }
246
247 /**
248 * Prints a debug message if logging is on.
249 * @param msg The message to print.
250 * @deprecated Use {@link Logging#debug(String)}.
251 */
252 @Deprecated
253 public static void debug(String msg) {
254 Logging.debug(msg);
255 }
256
257 /**
258 * Prints a trace message if logging is on.
259 * @param msg The message to print.
260 * @deprecated Use {@link Logging#trace(String)}.
261 */
262 @Deprecated
263 public static void trace(String msg) {
264 Logging.trace(msg);
265 }
266
267 /**
268 * Determines if debug log level is enabled.
269 * Useful to avoid costly construction of debug messages when not enabled.
270 * @return {@code true} if log level is at least debug, {@code false} otherwise
271 * @since 6852
272 * @deprecated Use {@link Logging#isDebugEnabled}.
273 */
274 @Deprecated
275 public static boolean isDebugEnabled() {
276 return Logging.isDebugEnabled();
277 }
278
279 /**
280 * Determines if trace log level is enabled.
281 * Useful to avoid costly construction of trace messages when not enabled.
282 * @return {@code true} if log level is at least trace, {@code false} otherwise
283 * @since 6852
284 * @deprecated Use {@link Logging#isTraceEnabled}.
285 */
286 @Deprecated
287 public static boolean isTraceEnabled() {
288 return Logging.isTraceEnabled();
289 }
290
291 /**
292 * Prints a formatted error message if logging is on. Calls {@link MessageFormat#format}
293 * function to format text.
294 * @param msg The formatted message to print.
295 * @param objects The objects to insert into format string.
296 * @since 6248
297 * @deprecated Use {@link Logging#error(String, Object...)}.
298 */
299 @Deprecated
300 public static void error(String msg, Object... objects) {
301 Logging.error(msg, objects);
302 }
303
304 /**
305 * Prints a formatted warning message if logging is on. Calls {@link MessageFormat#format}
306 * function to format text.
307 * @param msg The formatted message to print.
308 * @param objects The objects to insert into format string.
309 * @deprecated Use {@link Logging#warn(String, Object...)}.
310 */
311 @Deprecated
312 public static void warn(String msg, Object... objects) {
313 Logging.warn(msg, objects);
314 }
315
316 /**
317 * Prints a formatted informational message if logging is on. Calls {@link MessageFormat#format}
318 * function to format text.
319 * @param msg The formatted message to print.
320 * @param objects The objects to insert into format string.
321 * @deprecated Use {@link Logging#info(String, Object...)}.
322 */
323 @Deprecated
324 public static void info(String msg, Object... objects) {
325 Logging.info(msg, objects);
326 }
327
328 /**
329 * Prints a formatted debug message if logging is on. Calls {@link MessageFormat#format}
330 * function to format text.
331 * @param msg The formatted message to print.
332 * @param objects The objects to insert into format string.
333 * @deprecated Use {@link Logging#debug(String, Object...)}.
334 */
335 @Deprecated
336 public static void debug(String msg, Object... objects) {
337 Logging.debug(msg, objects);
338 }
339
340 /**
341 * Prints a formatted trace message if logging is on. Calls {@link MessageFormat#format}
342 * function to format text.
343 * @param msg The formatted message to print.
344 * @param objects The objects to insert into format string.
345 * @deprecated Use {@link Logging#trace(String, Object...)}.
346 */
347 @Deprecated
348 public static void trace(String msg, Object... objects) {
349 Logging.trace(msg, objects);
350 }
351
352 /**
353 * Prints an error message for the given Throwable.
354 * @param t The throwable object causing the error
355 * @since 6248
356 * @deprecated Use {@link Logging#error(Throwable)}.
357 */
358 @Deprecated
359 public static void error(Throwable t) {
360 Logging.error(t);
361 }
362
363 /**
364 * Prints a warning message for the given Throwable.
365 * @param t The throwable object causing the error
366 * @since 6248
367 * @deprecated Use {@link Logging#warn(Throwable)}.
368 */
369 @Deprecated
370 public static void warn(Throwable t) {
371 Logging.warn(t);
372 }
373
374 /**
375 * Prints a debug message for the given Throwable. Useful for exceptions usually ignored
376 * @param t The throwable object causing the error
377 * @since 10420
378 * @deprecated Use {@link Logging#debug(Throwable)}.
379 */
380 @Deprecated
381 public static void debug(Throwable t) {
382 Logging.debug(t);
383 }
384
385 /**
386 * Prints a trace message for the given Throwable. Useful for exceptions usually ignored
387 * @param t The throwable object causing the error
388 * @since 10420
389 * @deprecated Use {@link Logging#trace(Throwable)}.
390 */
391 @Deprecated
392 public static void trace(Throwable t) {
393 Logging.trace(t);
394 }
395
396 /**
397 * Prints an error message for the given Throwable.
398 * @param t The throwable object causing the error
399 * @param stackTrace {@code true}, if the stacktrace should be displayed
400 * @since 6642
401 * @deprecated Use {@link Logging#log(java.util.logging.Level, Throwable)}
402 * or {@link Logging#logWithStackTrace(java.util.logging.Level, Throwable)}.
403 */
404 @Deprecated
405 public static void error(Throwable t, boolean stackTrace) {
406 if (stackTrace) {
407 Logging.log(Logging.LEVEL_ERROR, t);
408 } else {
409 Logging.logWithStackTrace(Logging.LEVEL_ERROR, t);
410 }
411 }
412
413 /**
414 * Prints an error message for the given Throwable.
415 * @param t The throwable object causing the error
416 * @param message additional error message
417 * @since 10420
418 * @deprecated Use {@link Logging#log(java.util.logging.Level, String, Throwable)}.
419 */
420 @Deprecated
421 public static void error(Throwable t, String message) {
422 Logging.log(Logging.LEVEL_ERROR, message, t);
423 }
424
425 /**
426 * Prints a warning message for the given Throwable.
427 * @param t The throwable object causing the error
428 * @param stackTrace {@code true}, if the stacktrace should be displayed
429 * @since 6642
430 * @deprecated Use {@link Logging#log(java.util.logging.Level, Throwable)}
431 * or {@link Logging#logWithStackTrace(java.util.logging.Level, Throwable)}.
432 */
433 @Deprecated
434 public static void warn(Throwable t, boolean stackTrace) {
435 if (stackTrace) {
436 Logging.log(Logging.LEVEL_WARN, t);
437 } else {
438 Logging.logWithStackTrace(Logging.LEVEL_WARN, t);
439 }
440 }
441
442 /**
443 * Prints a warning message for the given Throwable.
444 * @param t The throwable object causing the error
445 * @param message additional error message
446 * @since 10420
447 * @deprecated Use {@link Logging#log(java.util.logging.Level, String, Throwable)}.
448 */
449 @Deprecated
450 public static void warn(Throwable t, String message) {
451 Logging.log(Logging.LEVEL_WARN, message, t);
452 }
453
454 /**
455 * Returns a human-readable message of error, also usable for developers.
456 * @param t The error
457 * @return The human-readable error message
458 * @since 6642
459 * @deprecated Use {@link Logging#getErrorMessage}.
460 */
461 @Deprecated
462 public static String getErrorMessage(Throwable t) {
463 if (t == null) {
464 return null;
465 } else {
466 return Logging.getErrorMessage(t);
467 }
468 }
469
470 /**
471 * Platform specific code goes in here.
472 * Plugins may replace it, however, some hooks will be called before any plugins have been loeaded.
473 * So if you need to hook into those early ones, split your class and send the one with the early hooks
474 * to the JOSM team for inclusion.
475 */
476 public static volatile PlatformHook platform;
477
478 private static volatile InitStatusListener initListener;
479
480 /**
481 * Initialization task listener.
482 */
483 public interface InitStatusListener {
484
485 /**
486 * Called when an initialization task updates its status.
487 * @param event task name
488 * @return new status
489 */
490 Object updateStatus(String event);
491
492 /**
493 * Called when an initialization task completes.
494 * @param status final status
495 */
496 void finish(Object status);
497 }
498
499 /**
500 * Sets initialization task listener.
501 * @param listener initialization task listener
502 */
503 public static void setInitStatusListener(InitStatusListener listener) {
504 CheckParameterUtil.ensureParameterNotNull(listener);
505 initListener = listener;
506 }
507
508 /**
509 * Constructs new {@code Main} object.
510 * @see #initialize()
511 */
512 protected Main() {
513 setInstance(this);
514 }
515
516 private static void setInstance(Main instance) {
517 main = instance;
518 }
519
520 /**
521 * Initializes the main object. A lot of global variables are initialized here.
522 * @since 10340
523 */
524 public void initialize() {
525 // Initializes tasks that must be run before parallel tasks
526 runInitializationTasks(beforeInitializationTasks());
527
528 // Initializes tasks to be executed (in parallel) by a ExecutorService
529 try {
530 ExecutorService service = Executors.newFixedThreadPool(
531 Runtime.getRuntime().availableProcessors(), Utils.newThreadFactory("main-init-%d", Thread.NORM_PRIORITY));
532 for (Future<Void> i : service.invokeAll(parallelInitializationTasks())) {
533 i.get();
534 }
535 // asynchronous initializations to be completed eventually
536 asynchronousRunnableTasks().forEach(service::submit);
537 asynchronousCallableTasks().forEach(service::submit);
538 service.shutdown();
539 } catch (InterruptedException | ExecutionException ex) {
540 throw new JosmRuntimeException(ex);
541 }
542
543 // Initializes tasks that must be run after parallel tasks
544 runInitializationTasks(afterInitializationTasks());
545 }
546
547 private static void runInitializationTasks(List<InitializationTask> tasks) {
548 for (InitializationTask task : tasks) {
549 try {
550 task.call();
551 } catch (JosmRuntimeException e) {
552 // Can happen if the current projection needs NTV2 grid which is not available
553 // In this case we want the user be able to change his projection
554 BugReport.intercept(e).warn();
555 }
556 }
557 }
558
559 /**
560 * Returns tasks that must be run before parallel tasks.
561 * @return tasks that must be run before parallel tasks
562 * @see #afterInitializationTasks
563 * @see #parallelInitializationTasks
564 */
565 protected List<InitializationTask> beforeInitializationTasks() {
566 return Collections.emptyList();
567 }
568
569 /**
570 * Returns tasks to be executed (in parallel) by a ExecutorService.
571 * @return tasks to be executed (in parallel) by a ExecutorService
572 */
573 protected Collection<InitializationTask> parallelInitializationTasks() {
574 return Collections.emptyList();
575 }
576
577 /**
578 * Returns asynchronous callable initializations to be completed eventually
579 * @return asynchronous callable initializations to be completed eventually
580 */
581 protected List<Callable<?>> asynchronousCallableTasks() {
582 return Collections.emptyList();
583 }
584
585 /**
586 * Returns asynchronous runnable initializations to be completed eventually
587 * @return asynchronous runnable initializations to be completed eventually
588 */
589 protected List<Runnable> asynchronousRunnableTasks() {
590 return Collections.emptyList();
591 }
592
593 /**
594 * Returns tasks that must be run after parallel tasks.
595 * @return tasks that must be run after parallel tasks
596 * @see #beforeInitializationTasks
597 * @see #parallelInitializationTasks
598 */
599 protected List<InitializationTask> afterInitializationTasks() {
600 return Collections.emptyList();
601 }
602
603 /**
604 * Called once at startup to initialize the main window content.
605 * Should set {@link #menu} and {@link #panel}
606 */
607 protected abstract void initializeMainWindow();
608
609 protected static final class InitializationTask implements Callable<Void> {
610
611 private final String name;
612 private final Runnable task;
613
614 /**
615 * Constructs a new {@code InitializationTask}.
616 * @param name translated name to be displayed to user
617 * @param task runnable initialization task
618 */
619 public InitializationTask(String name, Runnable task) {
620 this.name = name;
621 this.task = task;
622 }
623
624 @Override
625 public Void call() {
626 Object status = null;
627 if (initListener != null) {
628 status = initListener.updateStatus(name);
629 }
630 task.run();
631 if (initListener != null) {
632 initListener.finish(status);
633 }
634 return null;
635 }
636 }
637
638 /**
639 * Returns the main layer manager that is used by the map view.
640 * @return The layer manager. The value returned will never change.
641 * @since 10279
642 * @deprecated use {@link MainApplication#getLayerManager} instead
643 */
644 @Deprecated
645 public static MainLayerManager getLayerManager() {
646 return MainApplication.getLayerManager();
647 }
648
649 /**
650 * Replies the current selected primitives, from a end-user point of view.
651 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
652 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
653 * @since 6546
654 */
655 public Collection<OsmPrimitive> getInProgressSelection() {
656 return Collections.emptyList();
657 }
658
659 /**
660 * Registers a {@code JosmAction} and its shortcut.
661 * @param action action defining its own shortcut
662 */
663 public static void registerActionShortcut(JosmAction action) {
664 registerActionShortcut(action, action.getShortcut());
665 }
666
667 /**
668 * Registers an action and its shortcut.
669 * @param action action to register
670 * @param shortcut shortcut to associate to {@code action}
671 */
672 public static void registerActionShortcut(Action action, Shortcut shortcut) {
673 KeyStroke keyStroke = shortcut.getKeyStroke();
674 if (keyStroke == null)
675 return;
676
677 InputMap inputMap = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
678 Object existing = inputMap.get(keyStroke);
679 if (existing != null && !existing.equals(action)) {
680 Logging.info(String.format("Keystroke %s is already assigned to %s, will be overridden by %s", keyStroke, existing, action));
681 }
682 inputMap.put(keyStroke, action);
683
684 contentPanePrivate.getActionMap().put(action, action);
685 }
686
687 /**
688 * Unregisters a shortcut.
689 * @param shortcut shortcut to unregister
690 */
691 public static void unregisterShortcut(Shortcut shortcut) {
692 contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).remove(shortcut.getKeyStroke());
693 }
694
695 /**
696 * Unregisters a {@code JosmAction} and its shortcut.
697 * @param action action to unregister
698 */
699 public static void unregisterActionShortcut(JosmAction action) {
700 unregisterActionShortcut(action, action.getShortcut());
701 }
702
703 /**
704 * Unregisters an action and its shortcut.
705 * @param action action to unregister
706 * @param shortcut shortcut to unregister
707 */
708 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
709 unregisterShortcut(shortcut);
710 contentPanePrivate.getActionMap().remove(action);
711 }
712
713 /**
714 * Replies the registered action for the given shortcut
715 * @param shortcut The shortcut to look for
716 * @return the registered action for the given shortcut
717 * @since 5696
718 */
719 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
720 KeyStroke keyStroke = shortcut.getKeyStroke();
721 if (keyStroke == null)
722 return null;
723 Object action = contentPanePrivate.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).get(keyStroke);
724 if (action instanceof Action)
725 return (Action) action;
726 return null;
727 }
728
729 ///////////////////////////////////////////////////////////////////////////
730 // Implementation part
731 ///////////////////////////////////////////////////////////////////////////
732
733 /**
734 * Listener that sets the enabled state of undo/redo menu entries.
735 */
736 protected final CommandQueueListener redoUndoListener = (queueSize, redoSize) -> {
737 menu.undo.setEnabled(queueSize > 0);
738 menu.redo.setEnabled(redoSize > 0);
739 };
740
741 /**
742 * Should be called before the main constructor to setup some parameter stuff
743 */
744 public static void preConstructorInit() {
745 ProjectionPreference.setProjection();
746
747 String defaultlaf = platform.getDefaultStyle();
748 String laf = LafPreference.LAF.get();
749 try {
750 UIManager.setLookAndFeel(laf);
751 } catch (final NoClassDefFoundError | ClassNotFoundException e) {
752 // Try to find look and feel in plugin classloaders
753 Logging.trace(e);
754 Class<?> klass = null;
755 for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
756 try {
757 klass = cl.loadClass(laf);
758 break;
759 } catch (ClassNotFoundException ex) {
760 Logging.trace(ex);
761 }
762 }
763 if (klass != null && LookAndFeel.class.isAssignableFrom(klass)) {
764 try {
765 UIManager.setLookAndFeel((LookAndFeel) klass.getConstructor().newInstance());
766 } catch (ReflectiveOperationException ex) {
767 Logging.log(Logging.LEVEL_WARN, "Cannot set Look and Feel: " + laf + ": "+ex.getMessage(), ex);
768 } catch (UnsupportedLookAndFeelException ex) {
769 Logging.info("Look and Feel not supported: " + laf);
770 LafPreference.LAF.put(defaultlaf);
771 Logging.trace(ex);
772 }
773 } else {
774 Logging.info("Look and Feel not found: " + laf);
775 LafPreference.LAF.put(defaultlaf);
776 }
777 } catch (UnsupportedLookAndFeelException e) {
778 Logging.info("Look and Feel not supported: " + laf);
779 LafPreference.LAF.put(defaultlaf);
780 Logging.trace(e);
781 } catch (InstantiationException | IllegalAccessException e) {
782 Logging.error(e);
783 }
784 toolbar = new ToolbarPreferences();
785
786 UIManager.put("OptionPane.okIcon", ImageProvider.get("ok"));
787 UIManager.put("OptionPane.yesIcon", UIManager.get("OptionPane.okIcon"));
788 UIManager.put("OptionPane.cancelIcon", ImageProvider.get("cancel"));
789 UIManager.put("OptionPane.noIcon", UIManager.get("OptionPane.cancelIcon"));
790 // Ensures caret color is the same than text foreground color, see #12257
791 // See http://docs.oracle.com/javase/8/docs/api/javax/swing/plaf/synth/doc-files/componentProperties.html
792 for (String p : Arrays.asList(
793 "EditorPane", "FormattedTextField", "PasswordField", "TextArea", "TextField", "TextPane")) {
794 UIManager.put(p+".caretForeground", UIManager.getColor(p+".foreground"));
795 }
796
797 I18n.translateJavaInternalMessages();
798
799 // init default coordinate format
800 //
801 try {
802 CoordinateFormat.setCoordinateFormat(CoordinateFormat.valueOf(Main.pref.get("coordinates")));
803 } catch (IllegalArgumentException iae) {
804 Logging.trace(iae);
805 CoordinateFormat.setCoordinateFormat(CoordinateFormat.DECIMAL_DEGREES);
806 }
807 }
808
809 /**
810 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
811 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
812 * @param exitCode The return code
813 * @return {@code true}
814 * @since 12636
815 */
816 public static boolean exitJosm(boolean exit, int exitCode) {
817 if (Main.main != null) {
818 Main.main.shutdown();
819 }
820
821 if (exit) {
822 System.exit(exitCode);
823 }
824 return true;
825 }
826
827 /**
828 * Shutdown JOSM.
829 */
830 protected void shutdown() {
831 if (!GraphicsEnvironment.isHeadless()) {
832 ImageProvider.shutdown(false);
833 JCSCacheManager.shutdown();
834 }
835 try {
836 pref.saveDefaults();
837 } catch (IOException ex) {
838 Logging.log(Logging.LEVEL_WARN, tr("Failed to save default preferences."), ex);
839 }
840 if (!GraphicsEnvironment.isHeadless()) {
841 ImageProvider.shutdown(true);
842 }
843 }
844
845 /**
846 * Identifies the current operating system family and initializes the platform hook accordingly.
847 * @since 1849
848 */
849 public static void determinePlatformHook() {
850 String os = System.getProperty("os.name");
851 if (os == null) {
852 Logging.warn("Your operating system has no name, so I'm guessing its some kind of *nix.");
853 platform = new PlatformHookUnixoid();
854 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("windows")) {
855 platform = new PlatformHookWindows();
856 } else if ("Linux".equals(os) || "Solaris".equals(os) ||
857 "SunOS".equals(os) || "AIX".equals(os) ||
858 "FreeBSD".equals(os) || "NetBSD".equals(os) || "OpenBSD".equals(os)) {
859 platform = new PlatformHookUnixoid();
860 } else if (os.toLowerCase(Locale.ENGLISH).startsWith("mac os x")) {
861 platform = new PlatformHookOsx();
862 } else {
863 Logging.warn("I don't know your operating system '"+os+"', so I'm guessing its some kind of *nix.");
864 platform = new PlatformHookUnixoid();
865 }
866 }
867
868 /* ----------------------------------------------------------------------------------------- */
869 /* projection handling - Main is a registry for a single, global projection instance */
870 /* */
871 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
872 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
873 /* ----------------------------------------------------------------------------------------- */
874 /**
875 * The projection method used.
876 * Use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
877 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
878 */
879 private static volatile Projection proj;
880
881 /**
882 * Replies the current projection.
883 *
884 * @return the currently active projection
885 */
886 public static Projection getProjection() {
887 return proj;
888 }
889
890 /**
891 * Sets the current projection
892 *
893 * @param p the projection
894 */
895 public static void setProjection(Projection p) {
896 CheckParameterUtil.ensureParameterNotNull(p);
897 Projection oldValue = proj;
898 Bounds b = main != null ? main.getRealBounds() : null;
899 proj = p;
900 fireProjectionChanged(oldValue, proj, b);
901 }
902
903 /**
904 * Returns the bounds for the current projection. Used for projection events.
905 * @return the bounds for the current projection
906 * @see #restoreOldBounds
907 */
908 protected Bounds getRealBounds() {
909 // To be overriden
910 return null;
911 }
912
913 /**
914 * Restore clean state corresponding to old bounds after a projection change event.
915 * @param oldBounds bounds previously returned by {@link #getRealBounds}, before the change of projection
916 * @see #getRealBounds
917 */
918 protected void restoreOldBounds(Bounds oldBounds) {
919 // To be overriden
920 }
921
922 /*
923 * Keep WeakReferences to the listeners. This relieves clients from the burden of
924 * explicitly removing the listeners and allows us to transparently register every
925 * created dataset as projection change listener.
926 */
927 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<>();
928
929 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
930 if ((newValue == null ^ oldValue == null)
931 || (newValue != null && oldValue != null && !Objects.equals(newValue.toCode(), oldValue.toCode()))) {
932 synchronized (Main.class) {
933 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
934 while (it.hasNext()) {
935 WeakReference<ProjectionChangeListener> wr = it.next();
936 ProjectionChangeListener listener = wr.get();
937 if (listener == null) {
938 it.remove();
939 continue;
940 }
941 listener.projectionChanged(oldValue, newValue);
942 }
943 }
944 if (newValue != null && oldBounds != null && main != null) {
945 main.restoreOldBounds(oldBounds);
946 }
947 /* TODO - remove layers with fixed projection */
948 }
949 }
950
951 /**
952 * Register a projection change listener.
953 * The listener is registered to be weak, so keep a reference of it if you want it to be preserved.
954 *
955 * @param listener the listener. Ignored if <code>null</code>.
956 */
957 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
958 if (listener == null) return;
959 synchronized (Main.class) {
960 for (WeakReference<ProjectionChangeListener> wr : listeners) {
961 // already registered ? => abort
962 if (wr.get() == listener) return;
963 }
964 listeners.add(new WeakReference<>(listener));
965 }
966 }
967
968 /**
969 * Removes a projection change listener.
970 *
971 * @param listener the listener. Ignored if <code>null</code>.
972 */
973 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
974 if (listener == null) return;
975 synchronized (Main.class) {
976 // remove the listener - and any other listener which got garbage
977 // collected in the meantime
978 listeners.removeIf(wr -> wr.get() == null || wr.get() == listener);
979 }
980 }
981
982 /**
983 * Listener for window switch events.
984 *
985 * These are events, when the user activates a window of another application
986 * or comes back to JOSM. Window switches from one JOSM window to another
987 * are not reported.
988 */
989 public interface WindowSwitchListener {
990 /**
991 * Called when the user activates a window of another application.
992 */
993 void toOtherApplication();
994
995 /**
996 * Called when the user comes from a window of another application back to JOSM.
997 */
998 void fromOtherApplication();
999 }
1000
1001 /**
1002 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes.
1003 * <p>
1004 * It will fire an initial mapFrameInitialized event when the MapFrame is present.
1005 * Otherwise will only fire when the MapFrame is created or destroyed.
1006 * @param listener The MapFrameListener
1007 * @return {@code true} if the listeners collection changed as a result of the call
1008 * @see #addMapFrameListener
1009 * @since 11904
1010 */
1011 public static boolean addAndFireMapFrameListener(MapFrameListener listener) {
1012 return mainPanel != null && mainPanel.addAndFireMapFrameListener(listener);
1013 }
1014
1015 /**
1016 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
1017 * @param listener The MapFrameListener
1018 * @return {@code true} if the listeners collection changed as a result of the call
1019 * @see #addAndFireMapFrameListener
1020 * @since 5957
1021 */
1022 public static boolean addMapFrameListener(MapFrameListener listener) {
1023 return mainPanel != null && mainPanel.addMapFrameListener(listener);
1024 }
1025
1026 /**
1027 * Unregisters the given {@code MapFrameListener} from MapFrame changes
1028 * @param listener The MapFrameListener
1029 * @return {@code true} if the listeners collection changed as a result of the call
1030 * @since 5957
1031 */
1032 public static boolean removeMapFrameListener(MapFrameListener listener) {
1033 return mainPanel != null && mainPanel.removeMapFrameListener(listener);
1034 }
1035
1036 /**
1037 * Adds a new network error that occur to give a hint about broken Internet connection.
1038 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1039 *
1040 * @param url The accessed URL that caused the error
1041 * @param t The network error
1042 * @return The previous error associated to the given resource, if any. Can be {@code null}
1043 * @since 6642
1044 */
1045 public static Throwable addNetworkError(URL url, Throwable t) {
1046 if (url != null && t != null) {
1047 Throwable old = addNetworkError(url.toExternalForm(), t);
1048 if (old != null) {
1049 Logging.warn("Already here "+old);
1050 }
1051 return old;
1052 }
1053 return null;
1054 }
1055
1056 /**
1057 * Adds a new network error that occur to give a hint about broken Internet connection.
1058 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
1059 *
1060 * @param url The accessed URL that caused the error
1061 * @param t The network error
1062 * @return The previous error associated to the given resource, if any. Can be {@code null}
1063 * @since 6642
1064 */
1065 public static Throwable addNetworkError(String url, Throwable t) {
1066 if (url != null && t != null) {
1067 return NETWORK_ERRORS.put(url, t);
1068 }
1069 return null;
1070 }
1071
1072 /**
1073 * Returns the network errors that occured until now.
1074 * @return the network errors that occured until now, indexed by URL
1075 * @since 6639
1076 */
1077 public static Map<String, Throwable> getNetworkErrors() {
1078 return new HashMap<>(NETWORK_ERRORS);
1079 }
1080
1081 /**
1082 * Clears the network errors cache.
1083 * @since 12011
1084 */
1085 public static void clearNetworkErrors() {
1086 NETWORK_ERRORS.clear();
1087 }
1088
1089 /**
1090 * Returns the JOSM website URL.
1091 * @return the josm website URL
1092 * @since 6897
1093 */
1094 public static String getJOSMWebsite() {
1095 if (Main.pref != null)
1096 return Main.pref.get("josm.url", JOSM_WEBSITE);
1097 return JOSM_WEBSITE;
1098 }
1099
1100 /**
1101 * Returns the JOSM XML URL.
1102 * @return the josm XML URL
1103 * @since 6897
1104 */
1105 public static String getXMLBase() {
1106 // Always return HTTP (issues reported with HTTPS)
1107 return "http://josm.openstreetmap.de";
1108 }
1109
1110 /**
1111 * Returns the OSM website URL.
1112 * @return the OSM website URL
1113 * @since 6897
1114 */
1115 public static String getOSMWebsite() {
1116 if (Main.pref != null)
1117 return Main.pref.get("osm.url", OSM_WEBSITE);
1118 return OSM_WEBSITE;
1119 }
1120
1121 /**
1122 * Returns the OSM website URL depending on the selected {@link OsmApi}.
1123 * @return the OSM website URL depending on the selected {@link OsmApi}
1124 */
1125 private static String getOSMWebsiteDependingOnSelectedApi() {
1126 final String api = OsmApi.getOsmApi().getServerUrl();
1127 if (OsmApi.DEFAULT_API_URL.equals(api)) {
1128 return getOSMWebsite();
1129 } else {
1130 return api.replaceAll("/api$", "");
1131 }
1132 }
1133
1134 /**
1135 * Replies the base URL for browsing information about a primitive.
1136 * @return the base URL, i.e. https://www.openstreetmap.org
1137 * @since 7678
1138 */
1139 public static String getBaseBrowseUrl() {
1140 if (Main.pref != null)
1141 return Main.pref.get("osm-browse.url", getOSMWebsiteDependingOnSelectedApi());
1142 return getOSMWebsiteDependingOnSelectedApi();
1143 }
1144
1145 /**
1146 * Replies the base URL for browsing information about a user.
1147 * @return the base URL, i.e. https://www.openstreetmap.org/user
1148 * @since 7678
1149 */
1150 public static String getBaseUserUrl() {
1151 if (Main.pref != null)
1152 return Main.pref.get("osm-user.url", getOSMWebsiteDependingOnSelectedApi() + "/user");
1153 return getOSMWebsiteDependingOnSelectedApi() + "/user";
1154 }
1155
1156 /**
1157 * Determines if we are currently running on OSX.
1158 * @return {@code true} if we are currently running on OSX
1159 * @since 6957
1160 */
1161 public static boolean isPlatformOsx() {
1162 return Main.platform instanceof PlatformHookOsx;
1163 }
1164
1165 /**
1166 * Determines if we are currently running on Windows.
1167 * @return {@code true} if we are currently running on Windows
1168 * @since 7335
1169 */
1170 public static boolean isPlatformWindows() {
1171 return Main.platform instanceof PlatformHookWindows;
1172 }
1173
1174 /**
1175 * Determines if the given online resource is currently offline.
1176 * @param r the online resource
1177 * @return {@code true} if {@code r} is offline and should not be accessed
1178 * @since 7434
1179 */
1180 public static boolean isOffline(OnlineResource r) {
1181 return OFFLINE_RESOURCES.contains(r) || OFFLINE_RESOURCES.contains(OnlineResource.ALL);
1182 }
1183
1184 /**
1185 * Sets the given online resource to offline state.
1186 * @param r the online resource
1187 * @return {@code true} if {@code r} was not already offline
1188 * @since 7434
1189 */
1190 public static boolean setOffline(OnlineResource r) {
1191 return OFFLINE_RESOURCES.add(r);
1192 }
1193
1194 /**
1195 * Sets the given online resource to online state.
1196 * @param r the online resource
1197 * @return {@code true} if {@code r} was offline
1198 * @since 8506
1199 */
1200 public static boolean setOnline(OnlineResource r) {
1201 return OFFLINE_RESOURCES.remove(r);
1202 }
1203
1204 /**
1205 * Replies the set of online resources currently offline.
1206 * @return the set of online resources currently offline
1207 * @since 7434
1208 */
1209 public static Set<OnlineResource> getOfflineResources() {
1210 return EnumSet.copyOf(OFFLINE_RESOURCES);
1211 }
1212}
Note: See TracBrowser for help on using the repository browser.