001// License: GPL. See LICENSE file for details. 002package org.openstreetmap.josm.gui.preferences.advanced; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006import java.awt.event.ActionEvent; 007import java.io.File; 008import java.util.ArrayList; 009import java.util.List; 010import java.util.Map; 011 012import javax.swing.AbstractAction; 013import javax.swing.JFileChooser; 014import javax.swing.JOptionPane; 015import javax.swing.filechooser.FileFilter; 016 017import org.openstreetmap.josm.Main; 018import org.openstreetmap.josm.actions.DiskAccessAction; 019import org.openstreetmap.josm.data.CustomConfigurator; 020import org.openstreetmap.josm.data.Preferences; 021import org.openstreetmap.josm.data.Preferences.Setting; 022import org.openstreetmap.josm.gui.widgets.AbstractFileChooser; 023 024/** 025 * Action that exports some fragment of settings to custom configuration file 026 */ 027public class ExportProfileAction extends AbstractAction { 028 private final String prefPattern; 029 private final String schemaKey; 030 private final Preferences prefs; 031 032 /** 033 * Constructs a new {@code ExportProfileAction}. 034 */ 035 public ExportProfileAction(Preferences prefs, String schemaKey, String prefPattern) { 036 super(tr("Save {0} profile", tr(schemaKey))); 037 this.prefs = prefs; 038 this.prefPattern = prefPattern; 039 this.schemaKey = schemaKey; 040 } 041 042 @Override 043 public void actionPerformed(ActionEvent ae) { 044 List<String> keys = new ArrayList<>(); 045 Map<String, Setting<?>> all = prefs.getAllSettings(); 046 for (String key: all.keySet()) { 047 if (key.matches(prefPattern)) { 048 keys.add(key); 049 } 050 } 051 if (keys.isEmpty()) { 052 JOptionPane.showMessageDialog(Main.parent, 053 tr("All the preferences of this group are default, nothing to save"), tr("Warning"), JOptionPane.WARNING_MESSAGE); 054 return; 055 } 056 File f = askUserForCustomSettingsFile(); 057 if (f!=null) 058 CustomConfigurator.exportPreferencesKeysToFile(f.getAbsolutePath(), false, keys); 059 } 060 061 private File askUserForCustomSettingsFile() { 062 String title = tr("Choose profile file"); 063 064 FileFilter filter = new FileFilter() { 065 @Override 066 public boolean accept(File f) { 067 return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml") && f.getName().toLowerCase().startsWith(schemaKey); 068 } 069 @Override 070 public String getDescription() { 071 return tr("JOSM custom settings files (*.xml)"); 072 } 073 }; 074 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(false, false, title, filter, JFileChooser.FILES_ONLY, "customsettings.lastDirectory"); 075 if (fc != null) { 076 File sel = fc.getSelectedFile(); 077 if (!sel.getName().endsWith(".xml")) sel=new File(sel.getAbsolutePath()+".xml"); 078 if (!sel.getName().startsWith(schemaKey)) { 079 sel = new File(sel.getParentFile().getAbsolutePath()+"/"+schemaKey+"_"+sel.getName()); 080 } 081 return sel; 082 } 083 return null; 084 } 085}