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