source: josm/trunk/src/org/openstreetmap/josm/gui/preferences/PreferenceTabbedPane.java@ 10613

Last change on this file since 10613 was 10611, checked in by Don-vip, 8 years ago

see #11390 - sonar - squid:S1604 - Java 8: Anonymous inner classes containing only one method should become lambdas

  • Property svn:eol-style set to native
File size: 25.0 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.preferences;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Component;
7import java.awt.Font;
8import java.awt.GridBagLayout;
9import java.awt.event.MouseWheelEvent;
10import java.awt.event.MouseWheelListener;
11import java.util.ArrayList;
12import java.util.Collection;
13import java.util.HashSet;
14import java.util.Iterator;
15import java.util.LinkedList;
16import java.util.List;
17import java.util.Set;
18
19import javax.swing.BorderFactory;
20import javax.swing.Icon;
21import javax.swing.ImageIcon;
22import javax.swing.JLabel;
23import javax.swing.JOptionPane;
24import javax.swing.JPanel;
25import javax.swing.JScrollPane;
26import javax.swing.JTabbedPane;
27import javax.swing.SwingUtilities;
28import javax.swing.event.ChangeEvent;
29import javax.swing.event.ChangeListener;
30
31import org.openstreetmap.josm.Main;
32import org.openstreetmap.josm.actions.ExpertToggleAction;
33import org.openstreetmap.josm.actions.ExpertToggleAction.ExpertModeChangeListener;
34import org.openstreetmap.josm.actions.RestartAction;
35import org.openstreetmap.josm.gui.HelpAwareOptionPane;
36import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
37import org.openstreetmap.josm.gui.preferences.advanced.AdvancedPreference;
38import org.openstreetmap.josm.gui.preferences.audio.AudioPreference;
39import org.openstreetmap.josm.gui.preferences.display.ColorPreference;
40import org.openstreetmap.josm.gui.preferences.display.DisplayPreference;
41import org.openstreetmap.josm.gui.preferences.display.DrawingPreference;
42import org.openstreetmap.josm.gui.preferences.display.LafPreference;
43import org.openstreetmap.josm.gui.preferences.display.LanguagePreference;
44import org.openstreetmap.josm.gui.preferences.imagery.ImageryPreference;
45import org.openstreetmap.josm.gui.preferences.map.BackupPreference;
46import org.openstreetmap.josm.gui.preferences.map.MapPaintPreference;
47import org.openstreetmap.josm.gui.preferences.map.MapPreference;
48import org.openstreetmap.josm.gui.preferences.map.TaggingPresetPreference;
49import org.openstreetmap.josm.gui.preferences.plugin.PluginPreference;
50import org.openstreetmap.josm.gui.preferences.projection.ProjectionPreference;
51import org.openstreetmap.josm.gui.preferences.remotecontrol.RemoteControlPreference;
52import org.openstreetmap.josm.gui.preferences.server.AuthenticationPreference;
53import org.openstreetmap.josm.gui.preferences.server.OverpassServerPreference;
54import org.openstreetmap.josm.gui.preferences.server.ProxyPreference;
55import org.openstreetmap.josm.gui.preferences.server.ServerAccessPreference;
56import org.openstreetmap.josm.gui.preferences.shortcut.ShortcutPreference;
57import org.openstreetmap.josm.gui.preferences.validator.ValidatorPreference;
58import org.openstreetmap.josm.gui.preferences.validator.ValidatorTagCheckerRulesPreference;
59import org.openstreetmap.josm.gui.preferences.validator.ValidatorTestsPreference;
60import org.openstreetmap.josm.plugins.PluginDownloadTask;
61import org.openstreetmap.josm.plugins.PluginHandler;
62import org.openstreetmap.josm.plugins.PluginInformation;
63import org.openstreetmap.josm.plugins.PluginProxy;
64import org.openstreetmap.josm.tools.CheckParameterUtil;
65import org.openstreetmap.josm.tools.GBC;
66import org.openstreetmap.josm.tools.ImageProvider;
67import org.openstreetmap.josm.tools.bugreport.BugReportExceptionHandler;
68
69/**
70 * The preference settings.
71 *
72 * @author imi
73 */
74public final class PreferenceTabbedPane extends JTabbedPane implements MouseWheelListener, ExpertModeChangeListener, ChangeListener {
75
76 private final class PluginDownloadAfterTask implements Runnable {
77 private final PluginPreference preference;
78 private final PluginDownloadTask task;
79 private final Set<PluginInformation> toDownload;
80
81 private PluginDownloadAfterTask(PluginPreference preference, PluginDownloadTask task,
82 Set<PluginInformation> toDownload) {
83 this.preference = preference;
84 this.task = task;
85 this.toDownload = toDownload;
86 }
87
88 @Override
89 public void run() {
90 boolean requiresRestart = false;
91
92 for (PreferenceSetting setting : settingsInitialized) {
93 if (setting.ok()) {
94 requiresRestart = true;
95 }
96 }
97
98 // build the messages. We only display one message, including the status information from the plugin download task
99 // and - if necessary - a hint to restart JOSM
100 //
101 StringBuilder sb = new StringBuilder();
102 sb.append("<html>");
103 if (task != null && !task.isCanceled()) {
104 PluginHandler.refreshLocalUpdatedPluginInfo(task.getDownloadedPlugins());
105 sb.append(PluginPreference.buildDownloadSummary(task));
106 }
107 if (requiresRestart) {
108 sb.append(tr("You have to restart JOSM for some settings to take effect."));
109 sb.append("<br/><br/>");
110 sb.append(tr("Would you like to restart now?"));
111 }
112 sb.append("</html>");
113
114 // display the message, if necessary
115 //
116 if (requiresRestart) {
117 final ButtonSpec[] options = RestartAction.getButtonSpecs();
118 if (0 == HelpAwareOptionPane.showOptionDialog(
119 Main.parent,
120 sb.toString(),
121 tr("Restart"),
122 JOptionPane.INFORMATION_MESSAGE,
123 null, /* no special icon */
124 options,
125 options[0],
126 null /* no special help */
127 )) {
128 Main.main.menu.restart.actionPerformed(null);
129 }
130 } else if (task != null && !task.isCanceled()) {
131 JOptionPane.showMessageDialog(
132 Main.parent,
133 sb.toString(),
134 tr("Warning"),
135 JOptionPane.WARNING_MESSAGE
136 );
137 }
138
139 // load the plugins that can be loaded at runtime
140 List<PluginInformation> newPlugins = preference.getNewlyActivatedPlugins();
141 if (newPlugins != null) {
142 Collection<PluginInformation> downloadedPlugins = null;
143 if (task != null && !task.isCanceled()) {
144 downloadedPlugins = task.getDownloadedPlugins();
145 }
146 List<PluginInformation> toLoad = new ArrayList<>();
147 for (PluginInformation pi : newPlugins) {
148 if (toDownload.contains(pi) && downloadedPlugins != null && !downloadedPlugins.contains(pi)) {
149 continue; // failed download
150 }
151 if (pi.canloadatruntime) {
152 toLoad.add(pi);
153 }
154 }
155 // check if plugin dependences can also be loaded
156 Collection<PluginInformation> allPlugins = new HashSet<>(toLoad);
157 for (PluginProxy proxy : PluginHandler.pluginList) {
158 allPlugins.add(proxy.getPluginInformation());
159 }
160 boolean removed;
161 do {
162 removed = false;
163 Iterator<PluginInformation> it = toLoad.iterator();
164 while (it.hasNext()) {
165 if (!PluginHandler.checkRequiredPluginsPreconditions(null, allPlugins, it.next(), requiresRestart)) {
166 it.remove();
167 removed = true;
168 }
169 }
170 } while (removed);
171
172 if (!toLoad.isEmpty()) {
173 PluginHandler.loadPlugins(PreferenceTabbedPane.this, toLoad, null);
174 }
175 }
176
177 Main.parent.repaint();
178 }
179 }
180
181 /**
182 * Allows PreferenceSettings to do validation of entered values when ok was pressed.
183 * If data is invalid then event can return false to cancel closing of preferences dialog.
184 * @since 10600 (functional interface)
185 */
186 @FunctionalInterface
187 public interface ValidationListener {
188 /**
189 *
190 * @return True if preferences can be saved
191 */
192 boolean validatePreferences();
193 }
194
195 private interface PreferenceTab {
196 TabPreferenceSetting getTabPreferenceSetting();
197
198 Component getComponent();
199 }
200
201 public static final class PreferencePanel extends JPanel implements PreferenceTab {
202 private final transient TabPreferenceSetting preferenceSetting;
203
204 private PreferencePanel(TabPreferenceSetting preferenceSetting) {
205 super(new GridBagLayout());
206 CheckParameterUtil.ensureParameterNotNull(preferenceSetting);
207 this.preferenceSetting = preferenceSetting;
208 buildPanel();
209 }
210
211 protected void buildPanel() {
212 setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
213 add(new JLabel(preferenceSetting.getTitle()), GBC.eol().insets(0, 5, 0, 10).anchor(GBC.NORTHWEST));
214
215 JLabel descLabel = new JLabel("<html>"+preferenceSetting.getDescription()+"</html>");
216 descLabel.setFont(descLabel.getFont().deriveFont(Font.ITALIC));
217 add(descLabel, GBC.eol().insets(5, 0, 5, 20).fill(GBC.HORIZONTAL));
218 }
219
220 @Override
221 public TabPreferenceSetting getTabPreferenceSetting() {
222 return preferenceSetting;
223 }
224
225 @Override
226 public Component getComponent() {
227 return this;
228 }
229 }
230
231 public static final class PreferenceScrollPane extends JScrollPane implements PreferenceTab {
232 private final transient TabPreferenceSetting preferenceSetting;
233
234 private PreferenceScrollPane(Component view, TabPreferenceSetting preferenceSetting) {
235 super(view);
236 this.preferenceSetting = preferenceSetting;
237 }
238
239 private PreferenceScrollPane(PreferencePanel preferencePanel) {
240 this(preferencePanel.getComponent(), preferencePanel.getTabPreferenceSetting());
241 }
242
243 @Override
244 public TabPreferenceSetting getTabPreferenceSetting() {
245 return preferenceSetting;
246 }
247
248 @Override
249 public Component getComponent() {
250 return this;
251 }
252 }
253
254 // all created tabs
255 private final transient List<PreferenceTab> tabs = new ArrayList<>();
256 private static final Collection<PreferenceSettingFactory> settingsFactories = new LinkedList<>();
257 private static final PreferenceSettingFactory advancedPreferenceFactory = new AdvancedPreference.Factory();
258 private final transient List<PreferenceSetting> settings = new ArrayList<>();
259
260 // distinct list of tabs that have been initialized (we do not initialize tabs until they are displayed to speed up dialog startup)
261 private final transient List<PreferenceSetting> settingsInitialized = new ArrayList<>();
262
263 final transient List<ValidationListener> validationListeners = new ArrayList<>();
264
265 /**
266 * Add validation listener to currently open preferences dialog. Calling to removeValidationListener is not necessary, all listeners will
267 * be automatically removed when dialog is closed
268 * @param validationListener validation listener to add
269 */
270 public void addValidationListener(ValidationListener validationListener) {
271 validationListeners.add(validationListener);
272 }
273
274 /**
275 * Construct a PreferencePanel for the preference settings. Layout is GridBagLayout
276 * and a centered title label and the description are added.
277 * @param caller Preference settings, that display a top level tab
278 * @return The created panel ready to add other controls.
279 */
280 public PreferencePanel createPreferenceTab(TabPreferenceSetting caller) {
281 return createPreferenceTab(caller, false);
282 }
283
284 /**
285 * Construct a PreferencePanel for the preference settings. Layout is GridBagLayout
286 * and a centered title label and the description are added.
287 * @param caller Preference settings, that display a top level tab
288 * @param inScrollPane if <code>true</code> the added tab will show scroll bars
289 * if the panel content is larger than the available space
290 * @return The created panel ready to add other controls.
291 */
292 public PreferencePanel createPreferenceTab(TabPreferenceSetting caller, boolean inScrollPane) {
293 CheckParameterUtil.ensureParameterNotNull(caller, "caller");
294 PreferencePanel p = new PreferencePanel(caller);
295
296 PreferenceTab tab = p;
297 if (inScrollPane) {
298 PreferenceScrollPane sp = new PreferenceScrollPane(p);
299 tab = sp;
300 }
301 tabs.add(tab);
302 return p;
303 }
304
305 @FunctionalInterface
306 private interface TabIdentifier {
307 boolean identify(TabPreferenceSetting tps, Object param);
308 }
309
310 private void selectTabBy(TabIdentifier method, Object param) {
311 for (int i = 0; i < getTabCount(); i++) {
312 Component c = getComponentAt(i);
313 if (c instanceof PreferenceTab) {
314 PreferenceTab tab = (PreferenceTab) c;
315 if (method.identify(tab.getTabPreferenceSetting(), param)) {
316 setSelectedIndex(i);
317 return;
318 }
319 }
320 }
321 }
322
323 public void selectTabByName(String name) {
324 selectTabBy((tps, name1) -> name1 != null && tps != null && tps.getIconName() != null && name1.equals(tps.getIconName()), name);
325 }
326
327 public void selectTabByPref(Class<? extends TabPreferenceSetting> clazz) {
328 selectTabBy((tps, clazz1) -> tps.getClass().isAssignableFrom((Class<?>) clazz1), clazz);
329 }
330
331 public boolean selectSubTabByPref(Class<? extends SubPreferenceSetting> clazz) {
332 for (PreferenceSetting setting : settings) {
333 if (clazz.isInstance(setting)) {
334 final SubPreferenceSetting sub = (SubPreferenceSetting) setting;
335 final TabPreferenceSetting tab = sub.getTabPreferenceSetting(this);
336 selectTabBy((tps, unused) -> tps.equals(tab), null);
337 return tab.selectSubTab(sub);
338 }
339 }
340 return false;
341 }
342
343 /**
344 * Returns the {@code DisplayPreference} object.
345 * @return the {@code DisplayPreference} object.
346 */
347 public DisplayPreference getDisplayPreference() {
348 return getSetting(DisplayPreference.class);
349 }
350
351 /**
352 * Returns the {@code MapPreference} object.
353 * @return the {@code MapPreference} object.
354 */
355 public MapPreference getMapPreference() {
356 return getSetting(MapPreference.class);
357 }
358
359 /**
360 * Returns the {@code PluginPreference} object.
361 * @return the {@code PluginPreference} object.
362 */
363 public PluginPreference getPluginPreference() {
364 return getSetting(PluginPreference.class);
365 }
366
367 /**
368 * Returns the {@code ImageryPreference} object.
369 * @return the {@code ImageryPreference} object.
370 */
371 public ImageryPreference getImageryPreference() {
372 return getSetting(ImageryPreference.class);
373 }
374
375 /**
376 * Returns the {@code ShortcutPreference} object.
377 * @return the {@code ShortcutPreference} object.
378 */
379 public ShortcutPreference getShortcutPreference() {
380 return getSetting(ShortcutPreference.class);
381 }
382
383 /**
384 * Returns the {@code ServerAccessPreference} object.
385 * @return the {@code ServerAccessPreference} object.
386 * @since 6523
387 */
388 public ServerAccessPreference getServerPreference() {
389 return getSetting(ServerAccessPreference.class);
390 }
391
392 /**
393 * Returns the {@code ValidatorPreference} object.
394 * @return the {@code ValidatorPreference} object.
395 * @since 6665
396 */
397 public ValidatorPreference getValidatorPreference() {
398 return getSetting(ValidatorPreference.class);
399 }
400
401 /**
402 * Saves preferences.
403 */
404 public void savePreferences() {
405 // create a task for downloading plugins if the user has activated, yet not downloaded, new plugins
406 final PluginPreference preference = getPluginPreference();
407 final Set<PluginInformation> toDownload = preference.getPluginsScheduledForUpdateOrDownload();
408 final PluginDownloadTask task;
409 if (toDownload != null && !toDownload.isEmpty()) {
410 task = new PluginDownloadTask(this, toDownload, tr("Download plugins"));
411 } else {
412 task = null;
413 }
414
415 // this is the task which will run *after* the plugins are downloaded
416 final Runnable continuation = new PluginDownloadAfterTask(preference, task, toDownload);
417
418 if (task != null) {
419 // if we have to launch a plugin download task we do it asynchronously, followed
420 // by the remaining "save preferences" activites run on the Swing EDT.
421 Main.worker.submit(task);
422 Main.worker.submit(() -> SwingUtilities.invokeLater(continuation));
423 } else {
424 // no need for asynchronous activities. Simply run the remaining "save preference"
425 // activities on this thread (we are already on the Swing EDT
426 continuation.run();
427 }
428 }
429
430 /**
431 * If the dialog is closed with Ok, the preferences will be stored to the preferences-
432 * file, otherwise no change of the file happens.
433 */
434 public PreferenceTabbedPane() {
435 super(JTabbedPane.LEFT, JTabbedPane.SCROLL_TAB_LAYOUT);
436 super.addMouseWheelListener(this);
437 super.getModel().addChangeListener(this);
438 ExpertToggleAction.addExpertModeChangeListener(this);
439 }
440
441 public void buildGui() {
442 Collection<PreferenceSettingFactory> factories = new ArrayList<>(settingsFactories);
443 factories.addAll(PluginHandler.getPreferenceSetting());
444 factories.add(advancedPreferenceFactory);
445
446 for (PreferenceSettingFactory factory : factories) {
447 if (factory != null) {
448 PreferenceSetting setting = factory.createPreferenceSetting();
449 if (setting != null) {
450 settings.add(setting);
451 }
452 }
453 }
454 addGUITabs(false);
455 }
456
457 private void addGUITabsForSetting(Icon icon, TabPreferenceSetting tps) {
458 for (PreferenceTab tab : tabs) {
459 if (tab.getTabPreferenceSetting().equals(tps)) {
460 insertGUITabsForSetting(icon, tps, getTabCount());
461 }
462 }
463 }
464
465 private void insertGUITabsForSetting(Icon icon, TabPreferenceSetting tps, int index) {
466 int position = index;
467 for (PreferenceTab tab : tabs) {
468 if (tab.getTabPreferenceSetting().equals(tps)) {
469 insertTab(null, icon, tab.getComponent(), tps.getTooltip(), position++);
470 }
471 }
472 }
473
474 private void addGUITabs(boolean clear) {
475 boolean expert = ExpertToggleAction.isExpert();
476 Component sel = getSelectedComponent();
477 if (clear) {
478 removeAll();
479 }
480 // Inspect each tab setting
481 for (PreferenceSetting setting : settings) {
482 if (setting instanceof TabPreferenceSetting) {
483 TabPreferenceSetting tps = (TabPreferenceSetting) setting;
484 if (expert || !tps.isExpert()) {
485 // Get icon
486 String iconName = tps.getIconName();
487 ImageIcon icon = null;
488
489 if (iconName != null && !iconName.isEmpty()) {
490 icon = ImageProvider.get("preferences", iconName, ImageProvider.ImageSizes.SETTINGS_TAB);
491 }
492 if (settingsInitialized.contains(tps)) {
493 // If it has been initialized, add corresponding tab(s)
494 addGUITabsForSetting(icon, tps);
495 } else {
496 // If it has not been initialized, create an empty tab with only icon and tooltip
497 addTab(null, icon, new PreferencePanel(tps), tps.getTooltip());
498 }
499 }
500 } else if (!(setting instanceof SubPreferenceSetting)) {
501 Main.warn("Ignoring preferences "+setting);
502 }
503 }
504 try {
505 if (sel != null) {
506 setSelectedComponent(sel);
507 }
508 } catch (IllegalArgumentException e) {
509 Main.warn(e);
510 }
511 }
512
513 @Override
514 public void expertChanged(boolean isExpert) {
515 addGUITabs(true);
516 }
517
518 public List<PreferenceSetting> getSettings() {
519 return settings;
520 }
521
522 @SuppressWarnings("unchecked")
523 public <T> T getSetting(Class<? extends T> clazz) {
524 for (PreferenceSetting setting:settings) {
525 if (clazz.isAssignableFrom(setting.getClass()))
526 return (T) setting;
527 }
528 return null;
529 }
530
531 static {
532 // order is important!
533 settingsFactories.add(new DisplayPreference.Factory());
534 settingsFactories.add(new DrawingPreference.Factory());
535 settingsFactories.add(new ColorPreference.Factory());
536 settingsFactories.add(new LafPreference.Factory());
537 settingsFactories.add(new LanguagePreference.Factory());
538 settingsFactories.add(new ServerAccessPreference.Factory());
539 settingsFactories.add(new AuthenticationPreference.Factory());
540 settingsFactories.add(new ProxyPreference.Factory());
541 settingsFactories.add(new OverpassServerPreference.Factory());
542 settingsFactories.add(new MapPreference.Factory());
543 settingsFactories.add(new ProjectionPreference.Factory());
544 settingsFactories.add(new MapPaintPreference.Factory());
545 settingsFactories.add(new TaggingPresetPreference.Factory());
546 settingsFactories.add(new BackupPreference.Factory());
547 settingsFactories.add(new PluginPreference.Factory());
548 settingsFactories.add(Main.toolbar);
549 settingsFactories.add(new AudioPreference.Factory());
550 settingsFactories.add(new ShortcutPreference.Factory());
551 settingsFactories.add(new ValidatorPreference.Factory());
552 settingsFactories.add(new ValidatorTestsPreference.Factory());
553 settingsFactories.add(new ValidatorTagCheckerRulesPreference.Factory());
554 settingsFactories.add(new RemoteControlPreference.Factory());
555 settingsFactories.add(new ImageryPreference.Factory());
556 }
557
558 /**
559 * This mouse wheel listener reacts when a scroll is carried out over the
560 * tab strip and scrolls one tab/down or up, selecting it immediately.
561 */
562 @Override
563 public void mouseWheelMoved(MouseWheelEvent wev) {
564 // Ensure the cursor is over the tab strip
565 if (super.indexAtLocation(wev.getPoint().x, wev.getPoint().y) < 0)
566 return;
567
568 // Get currently selected tab
569 int newTab = super.getSelectedIndex() + wev.getWheelRotation();
570
571 // Ensure the new tab index is sound
572 newTab = newTab < 0 ? 0 : newTab;
573 newTab = newTab >= super.getTabCount() ? super.getTabCount() - 1 : newTab;
574
575 // select new tab
576 super.setSelectedIndex(newTab);
577 }
578
579 @Override
580 public void stateChanged(ChangeEvent e) {
581 int index = getSelectedIndex();
582 Component sel = getSelectedComponent();
583 if (index > -1 && sel instanceof PreferenceTab) {
584 PreferenceTab tab = (PreferenceTab) sel;
585 TabPreferenceSetting preferenceSettings = tab.getTabPreferenceSetting();
586 if (!settingsInitialized.contains(preferenceSettings)) {
587 try {
588 getModel().removeChangeListener(this);
589 preferenceSettings.addGui(this);
590 // Add GUI for sub preferences
591 for (PreferenceSetting setting : settings) {
592 if (setting instanceof SubPreferenceSetting) {
593 SubPreferenceSetting sps = (SubPreferenceSetting) setting;
594 if (sps.getTabPreferenceSetting(this) == preferenceSettings) {
595 try {
596 sps.addGui(this);
597 } catch (SecurityException ex) {
598 Main.error(ex);
599 } catch (RuntimeException ex) {
600 BugReportExceptionHandler.handleException(ex);
601 } finally {
602 settingsInitialized.add(sps);
603 }
604 }
605 }
606 }
607 Icon icon = getIconAt(index);
608 remove(index);
609 insertGUITabsForSetting(icon, preferenceSettings, index);
610 setSelectedIndex(index);
611 } catch (SecurityException ex) {
612 Main.error(ex);
613 } catch (RuntimeException ex) {
614 // allow to change most settings even if e.g. a plugin fails
615 BugReportExceptionHandler.handleException(ex);
616 } finally {
617 settingsInitialized.add(preferenceSettings);
618 getModel().addChangeListener(this);
619 }
620 }
621 }
622 }
623}
Note: See TracBrowser for help on using the repository browser.