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; 022 023/** 024 * Action that exports some fragment of settings to custom configuration file 025 */ 026public class ExportProfileAction extends AbstractAction { 027 private final String prefPattern; 028 private final String schemaKey; 029 private final Preferences prefs; 030 031 /** 032 * Constructs a new {@code ExportProfileAction}. 033 */ 034 public ExportProfileAction(Preferences prefs, String schemaKey, String prefPattern) { 035 super(tr("Save {0} profile", tr(schemaKey))); 036 this.prefs = prefs; 037 this.prefPattern = prefPattern; 038 this.schemaKey = schemaKey; 039 } 040 041 @Override 042 public void actionPerformed(ActionEvent ae) { 043 List<String> keys = new ArrayList<>(); 044 Map<String, Setting<?>> all = prefs.getAllSettings(); 045 for (String key: all.keySet()) { 046 if (key.matches(prefPattern)) { 047 keys.add(key); 048 } 049 } 050 if (keys.isEmpty()) { 051 JOptionPane.showMessageDialog(Main.parent, 052 tr("All the preferences of this group are default, nothing to save"), tr("Warning"), JOptionPane.WARNING_MESSAGE); 053 return; 054 } 055 File f = askUserForCustomSettingsFile(); 056 if (f!=null) 057 CustomConfigurator.exportPreferencesKeysToFile(f.getAbsolutePath(), false, keys); 058 } 059 060 private File askUserForCustomSettingsFile() { 061 String title = tr("Choose profile file"); 062 063 FileFilter filter = new FileFilter() { 064 @Override 065 public boolean accept(File f) { 066 return f.isDirectory() || f.getName().toLowerCase().endsWith(".xml") && f.getName().toLowerCase().startsWith(schemaKey); 067 } 068 @Override 069 public String getDescription() { 070 return tr("JOSM custom settings files (*.xml)"); 071 } 072 }; 073 JFileChooser fc = DiskAccessAction.createAndOpenFileChooser(false, false, title, filter, JFileChooser.FILES_ONLY, "customsettings.lastDirectory"); 074 if (fc != null) { 075 File sel = fc.getSelectedFile(); 076 if (!sel.getName().endsWith(".xml")) sel=new File(sel.getAbsolutePath()+".xml"); 077 if (!sel.getName().startsWith(schemaKey)) { 078 sel = new File(sel.getParentFile().getAbsolutePath()+"/"+schemaKey+"_"+sel.getName()); 079 } 080 return sel; 081 } 082 return null; 083 } 084}