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

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

see #15182 - deprecate Main.main.panel. Replacement: gui.MainApplication.getMainPanel()

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