source: josm/trunk/src/org/openstreetmap/josm/gui/preferences/advanced/AdvancedPreference.java@ 12856

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

see #15229 - add parameter to base directory methods

  • Property svn:eol-style set to native
File size: 17.2 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.preferences.advanced;
3
4import static org.openstreetmap.josm.tools.I18n.marktr;
5import static org.openstreetmap.josm.tools.I18n.tr;
6
7import java.awt.Dimension;
8import java.awt.event.ActionEvent;
9import java.awt.event.ActionListener;
10import java.io.File;
11import java.io.IOException;
12import java.util.ArrayList;
13import java.util.Collections;
14import java.util.Comparator;
15import java.util.LinkedHashMap;
16import java.util.List;
17import java.util.Locale;
18import java.util.Map;
19import java.util.Map.Entry;
20import java.util.Objects;
21
22import javax.swing.AbstractAction;
23import javax.swing.Box;
24import javax.swing.JButton;
25import javax.swing.JFileChooser;
26import javax.swing.JLabel;
27import javax.swing.JMenu;
28import javax.swing.JOptionPane;
29import javax.swing.JPanel;
30import javax.swing.JPopupMenu;
31import javax.swing.JScrollPane;
32import javax.swing.event.DocumentEvent;
33import javax.swing.event.DocumentListener;
34import javax.swing.event.MenuEvent;
35import javax.swing.event.MenuListener;
36import javax.swing.filechooser.FileFilter;
37
38import org.openstreetmap.josm.Main;
39import org.openstreetmap.josm.actions.DiskAccessAction;
40import org.openstreetmap.josm.data.Preferences;
41import org.openstreetmap.josm.data.PreferencesUtils;
42import org.openstreetmap.josm.data.preferences.Setting;
43import org.openstreetmap.josm.data.preferences.StringSetting;
44import org.openstreetmap.josm.gui.dialogs.LogShowDialog;
45import org.openstreetmap.josm.gui.io.CustomConfigurator;
46import org.openstreetmap.josm.gui.preferences.DefaultTabPreferenceSetting;
47import org.openstreetmap.josm.gui.preferences.PreferenceSetting;
48import org.openstreetmap.josm.gui.preferences.PreferenceSettingFactory;
49import org.openstreetmap.josm.gui.preferences.PreferenceTabbedPane;
50import org.openstreetmap.josm.gui.util.GuiHelper;
51import org.openstreetmap.josm.gui.widgets.AbstractFileChooser;
52import org.openstreetmap.josm.gui.widgets.JosmTextField;
53import org.openstreetmap.josm.spi.preferences.Config;
54import org.openstreetmap.josm.tools.GBC;
55import org.openstreetmap.josm.tools.Logging;
56import org.openstreetmap.josm.tools.Utils;
57
58/**
59 * Advanced preferences, allowing to set preference entries directly.
60 */
61public final class AdvancedPreference extends DefaultTabPreferenceSetting {
62
63 /**
64 * Factory used to create a new {@code AdvancedPreference}.
65 */
66 public static class Factory implements PreferenceSettingFactory {
67 @Override
68 public PreferenceSetting createPreferenceSetting() {
69 return new AdvancedPreference();
70 }
71 }
72
73 private List<PrefEntry> allData;
74 private final List<PrefEntry> displayData = new ArrayList<>();
75 private JosmTextField txtFilter;
76 private PreferencesTable table;
77
78 private final Map<String, String> profileTypes = new LinkedHashMap<>();
79
80 private final Comparator<PrefEntry> customComparator = (o1, o2) -> {
81 if (o1.isChanged() && !o2.isChanged())
82 return -1;
83 if (o2.isChanged() && !o1.isChanged())
84 return 1;
85 if (!(o1.isDefault()) && o2.isDefault())
86 return -1;
87 if (!(o2.isDefault()) && o1.isDefault())
88 return 1;
89 return o1.compareTo(o2);
90 };
91
92 private AdvancedPreference() {
93 super(/* ICON(preferences/) */ "advanced", tr("Advanced Preferences"), tr("Setting Preference entries directly. Use with caution!"));
94 }
95
96 @Override
97 public boolean isExpert() {
98 return true;
99 }
100
101 @Override
102 public void addGui(final PreferenceTabbedPane gui) {
103 JPanel p = gui.createPreferenceTab(this);
104
105 txtFilter = new JosmTextField();
106 JLabel lbFilter = new JLabel(tr("Search: "));
107 lbFilter.setLabelFor(txtFilter);
108 p.add(lbFilter);
109 p.add(txtFilter, GBC.eol().fill(GBC.HORIZONTAL));
110 txtFilter.getDocument().addDocumentListener(new DocumentListener() {
111 @Override
112 public void changedUpdate(DocumentEvent e) {
113 action();
114 }
115
116 @Override
117 public void insertUpdate(DocumentEvent e) {
118 action();
119 }
120
121 @Override
122 public void removeUpdate(DocumentEvent e) {
123 action();
124 }
125
126 private void action() {
127 applyFilter();
128 }
129 });
130 readPreferences(Main.pref);
131
132 applyFilter();
133 table = new PreferencesTable(displayData);
134 JScrollPane scroll = new JScrollPane(table);
135 p.add(scroll, GBC.eol().fill(GBC.BOTH));
136 scroll.setPreferredSize(new Dimension(400, 200));
137
138 JButton add = new JButton(tr("Add"));
139 p.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL));
140 p.add(add, GBC.std().insets(0, 5, 0, 0));
141 add.addActionListener(e -> {
142 PrefEntry pe = table.addPreference(gui);
143 if (pe != null) {
144 allData.add(pe);
145 Collections.sort(allData);
146 applyFilter();
147 }
148 });
149
150 JButton edit = new JButton(tr("Edit"));
151 p.add(edit, GBC.std().insets(5, 5, 5, 0));
152 edit.addActionListener(e -> {
153 if (table.editPreference(gui))
154 applyFilter();
155 });
156
157 JButton reset = new JButton(tr("Reset"));
158 p.add(reset, GBC.std().insets(0, 5, 0, 0));
159 reset.addActionListener(e -> table.resetPreferences(gui));
160
161 JButton read = new JButton(tr("Read from file"));
162 p.add(read, GBC.std().insets(5, 5, 0, 0));
163 read.addActionListener(e -> readPreferencesFromXML());
164
165 JButton export = new JButton(tr("Export selected items"));
166 p.add(export, GBC.std().insets(5, 5, 0, 0));
167 export.addActionListener(e -> exportSelectedToXML());
168
169 final JButton more = new JButton(tr("More..."));
170 p.add(more, GBC.std().insets(5, 5, 0, 0));
171 more.addActionListener(new ActionListener() {
172 private JPopupMenu menu = buildPopupMenu();
173 @Override public void actionPerformed(ActionEvent ev) {
174 menu.show(more, 0, 0);
175 }
176 });
177 }
178
179 private void readPreferences(Preferences tmpPrefs) {
180 Map<String, Setting<?>> loaded;
181 Map<String, Setting<?>> orig = Main.pref.getAllSettings();
182 Map<String, Setting<?>> defaults = tmpPrefs.getAllDefaults();
183 orig.remove("osm-server.password");
184 defaults.remove("osm-server.password");
185 if (tmpPrefs != Main.pref) {
186 loaded = tmpPrefs.getAllSettings();
187 // plugins preference keys may be changed directly later, after plugins are downloaded
188 // so we do not want to show it in the table as "changed" now
189 Setting<?> pluginSetting = orig.get("plugins");
190 if (pluginSetting != null) {
191 loaded.put("plugins", pluginSetting);
192 }
193 } else {
194 loaded = orig;
195 }
196 allData = prepareData(loaded, orig, defaults);
197 }
198
199 private static File[] askUserForCustomSettingsFiles(boolean saveFileFlag, String title) {
200 FileFilter filter = new FileFilter() {
201 @Override
202 public boolean accept(File f) {
203 return f.isDirectory() || Utils.hasExtension(f, "xml");
204 }
205
206 @Override
207 public String getDescription() {
208 return tr("JOSM custom settings files (*.xml)");
209 }
210 };
211 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(!saveFileFlag, !saveFileFlag, title, filter,
212 JFileChooser.FILES_ONLY, "customsettings.lastDirectory");
213 if (fc != null) {
214 File[] sel = fc.isMultiSelectionEnabled() ? fc.getSelectedFiles() : (new File[]{fc.getSelectedFile()});
215 if (sel.length == 1 && !sel[0].getName().contains("."))
216 sel[0] = new File(sel[0].getAbsolutePath()+".xml");
217 return sel;
218 }
219 return new File[0];
220 }
221
222 private void exportSelectedToXML() {
223 List<String> keys = new ArrayList<>();
224 boolean hasLists = false;
225
226 for (PrefEntry p: table.getSelectedItems()) {
227 // preferences with default values are not saved
228 if (!(p.getValue() instanceof StringSetting)) {
229 hasLists = true; // => append and replace differs
230 }
231 if (!p.isDefault()) {
232 keys.add(p.getKey());
233 }
234 }
235
236 if (keys.isEmpty()) {
237 JOptionPane.showMessageDialog(Main.parent,
238 tr("Please select some preference keys not marked as default"), tr("Warning"), JOptionPane.WARNING_MESSAGE);
239 return;
240 }
241
242 File[] files = askUserForCustomSettingsFiles(true, tr("Export preferences keys to JOSM customization file"));
243 if (files.length == 0) {
244 return;
245 }
246
247 int answer = 0;
248 if (hasLists) {
249 answer = JOptionPane.showOptionDialog(
250 Main.parent, tr("What to do with preference lists when this file is to be imported?"), tr("Question"),
251 JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null,
252 new String[]{tr("Append preferences from file to existing values"), tr("Replace existing values")}, 0);
253 }
254 CustomConfigurator.exportPreferencesKeysToFile(files[0].getAbsolutePath(), answer == 0, keys);
255 }
256
257 private void readPreferencesFromXML() {
258 File[] files = askUserForCustomSettingsFiles(false, tr("Open JOSM customization file"));
259 if (files.length == 0)
260 return;
261
262 Preferences tmpPrefs = new Preferences(Main.pref);
263
264 StringBuilder log = new StringBuilder();
265 log.append("<html>");
266 for (File f : files) {
267 CustomConfigurator.readXML(f, tmpPrefs);
268 log.append(PreferencesUtils.getLog());
269 }
270 log.append("</html>");
271 String msg = log.toString().replace("\n", "<br/>");
272
273 new LogShowDialog(tr("Import log"), tr("<html>Here is file import summary. <br/>"
274 + "You can reject preferences changes by pressing \"Cancel\" in preferences dialog <br/>"
275 + "To activate some changes JOSM restart may be needed.</html>"), msg).showDialog();
276
277 readPreferences(tmpPrefs);
278 // sorting after modification - first modified, then non-default, then default entries
279 allData.sort(customComparator);
280 applyFilter();
281 }
282
283 private List<PrefEntry> prepareData(Map<String, Setting<?>> loaded, Map<String, Setting<?>> orig, Map<String, Setting<?>> defaults) {
284 List<PrefEntry> data = new ArrayList<>();
285 for (Entry<String, Setting<?>> e : loaded.entrySet()) {
286 Setting<?> value = e.getValue();
287 Setting<?> old = orig.get(e.getKey());
288 Setting<?> def = defaults.get(e.getKey());
289 if (def == null) {
290 def = value.getNullInstance();
291 }
292 PrefEntry en = new PrefEntry(e.getKey(), value, def, false);
293 // after changes we have nondefault value. Value is changed if is not equal to old value
294 if (!Objects.equals(old, value)) {
295 en.markAsChanged();
296 }
297 data.add(en);
298 }
299 for (Entry<String, Setting<?>> e : defaults.entrySet()) {
300 if (!loaded.containsKey(e.getKey())) {
301 PrefEntry en = new PrefEntry(e.getKey(), e.getValue(), e.getValue(), true);
302 // after changes we have default value. So, value is changed if old value is not default
303 Setting<?> old = orig.get(e.getKey());
304 if (old != null) {
305 en.markAsChanged();
306 }
307 data.add(en);
308 }
309 }
310 Collections.sort(data);
311 displayData.clear();
312 displayData.addAll(data);
313 return data;
314 }
315
316 private JPopupMenu buildPopupMenu() {
317 JPopupMenu menu = new JPopupMenu();
318 profileTypes.put(marktr("shortcut"), "shortcut\\..*");
319 profileTypes.put(marktr("color"), "color\\..*");
320 profileTypes.put(marktr("toolbar"), "toolbar.*");
321 profileTypes.put(marktr("imagery"), "imagery.*");
322
323 for (Entry<String, String> e: profileTypes.entrySet()) {
324 menu.add(new ExportProfileAction(Main.pref, e.getKey(), e.getValue()));
325 }
326
327 menu.addSeparator();
328 menu.add(getProfileMenu());
329 menu.addSeparator();
330 menu.add(new AbstractAction(tr("Reset preferences")) {
331 @Override
332 public void actionPerformed(ActionEvent ae) {
333 if (!GuiHelper.warnUser(tr("Reset preferences"),
334 "<html>"+
335 tr("You are about to clear all preferences to their default values<br />"+
336 "All your settings will be deleted: plugins, imagery, filters, toolbar buttons, keyboard, etc. <br />"+
337 "Are you sure you want to continue?")
338 +"</html>", null, "")) {
339 Main.pref.resetToDefault();
340 try {
341 Main.pref.save();
342 } catch (IOException e) {
343 Logging.log(Logging.LEVEL_WARN, "IOException while saving preferences:", e);
344 }
345 readPreferences(Main.pref);
346 applyFilter();
347 }
348 }
349 });
350 return menu;
351 }
352
353 private JMenu getProfileMenu() {
354 final JMenu p = new JMenu(tr("Load profile"));
355 p.addMenuListener(new MenuListener() {
356 @Override
357 public void menuSelected(MenuEvent me) {
358 p.removeAll();
359 File[] files = new File(".").listFiles();
360 if (files != null) {
361 for (File f: files) {
362 String s = f.getName();
363 int idx = s.indexOf('_');
364 if (idx >= 0) {
365 String t = s.substring(0, idx);
366 if (profileTypes.containsKey(t)) {
367 p.add(new ImportProfileAction(s, f, t));
368 }
369 }
370 }
371 }
372 files = Config.getDirs().getPreferencesDirectory(false).listFiles();
373 if (files != null) {
374 for (File f: files) {
375 String s = f.getName();
376 int idx = s.indexOf('_');
377 if (idx >= 0) {
378 String t = s.substring(0, idx);
379 if (profileTypes.containsKey(t)) {
380 p.add(new ImportProfileAction(s, f, t));
381 }
382 }
383 }
384 }
385 }
386
387 @Override
388 public void menuDeselected(MenuEvent me) {
389 // Not implemented
390 }
391
392 @Override
393 public void menuCanceled(MenuEvent me) {
394 // Not implemented
395 }
396 });
397 return p;
398 }
399
400 private class ImportProfileAction extends AbstractAction {
401 private final File file;
402 private final String type;
403
404 ImportProfileAction(String name, File file, String type) {
405 super(name);
406 this.file = file;
407 this.type = type;
408 }
409
410 @Override
411 public void actionPerformed(ActionEvent ae) {
412 Preferences tmpPrefs = new Preferences(Main.pref);
413 CustomConfigurator.readXML(file, tmpPrefs);
414 readPreferences(tmpPrefs);
415 String prefRegex = profileTypes.get(type);
416 // clean all the preferences from the chosen group
417 for (PrefEntry p : allData) {
418 if (p.getKey().matches(prefRegex) && !p.isDefault()) {
419 p.reset();
420 }
421 }
422 // allow user to review the changes in table
423 allData.sort(customComparator);
424 applyFilter();
425 }
426 }
427
428 private void applyFilter() {
429 displayData.clear();
430 for (PrefEntry e : allData) {
431 String prefKey = e.getKey();
432 Setting<?> valueSetting = e.getValue();
433 String prefValue = valueSetting.getValue() == null ? "" : valueSetting.getValue().toString();
434
435 String[] input = txtFilter.getText().split("\\s+");
436 boolean canHas = true;
437
438 // Make 'wmsplugin cache' search for e.g. 'cache.wmsplugin'
439 final String prefKeyLower = prefKey.toLowerCase(Locale.ENGLISH);
440 final String prefValueLower = prefValue.toLowerCase(Locale.ENGLISH);
441 for (String bit : input) {
442 bit = bit.toLowerCase(Locale.ENGLISH);
443 if (!prefKeyLower.contains(bit) && !prefValueLower.contains(bit)) {
444 canHas = false;
445 break;
446 }
447 }
448 if (canHas) {
449 displayData.add(e);
450 }
451 }
452 if (table != null)
453 table.fireDataChanged();
454 }
455
456 @Override
457 public boolean ok() {
458 for (PrefEntry e : allData) {
459 if (e.isChanged()) {
460 Main.pref.putSetting(e.getKey(), e.getValue().getValue() == null ? null : e.getValue());
461 }
462 }
463 return false;
464 }
465}
Note: See TracBrowser for help on using the repository browser.