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

Last change on this file since 13133 was 13023, checked in by bastiK, 7 years ago

see #15451 - fix initialization

  • Property svn:eol-style set to native
File size: 37.7 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.Map;
20import java.util.Objects;
21import java.util.Set;
22import java.util.concurrent.Callable;
23import java.util.concurrent.ExecutionException;
24import java.util.concurrent.ExecutorService;
25import java.util.concurrent.Executors;
26import java.util.concurrent.Future;
27
28import javax.swing.Action;
29
30import org.openstreetmap.josm.actions.JosmAction;
31import org.openstreetmap.josm.data.Bounds;
32import org.openstreetmap.josm.data.Preferences;
33import org.openstreetmap.josm.data.UndoRedoHandler;
34import org.openstreetmap.josm.data.coor.conversion.CoordinateFormatManager;
35import org.openstreetmap.josm.data.coor.conversion.DecimalDegreesCoordinateFormat;
36import org.openstreetmap.josm.data.coor.conversion.ICoordinateFormat;
37import org.openstreetmap.josm.data.osm.DataSet;
38import org.openstreetmap.josm.data.osm.OsmPrimitive;
39import org.openstreetmap.josm.data.preferences.JosmBaseDirectories;
40import org.openstreetmap.josm.data.projection.Projection;
41import org.openstreetmap.josm.data.projection.ProjectionChangeListener;
42import org.openstreetmap.josm.gui.MainApplication;
43import org.openstreetmap.josm.gui.MainMenu;
44import org.openstreetmap.josm.gui.MainPanel;
45import org.openstreetmap.josm.gui.MapFrame;
46import org.openstreetmap.josm.gui.MapFrameListener;
47import org.openstreetmap.josm.gui.layer.MainLayerManager;
48import org.openstreetmap.josm.gui.preferences.ToolbarPreferences;
49import org.openstreetmap.josm.io.FileWatcher;
50import org.openstreetmap.josm.io.OnlineResource;
51import org.openstreetmap.josm.io.OsmApi;
52import org.openstreetmap.josm.spi.preferences.Config;
53import org.openstreetmap.josm.tools.CheckParameterUtil;
54import org.openstreetmap.josm.tools.ImageProvider;
55import org.openstreetmap.josm.tools.JosmRuntimeException;
56import org.openstreetmap.josm.tools.Logging;
57import org.openstreetmap.josm.tools.Platform;
58import org.openstreetmap.josm.tools.PlatformHook;
59import org.openstreetmap.josm.tools.PlatformHookOsx;
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 ExecutorService worker;
114
115 /**
116 * Global application preferences
117 */
118 public static final Preferences pref = new Preferences(JosmBaseDirectories.getInstance());
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 */
141 public final UndoRedoHandler undoRedo = new UndoRedoHandler();
142
143 /**
144 * The main menu bar at top of screen.
145 * @deprecated Use {@link MainApplication#getMenu} instead
146 */
147 @Deprecated
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 protected static final class InitializationTask implements Callable<Void> {
584
585 private final String name;
586 private final Runnable task;
587
588 /**
589 * Constructs a new {@code InitializationTask}.
590 * @param name translated name to be displayed to user
591 * @param task runnable initialization task
592 */
593 public InitializationTask(String name, Runnable task) {
594 this.name = name;
595 this.task = task;
596 }
597
598 @Override
599 public Void call() {
600 Object status = null;
601 if (initListener != null) {
602 status = initListener.updateStatus(name);
603 }
604 task.run();
605 if (initListener != null) {
606 initListener.finish(status);
607 }
608 return null;
609 }
610 }
611
612 /**
613 * Returns the main layer manager that is used by the map view.
614 * @return The layer manager. The value returned will never change.
615 * @since 10279
616 * @deprecated use {@link MainApplication#getLayerManager} instead
617 */
618 @Deprecated
619 public static MainLayerManager getLayerManager() {
620 return MainApplication.getLayerManager();
621 }
622
623 /**
624 * Replies the current selected primitives, from a end-user point of view.
625 * It is not always technically the same collection of primitives than {@link DataSet#getSelected()}.
626 * @return The current selected primitives, from a end-user point of view. Can be {@code null}.
627 * @since 6546
628 */
629 public Collection<OsmPrimitive> getInProgressSelection() {
630 return Collections.emptyList();
631 }
632
633 /**
634 * Gets the active edit data set.
635 * @return That data set, <code>null</code>.
636 * @since 12691
637 */
638 public abstract DataSet getEditDataSet();
639
640 /**
641 * Sets the active data set.
642 * @param ds New edit data set, or <code>null</code>
643 * @since 12718
644 */
645 public abstract void setEditDataSet(DataSet ds);
646
647 /**
648 * Determines if the list of data sets managed by JOSM contains {@code ds}.
649 * @param ds the data set to look for
650 * @return {@code true} if the list of data sets managed by JOSM contains {@code ds}
651 * @since 12718
652 */
653 public abstract boolean containsDataSet(DataSet ds);
654
655 /**
656 * Registers a {@code JosmAction} and its shortcut.
657 * @param action action defining its own shortcut
658 * @deprecated use {@link MainApplication#registerActionShortcut(JosmAction)} instead
659 */
660 @Deprecated
661 public static void registerActionShortcut(JosmAction action) {
662 MainApplication.registerActionShortcut(action);
663 }
664
665 /**
666 * Registers an action and its shortcut.
667 * @param action action to register
668 * @param shortcut shortcut to associate to {@code action}
669 * @deprecated use {@link MainApplication#registerActionShortcut(Action, Shortcut)} instead
670 */
671 @Deprecated
672 public static void registerActionShortcut(Action action, Shortcut shortcut) {
673 MainApplication.registerActionShortcut(action, shortcut);
674 }
675
676 /**
677 * Unregisters a shortcut.
678 * @param shortcut shortcut to unregister
679 * @deprecated use {@link MainApplication#unregisterShortcut(Shortcut)} instead
680 */
681 @Deprecated
682 public static void unregisterShortcut(Shortcut shortcut) {
683 MainApplication.unregisterShortcut(shortcut);
684 }
685
686 /**
687 * Unregisters a {@code JosmAction} and its shortcut.
688 * @param action action to unregister
689 * @deprecated use {@link MainApplication#unregisterActionShortcut(JosmAction)} instead
690 */
691 @Deprecated
692 public static void unregisterActionShortcut(JosmAction action) {
693 MainApplication.unregisterActionShortcut(action);
694 }
695
696 /**
697 * Unregisters an action and its shortcut.
698 * @param action action to unregister
699 * @param shortcut shortcut to unregister
700 * @deprecated use {@link MainApplication#unregisterActionShortcut(Action, Shortcut)} instead
701 */
702 @Deprecated
703 public static void unregisterActionShortcut(Action action, Shortcut shortcut) {
704 MainApplication.unregisterActionShortcut(action, shortcut);
705 }
706
707 /**
708 * Replies the registered action for the given shortcut
709 * @param shortcut The shortcut to look for
710 * @return the registered action for the given shortcut
711 * @deprecated use {@link MainApplication#getRegisteredActionShortcut(Shortcut)} instead
712 * @since 5696
713 */
714 @Deprecated
715 public static Action getRegisteredActionShortcut(Shortcut shortcut) {
716 return MainApplication.getRegisteredActionShortcut(shortcut);
717 }
718
719 ///////////////////////////////////////////////////////////////////////////
720 // Implementation part
721 ///////////////////////////////////////////////////////////////////////////
722
723 /**
724 * Should be called before the main constructor to setup some parameter stuff
725 */
726 public static void preConstructorInit() {
727 // init default coordinate format
728 ICoordinateFormat fmt = CoordinateFormatManager.getCoordinateFormat(Config.getPref().get("coordinates"));
729 if (fmt == null) {
730 fmt = DecimalDegreesCoordinateFormat.INSTANCE;
731 }
732 CoordinateFormatManager.setCoordinateFormat(fmt);
733 }
734
735 /**
736 * Closes JOSM and optionally terminates the Java Virtual Machine (JVM).
737 * @param exit If {@code true}, the JVM is terminated by running {@link System#exit} with a given return code.
738 * @param exitCode The return code
739 * @return {@code true}
740 * @since 12636
741 */
742 public static boolean exitJosm(boolean exit, int exitCode) {
743 if (Main.main != null) {
744 Main.main.shutdown();
745 }
746
747 if (exit) {
748 System.exit(exitCode);
749 }
750 return true;
751 }
752
753 /**
754 * Shutdown JOSM.
755 */
756 protected void shutdown() {
757 if (!GraphicsEnvironment.isHeadless()) {
758 ImageProvider.shutdown(false);
759 }
760 try {
761 pref.saveDefaults();
762 } catch (IOException ex) {
763 Logging.log(Logging.LEVEL_WARN, tr("Failed to save default preferences."), ex);
764 }
765 if (!GraphicsEnvironment.isHeadless()) {
766 ImageProvider.shutdown(true);
767 }
768 }
769
770 /**
771 * Identifies the current operating system family and initializes the platform hook accordingly.
772 * @since 1849
773 */
774 public static void determinePlatformHook() {
775 platform = Platform.determinePlatform().accept(PlatformHook.CONSTRUCT_FROM_PLATFORM);
776 }
777
778 /* ----------------------------------------------------------------------------------------- */
779 /* projection handling - Main is a registry for a single, global projection instance */
780 /* */
781 /* TODO: For historical reasons the registry is implemented by Main. An alternative approach */
782 /* would be a singleton org.openstreetmap.josm.data.projection.ProjectionRegistry class. */
783 /* ----------------------------------------------------------------------------------------- */
784 /**
785 * The projection method used.
786 * Use {@link #getProjection()} and {@link #setProjection(Projection)} for access.
787 * Use {@link #setProjection(Projection)} in order to trigger a projection change event.
788 */
789 private static volatile Projection proj;
790
791 /**
792 * Replies the current projection.
793 *
794 * @return the currently active projection
795 */
796 public static Projection getProjection() {
797 return proj;
798 }
799
800 /**
801 * Sets the current projection
802 *
803 * @param p the projection
804 */
805 public static void setProjection(Projection p) {
806 CheckParameterUtil.ensureParameterNotNull(p);
807 Projection oldValue = proj;
808 Bounds b = main != null ? main.getRealBounds() : null;
809 proj = p;
810 fireProjectionChanged(oldValue, proj, b);
811 }
812
813 /**
814 * Returns the bounds for the current projection. Used for projection events.
815 * @return the bounds for the current projection
816 * @see #restoreOldBounds
817 */
818 protected Bounds getRealBounds() {
819 // To be overriden
820 return null;
821 }
822
823 /**
824 * Restore clean state corresponding to old bounds after a projection change event.
825 * @param oldBounds bounds previously returned by {@link #getRealBounds}, before the change of projection
826 * @see #getRealBounds
827 */
828 protected void restoreOldBounds(Bounds oldBounds) {
829 // To be overriden
830 }
831
832 /*
833 * Keep WeakReferences to the listeners. This relieves clients from the burden of
834 * explicitly removing the listeners and allows us to transparently register every
835 * created dataset as projection change listener.
836 */
837 private static final List<WeakReference<ProjectionChangeListener>> listeners = new ArrayList<>();
838
839 private static void fireProjectionChanged(Projection oldValue, Projection newValue, Bounds oldBounds) {
840 if ((newValue == null ^ oldValue == null)
841 || (newValue != null && oldValue != null && !Objects.equals(newValue.toCode(), oldValue.toCode()))) {
842 synchronized (Main.class) {
843 Iterator<WeakReference<ProjectionChangeListener>> it = listeners.iterator();
844 while (it.hasNext()) {
845 WeakReference<ProjectionChangeListener> wr = it.next();
846 ProjectionChangeListener listener = wr.get();
847 if (listener == null) {
848 it.remove();
849 continue;
850 }
851 listener.projectionChanged(oldValue, newValue);
852 }
853 }
854 if (newValue != null && oldBounds != null && main != null) {
855 main.restoreOldBounds(oldBounds);
856 }
857 /* TODO - remove layers with fixed projection */
858 }
859 }
860
861 /**
862 * Register a projection change listener.
863 * The listener is registered to be weak, so keep a reference of it if you want it to be preserved.
864 *
865 * @param listener the listener. Ignored if <code>null</code>.
866 */
867 public static void addProjectionChangeListener(ProjectionChangeListener listener) {
868 if (listener == null) return;
869 synchronized (Main.class) {
870 for (WeakReference<ProjectionChangeListener> wr : listeners) {
871 // already registered ? => abort
872 if (wr.get() == listener) return;
873 }
874 listeners.add(new WeakReference<>(listener));
875 }
876 }
877
878 /**
879 * Removes a projection change listener.
880 *
881 * @param listener the listener. Ignored if <code>null</code>.
882 */
883 public static void removeProjectionChangeListener(ProjectionChangeListener listener) {
884 if (listener == null) return;
885 synchronized (Main.class) {
886 // remove the listener - and any other listener which got garbage
887 // collected in the meantime
888 listeners.removeIf(wr -> wr.get() == null || wr.get() == listener);
889 }
890 }
891
892 /**
893 * Listener for window switch events.
894 *
895 * These are events, when the user activates a window of another application
896 * or comes back to JOSM. Window switches from one JOSM window to another
897 * are not reported.
898 */
899 public interface WindowSwitchListener {
900 /**
901 * Called when the user activates a window of another application.
902 */
903 void toOtherApplication();
904
905 /**
906 * Called when the user comes from a window of another application back to JOSM.
907 */
908 void fromOtherApplication();
909 }
910
911 /**
912 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes.
913 * <p>
914 * It will fire an initial mapFrameInitialized event when the MapFrame is present.
915 * Otherwise will only fire when the MapFrame is created or destroyed.
916 * @param listener The MapFrameListener
917 * @return {@code true} if the listeners collection changed as a result of the call
918 * @see #addMapFrameListener
919 * @deprecated use {@link MainApplication#addAndFireMapFrameListener} instead
920 * @since 11904
921 */
922 @Deprecated
923 public static boolean addAndFireMapFrameListener(MapFrameListener listener) {
924 return MainApplication.addAndFireMapFrameListener(listener);
925 }
926
927 /**
928 * Registers a new {@code MapFrameListener} that will be notified of MapFrame changes
929 * @param listener The MapFrameListener
930 * @return {@code true} if the listeners collection changed as a result of the call
931 * @see #addAndFireMapFrameListener
932 * @deprecated use {@link MainApplication#addMapFrameListener} instead
933 * @since 5957
934 */
935 @Deprecated
936 public static boolean addMapFrameListener(MapFrameListener listener) {
937 return MainApplication.addMapFrameListener(listener);
938 }
939
940 /**
941 * Unregisters the given {@code MapFrameListener} from MapFrame changes
942 * @param listener The MapFrameListener
943 * @return {@code true} if the listeners collection changed as a result of the call
944 * @deprecated use {@link MainApplication#removeMapFrameListener} instead
945 * @since 5957
946 */
947 @Deprecated
948 public static boolean removeMapFrameListener(MapFrameListener listener) {
949 return MainApplication.removeMapFrameListener(listener);
950 }
951
952 /**
953 * Adds a new network error that occur to give a hint about broken Internet connection.
954 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
955 *
956 * @param url The accessed URL that caused the error
957 * @param t The network error
958 * @return The previous error associated to the given resource, if any. Can be {@code null}
959 * @since 6642
960 */
961 public static Throwable addNetworkError(URL url, Throwable t) {
962 if (url != null && t != null) {
963 Throwable old = addNetworkError(url.toExternalForm(), t);
964 if (old != null) {
965 Logging.warn("Already here "+old);
966 }
967 return old;
968 }
969 return null;
970 }
971
972 /**
973 * Adds a new network error that occur to give a hint about broken Internet connection.
974 * Do not use this method for errors known for sure thrown because of a bad proxy configuration.
975 *
976 * @param url The accessed URL that caused the error
977 * @param t The network error
978 * @return The previous error associated to the given resource, if any. Can be {@code null}
979 * @since 6642
980 */
981 public static Throwable addNetworkError(String url, Throwable t) {
982 if (url != null && t != null) {
983 return NETWORK_ERRORS.put(url, t);
984 }
985 return null;
986 }
987
988 /**
989 * Returns the network errors that occured until now.
990 * @return the network errors that occured until now, indexed by URL
991 * @since 6639
992 */
993 public static Map<String, Throwable> getNetworkErrors() {
994 return new HashMap<>(NETWORK_ERRORS);
995 }
996
997 /**
998 * Clears the network errors cache.
999 * @since 12011
1000 */
1001 public static void clearNetworkErrors() {
1002 NETWORK_ERRORS.clear();
1003 }
1004
1005 /**
1006 * Returns the JOSM website URL.
1007 * @return the josm website URL
1008 * @since 6897
1009 */
1010 public static String getJOSMWebsite() {
1011 if (Config.getPref() != null)
1012 return Config.getPref().get("josm.url", JOSM_WEBSITE);
1013 return JOSM_WEBSITE;
1014 }
1015
1016 /**
1017 * Returns the JOSM XML URL.
1018 * @return the josm XML URL
1019 * @since 6897
1020 */
1021 public static String getXMLBase() {
1022 // Always return HTTP (issues reported with HTTPS)
1023 return "http://josm.openstreetmap.de";
1024 }
1025
1026 /**
1027 * Returns the OSM website URL.
1028 * @return the OSM website URL
1029 * @since 6897
1030 */
1031 public static String getOSMWebsite() {
1032 if (Config.getPref() != null)
1033 return Config.getPref().get("osm.url", OSM_WEBSITE);
1034 return OSM_WEBSITE;
1035 }
1036
1037 /**
1038 * Returns the OSM website URL depending on the selected {@link OsmApi}.
1039 * @return the OSM website URL depending on the selected {@link OsmApi}
1040 */
1041 private static String getOSMWebsiteDependingOnSelectedApi() {
1042 final String api = OsmApi.getOsmApi().getServerUrl();
1043 if (OsmApi.DEFAULT_API_URL.equals(api)) {
1044 return getOSMWebsite();
1045 } else {
1046 return api.replaceAll("/api$", "");
1047 }
1048 }
1049
1050 /**
1051 * Replies the base URL for browsing information about a primitive.
1052 * @return the base URL, i.e. https://www.openstreetmap.org
1053 * @since 7678
1054 */
1055 public static String getBaseBrowseUrl() {
1056 if (Config.getPref() != null)
1057 return Config.getPref().get("osm-browse.url", getOSMWebsiteDependingOnSelectedApi());
1058 return getOSMWebsiteDependingOnSelectedApi();
1059 }
1060
1061 /**
1062 * Replies the base URL for browsing information about a user.
1063 * @return the base URL, i.e. https://www.openstreetmap.org/user
1064 * @since 7678
1065 */
1066 public static String getBaseUserUrl() {
1067 if (Config.getPref() != null)
1068 return Config.getPref().get("osm-user.url", getOSMWebsiteDependingOnSelectedApi() + "/user");
1069 return getOSMWebsiteDependingOnSelectedApi() + "/user";
1070 }
1071
1072 /**
1073 * Determines if we are currently running on OSX.
1074 * @return {@code true} if we are currently running on OSX
1075 * @since 6957
1076 */
1077 public static boolean isPlatformOsx() {
1078 return Main.platform instanceof PlatformHookOsx;
1079 }
1080
1081 /**
1082 * Determines if we are currently running on Windows.
1083 * @return {@code true} if we are currently running on Windows
1084 * @since 7335
1085 */
1086 public static boolean isPlatformWindows() {
1087 return Main.platform instanceof PlatformHookWindows;
1088 }
1089
1090 /**
1091 * Determines if the given online resource is currently offline.
1092 * @param r the online resource
1093 * @return {@code true} if {@code r} is offline and should not be accessed
1094 * @since 7434
1095 */
1096 public static boolean isOffline(OnlineResource r) {
1097 return OFFLINE_RESOURCES.contains(r) || OFFLINE_RESOURCES.contains(OnlineResource.ALL);
1098 }
1099
1100 /**
1101 * Sets the given online resource to offline state.
1102 * @param r the online resource
1103 * @return {@code true} if {@code r} was not already offline
1104 * @since 7434
1105 */
1106 public static boolean setOffline(OnlineResource r) {
1107 return OFFLINE_RESOURCES.add(r);
1108 }
1109
1110 /**
1111 * Sets the given online resource to online state.
1112 * @param r the online resource
1113 * @return {@code true} if {@code r} was offline
1114 * @since 8506
1115 */
1116 public static boolean setOnline(OnlineResource r) {
1117 return OFFLINE_RESOURCES.remove(r);
1118 }
1119
1120 /**
1121 * Replies the set of online resources currently offline.
1122 * @return the set of online resources currently offline
1123 * @since 7434
1124 */
1125 public static Set<OnlineResource> getOfflineResources() {
1126 return EnumSet.copyOf(OFFLINE_RESOURCES);
1127 }
1128}
Note: See TracBrowser for help on using the repository browser.