001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.gui.preferences.advanced; 003 004import static org.openstreetmap.josm.tools.I18n.marktr; 005import static org.openstreetmap.josm.tools.I18n.tr; 006 007import java.awt.Dimension; 008import java.awt.event.ActionEvent; 009import java.awt.event.ActionListener; 010import java.io.File; 011import java.io.IOException; 012import java.util.ArrayList; 013import java.util.Collections; 014import java.util.Comparator; 015import java.util.LinkedHashMap; 016import java.util.List; 017import java.util.Locale; 018import java.util.Map; 019import java.util.Map.Entry; 020import java.util.Objects; 021 022import javax.swing.AbstractAction; 023import javax.swing.Box; 024import javax.swing.JButton; 025import javax.swing.JFileChooser; 026import javax.swing.JLabel; 027import javax.swing.JMenu; 028import javax.swing.JOptionPane; 029import javax.swing.JPanel; 030import javax.swing.JPopupMenu; 031import javax.swing.JScrollPane; 032import javax.swing.event.DocumentEvent; 033import javax.swing.event.DocumentListener; 034import javax.swing.event.MenuEvent; 035import javax.swing.event.MenuListener; 036import javax.swing.filechooser.FileFilter; 037 038import org.openstreetmap.josm.Main; 039import org.openstreetmap.josm.actions.DiskAccessAction; 040import org.openstreetmap.josm.data.CustomConfigurator; 041import org.openstreetmap.josm.data.Preferences; 042import org.openstreetmap.josm.data.preferences.Setting; 043import org.openstreetmap.josm.data.preferences.StringSetting; 044import org.openstreetmap.josm.gui.dialogs.LogShowDialog; 045import org.openstreetmap.josm.gui.preferences.DefaultTabPreferenceSetting; 046import org.openstreetmap.josm.gui.preferences.PreferenceSetting; 047import org.openstreetmap.josm.gui.preferences.PreferenceSettingFactory; 048import org.openstreetmap.josm.gui.preferences.PreferenceTabbedPane; 049import org.openstreetmap.josm.gui.util.GuiHelper; 050import org.openstreetmap.josm.gui.widgets.AbstractFileChooser; 051import org.openstreetmap.josm.gui.widgets.JosmTextField; 052import org.openstreetmap.josm.tools.GBC; 053import org.openstreetmap.josm.tools.Utils; 054 055/** 056 * Advanced preferences, allowing to set preference entries directly. 057 */ 058public final class AdvancedPreference extends DefaultTabPreferenceSetting { 059 060 /** 061 * Factory used to create a new {@code AdvancedPreference}. 062 */ 063 public static class Factory implements PreferenceSettingFactory { 064 @Override 065 public PreferenceSetting createPreferenceSetting() { 066 return new AdvancedPreference(); 067 } 068 } 069 070 private List<PrefEntry> allData; 071 private final List<PrefEntry> displayData = new ArrayList<>(); 072 private JosmTextField txtFilter; 073 private PreferencesTable table; 074 075 private final Map<String, String> profileTypes = new LinkedHashMap<>(); 076 077 private final Comparator<PrefEntry> customComparator = (o1, o2) -> { 078 if (o1.isChanged() && !o2.isChanged()) 079 return -1; 080 if (o2.isChanged() && !o1.isChanged()) 081 return 1; 082 if (!(o1.isDefault()) && o2.isDefault()) 083 return -1; 084 if (!(o2.isDefault()) && o1.isDefault()) 085 return 1; 086 return o1.compareTo(o2); 087 }; 088 089 private AdvancedPreference() { 090 super(/* ICON(preferences/) */ "advanced", tr("Advanced Preferences"), tr("Setting Preference entries directly. Use with caution!")); 091 } 092 093 @Override 094 public boolean isExpert() { 095 return true; 096 } 097 098 @Override 099 public void addGui(final PreferenceTabbedPane gui) { 100 JPanel p = gui.createPreferenceTab(this); 101 102 txtFilter = new JosmTextField(); 103 JLabel lbFilter = new JLabel(tr("Search: ")); 104 lbFilter.setLabelFor(txtFilter); 105 p.add(lbFilter); 106 p.add(txtFilter, GBC.eol().fill(GBC.HORIZONTAL)); 107 txtFilter.getDocument().addDocumentListener(new DocumentListener() { 108 @Override 109 public void changedUpdate(DocumentEvent e) { 110 action(); 111 } 112 113 @Override 114 public void insertUpdate(DocumentEvent e) { 115 action(); 116 } 117 118 @Override 119 public void removeUpdate(DocumentEvent e) { 120 action(); 121 } 122 123 private void action() { 124 applyFilter(); 125 } 126 }); 127 readPreferences(Main.pref); 128 129 applyFilter(); 130 table = new PreferencesTable(displayData); 131 JScrollPane scroll = new JScrollPane(table); 132 p.add(scroll, GBC.eol().fill(GBC.BOTH)); 133 scroll.setPreferredSize(new Dimension(400, 200)); 134 135 JButton add = new JButton(tr("Add")); 136 p.add(Box.createHorizontalGlue(), GBC.std().fill(GBC.HORIZONTAL)); 137 p.add(add, GBC.std().insets(0, 5, 0, 0)); 138 add.addActionListener(e -> { 139 PrefEntry pe = table.addPreference(gui); 140 if (pe != null) { 141 allData.add(pe); 142 Collections.sort(allData); 143 applyFilter(); 144 } 145 }); 146 147 JButton edit = new JButton(tr("Edit")); 148 p.add(edit, GBC.std().insets(5, 5, 5, 0)); 149 edit.addActionListener(e -> { 150 if (table.editPreference(gui)) 151 applyFilter(); 152 }); 153 154 JButton reset = new JButton(tr("Reset")); 155 p.add(reset, GBC.std().insets(0, 5, 0, 0)); 156 reset.addActionListener(e -> table.resetPreferences(gui)); 157 158 JButton read = new JButton(tr("Read from file")); 159 p.add(read, GBC.std().insets(5, 5, 0, 0)); 160 read.addActionListener(e -> readPreferencesFromXML()); 161 162 JButton export = new JButton(tr("Export selected items")); 163 p.add(export, GBC.std().insets(5, 5, 0, 0)); 164 export.addActionListener(e -> exportSelectedToXML()); 165 166 final JButton more = new JButton(tr("More...")); 167 p.add(more, GBC.std().insets(5, 5, 0, 0)); 168 more.addActionListener(new ActionListener() { 169 private JPopupMenu menu = buildPopupMenu(); 170 @Override public void actionPerformed(ActionEvent ev) { 171 menu.show(more, 0, 0); 172 } 173 }); 174 } 175 176 private void readPreferences(Preferences tmpPrefs) { 177 Map<String, Setting<?>> loaded; 178 Map<String, Setting<?>> orig = Main.pref.getAllSettings(); 179 Map<String, Setting<?>> defaults = tmpPrefs.getAllDefaults(); 180 orig.remove("osm-server.password"); 181 defaults.remove("osm-server.password"); 182 if (tmpPrefs != Main.pref) { 183 loaded = tmpPrefs.getAllSettings(); 184 // plugins preference keys may be changed directly later, after plugins are downloaded 185 // so we do not want to show it in the table as "changed" now 186 Setting<?> pluginSetting = orig.get("plugins"); 187 if (pluginSetting != null) { 188 loaded.put("plugins", pluginSetting); 189 } 190 } else { 191 loaded = orig; 192 } 193 allData = prepareData(loaded, orig, defaults); 194 } 195 196 private static File[] askUserForCustomSettingsFiles(boolean saveFileFlag, String title) { 197 FileFilter filter = new FileFilter() { 198 @Override 199 public boolean accept(File f) { 200 return f.isDirectory() || Utils.hasExtension(f, "xml"); 201 } 202 203 @Override 204 public String getDescription() { 205 return tr("JOSM custom settings files (*.xml)"); 206 } 207 }; 208 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(!saveFileFlag, !saveFileFlag, title, filter, 209 JFileChooser.FILES_ONLY, "customsettings.lastDirectory"); 210 if (fc != null) { 211 File[] sel = fc.isMultiSelectionEnabled() ? fc.getSelectedFiles() : (new File[]{fc.getSelectedFile()}); 212 if (sel.length == 1 && !sel[0].getName().contains(".")) 213 sel[0] = new File(sel[0].getAbsolutePath()+".xml"); 214 return sel; 215 } 216 return new File[0]; 217 } 218 219 private void exportSelectedToXML() { 220 List<String> keys = new ArrayList<>(); 221 boolean hasLists = false; 222 223 for (PrefEntry p: table.getSelectedItems()) { 224 // preferences with default values are not saved 225 if (!(p.getValue() instanceof StringSetting)) { 226 hasLists = true; // => append and replace differs 227 } 228 if (!p.isDefault()) { 229 keys.add(p.getKey()); 230 } 231 } 232 233 if (keys.isEmpty()) { 234 JOptionPane.showMessageDialog(Main.parent, 235 tr("Please select some preference keys not marked as default"), tr("Warning"), JOptionPane.WARNING_MESSAGE); 236 return; 237 } 238 239 File[] files = askUserForCustomSettingsFiles(true, tr("Export preferences keys to JOSM customization file")); 240 if (files.length == 0) { 241 return; 242 } 243 244 int answer = 0; 245 if (hasLists) { 246 answer = JOptionPane.showOptionDialog( 247 Main.parent, tr("What to do with preference lists when this file is to be imported?"), tr("Question"), 248 JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, 249 new String[]{tr("Append preferences from file to existing values"), tr("Replace existing values")}, 0); 250 } 251 CustomConfigurator.exportPreferencesKeysToFile(files[0].getAbsolutePath(), answer == 0, keys); 252 } 253 254 private void readPreferencesFromXML() { 255 File[] files = askUserForCustomSettingsFiles(false, tr("Open JOSM customization file")); 256 if (files.length == 0) 257 return; 258 259 Preferences tmpPrefs = CustomConfigurator.clonePreferences(Main.pref); 260 261 StringBuilder log = new StringBuilder(); 262 log.append("<html>"); 263 for (File f : files) { 264 CustomConfigurator.readXML(f, tmpPrefs); 265 log.append(CustomConfigurator.getLog()); 266 } 267 log.append("</html>"); 268 String msg = log.toString().replace("\n", "<br/>"); 269 270 new LogShowDialog(tr("Import log"), tr("<html>Here is file import summary. <br/>" 271 + "You can reject preferences changes by pressing \"Cancel\" in preferences dialog <br/>" 272 + "To activate some changes JOSM restart may be needed.</html>"), msg).showDialog(); 273 274 readPreferences(tmpPrefs); 275 // sorting after modification - first modified, then non-default, then default entries 276 allData.sort(customComparator); 277 applyFilter(); 278 } 279 280 private List<PrefEntry> prepareData(Map<String, Setting<?>> loaded, Map<String, Setting<?>> orig, Map<String, Setting<?>> defaults) { 281 List<PrefEntry> data = new ArrayList<>(); 282 for (Entry<String, Setting<?>> e : loaded.entrySet()) { 283 Setting<?> value = e.getValue(); 284 Setting<?> old = orig.get(e.getKey()); 285 Setting<?> def = defaults.get(e.getKey()); 286 if (def == null) { 287 def = value.getNullInstance(); 288 } 289 PrefEntry en = new PrefEntry(e.getKey(), value, def, false); 290 // after changes we have nondefault value. Value is changed if is not equal to old value 291 if (!Objects.equals(old, value)) { 292 en.markAsChanged(); 293 } 294 data.add(en); 295 } 296 for (Entry<String, Setting<?>> e : defaults.entrySet()) { 297 if (!loaded.containsKey(e.getKey())) { 298 PrefEntry en = new PrefEntry(e.getKey(), e.getValue(), e.getValue(), true); 299 // after changes we have default value. So, value is changed if old value is not default 300 Setting<?> old = orig.get(e.getKey()); 301 if (old != null) { 302 en.markAsChanged(); 303 } 304 data.add(en); 305 } 306 } 307 Collections.sort(data); 308 displayData.clear(); 309 displayData.addAll(data); 310 return data; 311 } 312 313 private JPopupMenu buildPopupMenu() { 314 JPopupMenu menu = new JPopupMenu(); 315 profileTypes.put(marktr("shortcut"), "shortcut\\..*"); 316 profileTypes.put(marktr("color"), "color\\..*"); 317 profileTypes.put(marktr("toolbar"), "toolbar.*"); 318 profileTypes.put(marktr("imagery"), "imagery.*"); 319 320 for (Entry<String, String> e: profileTypes.entrySet()) { 321 menu.add(new ExportProfileAction(Main.pref, e.getKey(), e.getValue())); 322 } 323 324 menu.addSeparator(); 325 menu.add(getProfileMenu()); 326 menu.addSeparator(); 327 menu.add(new AbstractAction(tr("Reset preferences")) { 328 @Override 329 public void actionPerformed(ActionEvent ae) { 330 if (!GuiHelper.warnUser(tr("Reset preferences"), 331 "<html>"+ 332 tr("You are about to clear all preferences to their default values<br />"+ 333 "All your settings will be deleted: plugins, imagery, filters, toolbar buttons, keyboard, etc. <br />"+ 334 "Are you sure you want to continue?") 335 +"</html>", null, "")) { 336 Main.pref.resetToDefault(); 337 try { 338 Main.pref.save(); 339 } catch (IOException e) { 340 Main.warn(e, "IOException while saving preferences:"); 341 } 342 readPreferences(Main.pref); 343 applyFilter(); 344 } 345 } 346 }); 347 return menu; 348 } 349 350 private JMenu getProfileMenu() { 351 final JMenu p = new JMenu(tr("Load profile")); 352 p.addMenuListener(new MenuListener() { 353 @Override 354 public void menuSelected(MenuEvent me) { 355 p.removeAll(); 356 File[] files = new File(".").listFiles(); 357 if (files != null) { 358 for (File f: files) { 359 String s = f.getName(); 360 int idx = s.indexOf('_'); 361 if (idx >= 0) { 362 String t = s.substring(0, idx); 363 if (profileTypes.containsKey(t)) { 364 p.add(new ImportProfileAction(s, f, t)); 365 } 366 } 367 } 368 } 369 files = Main.pref.getPreferencesDirectory().listFiles(); 370 if (files != null) { 371 for (File f: files) { 372 String s = f.getName(); 373 int idx = s.indexOf('_'); 374 if (idx >= 0) { 375 String t = s.substring(0, idx); 376 if (profileTypes.containsKey(t)) { 377 p.add(new ImportProfileAction(s, f, t)); 378 } 379 } 380 } 381 } 382 } 383 384 @Override 385 public void menuDeselected(MenuEvent me) { 386 // Not implemented 387 } 388 389 @Override 390 public void menuCanceled(MenuEvent me) { 391 // Not implemented 392 } 393 }); 394 return p; 395 } 396 397 private class ImportProfileAction extends AbstractAction { 398 private final File file; 399 private final String type; 400 401 ImportProfileAction(String name, File file, String type) { 402 super(name); 403 this.file = file; 404 this.type = type; 405 } 406 407 @Override 408 public void actionPerformed(ActionEvent ae) { 409 Preferences tmpPrefs = CustomConfigurator.clonePreferences(Main.pref); 410 CustomConfigurator.readXML(file, tmpPrefs); 411 readPreferences(tmpPrefs); 412 String prefRegex = profileTypes.get(type); 413 // clean all the preferences from the chosen group 414 for (PrefEntry p : allData) { 415 if (p.getKey().matches(prefRegex) && !p.isDefault()) { 416 p.reset(); 417 } 418 } 419 // allow user to review the changes in table 420 allData.sort(customComparator); 421 applyFilter(); 422 } 423 } 424 425 private void applyFilter() { 426 displayData.clear(); 427 for (PrefEntry e : allData) { 428 String prefKey = e.getKey(); 429 Setting<?> valueSetting = e.getValue(); 430 String prefValue = valueSetting.getValue() == null ? "" : valueSetting.getValue().toString(); 431 432 String[] input = txtFilter.getText().split("\\s+"); 433 boolean canHas = true; 434 435 // Make 'wmsplugin cache' search for e.g. 'cache.wmsplugin' 436 final String prefKeyLower = prefKey.toLowerCase(Locale.ENGLISH); 437 final String prefValueLower = prefValue.toLowerCase(Locale.ENGLISH); 438 for (String bit : input) { 439 bit = bit.toLowerCase(Locale.ENGLISH); 440 if (!prefKeyLower.contains(bit) && !prefValueLower.contains(bit)) { 441 canHas = false; 442 break; 443 } 444 } 445 if (canHas) { 446 displayData.add(e); 447 } 448 } 449 if (table != null) 450 table.fireDataChanged(); 451 } 452 453 @Override 454 public boolean ok() { 455 for (PrefEntry e : allData) { 456 if (e.isChanged()) { 457 Main.pref.putSetting(e.getKey(), e.getValue().getValue() == null ? null : e.getValue()); 458 } 459 } 460 return false; 461 } 462}