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

Last change on this file since 6070 was 6070, checked in by stoecker, 11 years ago

see #8853 remove tabs, trailing spaces, windows line ends, strange characters

  • Property svn:eol-style set to native
File size: 21.2 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 name != null && tps != null && tps.getIconName() != 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 final ShortcutPreference getShortcutPreference() {
248 return getSetting(ShortcutPreference.class);
249 }
250
251 public void savePreferences() {
252 if(Main.applet)
253 return;
254 // create a task for downloading plugins if the user has activated, yet not downloaded,
255 // new plugins
256 //
257 final PluginPreference preference = getPluginPreference();
258 final List<PluginInformation> toDownload = preference.getPluginsScheduledForUpdateOrDownload();
259 final PluginDownloadTask task;
260 if (toDownload != null && ! toDownload.isEmpty()) {
261 task = new PluginDownloadTask(this, toDownload, tr("Download plugins"));
262 } else {
263 task = null;
264 }
265
266 // this is the task which will run *after* the plugins are downloaded
267 //
268 final Runnable continuation = new Runnable() {
269 public void run() {
270 boolean requiresRestart = false;
271 if (task != null && !task.isCanceled()) {
272 if (!task.getDownloadedPlugins().isEmpty()) {
273 requiresRestart = true;
274 }
275 }
276
277 for (PreferenceSetting setting : settingsInitialized) {
278 if (setting.ok()) {
279 requiresRestart = true;
280 }
281 }
282
283 // build the messages. We only display one message, including the status
284 // information from the plugin download task and - if necessary - a hint
285 // to restart JOSM
286 //
287 StringBuilder sb = new StringBuilder();
288 sb.append("<html>");
289 if (task != null && !task.isCanceled()) {
290 sb.append(PluginPreference.buildDownloadSummary(task));
291 }
292 if (requiresRestart) {
293 sb.append(tr("You have to restart JOSM for some settings to take effect."));
294 sb.append("<br/><br/>");
295 sb.append(tr("Would you like to restart now?"));
296 }
297 sb.append("</html>");
298
299 // display the message, if necessary
300 //
301 if (requiresRestart) {
302 final ButtonSpec [] options = RestartAction.getButtonSpecs();
303 if (0 == HelpAwareOptionPane.showOptionDialog(
304 Main.parent,
305 sb.toString(),
306 tr("Restart"),
307 JOptionPane.INFORMATION_MESSAGE,
308 null, /* no special icon */
309 options,
310 options[0],
311 null /* no special help */
312 )) {
313 Main.main.menu.restart.actionPerformed(null);
314 }
315 } else if (task != null && !task.isCanceled()) {
316 JOptionPane.showMessageDialog(
317 Main.parent,
318 sb.toString(),
319 tr("Warning"),
320 JOptionPane.WARNING_MESSAGE
321 );
322 }
323 Main.parent.repaint();
324 }
325 };
326
327 if (task != null) {
328 // if we have to launch a plugin download task we do it asynchronously, followed
329 // by the remaining "save preferences" activites run on the Swing EDT.
330 //
331 Main.worker.submit(task);
332 Main.worker.submit(
333 new Runnable() {
334 public void run() {
335 SwingUtilities.invokeLater(continuation);
336 }
337 }
338 );
339 } else {
340 // no need for asynchronous activities. Simply run the remaining "save preference"
341 // activities on this thread (we are already on the Swing EDT
342 //
343 continuation.run();
344 }
345 }
346
347 /**
348 * If the dialog is closed with Ok, the preferences will be stored to the preferences-
349 * file, otherwise no change of the file happens.
350 */
351 public PreferenceTabbedPane() {
352 super(JTabbedPane.LEFT, JTabbedPane.SCROLL_TAB_LAYOUT);
353 super.addMouseWheelListener(this);
354 super.getModel().addChangeListener(this);
355 ExpertToggleAction.addExpertModeChangeListener(this);
356 }
357
358 public void buildGui() {
359 for (PreferenceSettingFactory factory : settingsFactory) {
360 PreferenceSetting setting = factory.createPreferenceSetting();
361 if (setting != null) {
362 settings.add(setting);
363 }
364 }
365 addGUITabs(false);
366 }
367
368 private void addGUITabsForSetting(Icon icon, TabPreferenceSetting tps) {
369 for (PreferenceTab tab : tabs) {
370 if (tab.getTabPreferenceSetting().equals(tps)) {
371 insertGUITabsForSetting(icon, tps, getTabCount());
372 }
373 }
374 }
375
376 private void insertGUITabsForSetting(Icon icon, TabPreferenceSetting tps, int index) {
377 int position = index;
378 for (PreferenceTab tab : tabs) {
379 if (tab.getTabPreferenceSetting().equals(tps)) {
380 insertTab(null, icon, tab.getComponent(), tps.getTooltip(), position++);
381 }
382 }
383 }
384
385 private void addGUITabs(boolean clear) {
386 boolean expert = ExpertToggleAction.isExpert();
387 Component sel = getSelectedComponent();
388 if (clear) {
389 removeAll();
390 }
391 // Inspect each tab setting
392 for (PreferenceSetting setting : settings) {
393 if (setting instanceof TabPreferenceSetting) {
394 TabPreferenceSetting tps = (TabPreferenceSetting) setting;
395 if (expert || !tps.isExpert()) {
396 // Get icon
397 String iconName = tps.getIconName();
398 ImageIcon icon = iconName != null && iconName.length() > 0 ? ImageProvider.get("preferences", iconName) : null;
399 // See #6985 - Force icons to be 48x48 pixels
400 if (icon != null && (icon.getIconHeight() != 48 || icon.getIconWidth() != 48)) {
401 icon = new ImageIcon(icon.getImage().getScaledInstance(48, 48, Image.SCALE_DEFAULT));
402 }
403 if (settingsInitialized.contains(tps)) {
404 // If it has been initialized, add corresponding tab(s)
405 addGUITabsForSetting(icon, tps);
406 } else {
407 // If it has not been initialized, create an empty tab with only icon and tooltip
408 addTab(null, icon, new PreferencePanel(tps), tps.getTooltip());
409 }
410 }
411 } else if (!(setting instanceof SubPreferenceSetting)) {
412 Main.warn("Ignoring preferences "+setting);
413 }
414 }
415 try {
416 if (sel != null) {
417 setSelectedComponent(sel);
418 }
419 } catch (IllegalArgumentException e) {}
420 }
421
422 @Override
423 public void expertChanged(boolean isExpert) {
424 addGUITabs(true);
425 }
426
427 public List<PreferenceSetting> getSettings() {
428 return settings;
429 }
430
431 @SuppressWarnings("unchecked")
432 public <T> T getSetting(Class<? extends T> clazz) {
433 for (PreferenceSetting setting:settings) {
434 if (clazz.isAssignableFrom(setting.getClass()))
435 return (T)setting;
436 }
437 return null;
438 }
439
440 static {
441 // order is important!
442 settingsFactory.add(new DisplayPreference.Factory());
443 settingsFactory.add(new DrawingPreference.Factory());
444 settingsFactory.add(new ColorPreference.Factory());
445 settingsFactory.add(new LafPreference.Factory());
446 settingsFactory.add(new LanguagePreference.Factory());
447 settingsFactory.add(new ServerAccessPreference.Factory());
448 settingsFactory.add(new MapPreference.Factory());
449 settingsFactory.add(new ProjectionPreference.Factory());
450 settingsFactory.add(new MapPaintPreference.Factory());
451 settingsFactory.add(new TaggingPresetPreference.Factory());
452 settingsFactory.add(new BackupPreference.Factory());
453 if(!Main.applet) {
454 settingsFactory.add(new PluginPreference.Factory());
455 }
456 settingsFactory.add(Main.toolbar);
457 settingsFactory.add(new AudioPreference.Factory());
458 settingsFactory.add(new ShortcutPreference.Factory());
459 settingsFactory.add(new ValidatorPreference.Factory());
460 settingsFactory.add(new RemoteControlPreference.Factory());
461 settingsFactory.add(new ImageryPreference.Factory());
462
463 PluginHandler.getPreferenceSetting(settingsFactory);
464
465 // always the last: advanced tab
466 settingsFactory.add(new AdvancedPreference.Factory());
467 }
468
469 /**
470 * This mouse wheel listener reacts when a scroll is carried out over the
471 * tab strip and scrolls one tab/down or up, selecting it immediately.
472 */
473 public void mouseWheelMoved(MouseWheelEvent wev) {
474 // Ensure the cursor is over the tab strip
475 if(super.indexAtLocation(wev.getPoint().x, wev.getPoint().y) < 0)
476 return;
477
478 // Get currently selected tab
479 int newTab = super.getSelectedIndex() + wev.getWheelRotation();
480
481 // Ensure the new tab index is sound
482 newTab = newTab < 0 ? 0 : newTab;
483 newTab = newTab >= super.getTabCount() ? super.getTabCount() - 1 : newTab;
484
485 // select new tab
486 super.setSelectedIndex(newTab);
487 }
488
489 @Override
490 public void stateChanged(ChangeEvent e) {
491 int index = getSelectedIndex();
492 Component sel = getSelectedComponent();
493 if (index > -1 && sel instanceof PreferenceTab) {
494 PreferenceTab tab = (PreferenceTab) sel;
495 TabPreferenceSetting preferenceSettings = tab.getTabPreferenceSetting();
496 if (!settingsInitialized.contains(preferenceSettings)) {
497 try {
498 getModel().removeChangeListener(this);
499 preferenceSettings.addGui(this);
500 // Add GUI for sub preferences
501 for (PreferenceSetting setting : settings) {
502 if (setting instanceof SubPreferenceSetting) {
503 SubPreferenceSetting sps = (SubPreferenceSetting) setting;
504 if (sps.getTabPreferenceSetting(this) == preferenceSettings) {
505 try {
506 sps.addGui(this);
507 } catch (SecurityException ex) {
508 ex.printStackTrace();
509 } catch (Throwable ex) {
510 BugReportExceptionHandler.handleException(ex);
511 } finally {
512 settingsInitialized.add(sps);
513 }
514 }
515 }
516 }
517 Icon icon = getIconAt(index);
518 remove(index);
519 insertGUITabsForSetting(icon, preferenceSettings, index);
520 setSelectedIndex(index);
521 } catch (SecurityException ex) {
522 ex.printStackTrace();
523 } catch (Throwable ex) {
524 // allow to change most settings even if e.g. a plugin fails
525 BugReportExceptionHandler.handleException(ex);
526 } finally {
527 settingsInitialized.add(preferenceSettings);
528 getModel().addChangeListener(this);
529 }
530 }
531 }
532 }
533}
Note: See TracBrowser for help on using the repository browser.