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

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

fix #8667 - NPE with plugins returning invalid preferences (scripting)

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