1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.data;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.io.BufferedInputStream;
|
---|
7 | import java.io.ByteArrayInputStream;
|
---|
8 | import java.io.CharArrayReader;
|
---|
9 | import java.io.CharArrayWriter;
|
---|
10 | import java.io.File;
|
---|
11 | import java.io.FileInputStream;
|
---|
12 | import java.io.InputStream;
|
---|
13 | import java.util.ArrayList;
|
---|
14 | import java.util.Collection;
|
---|
15 | import java.util.Collections;
|
---|
16 | import java.util.HashMap;
|
---|
17 | import java.util.HashSet;
|
---|
18 | import java.util.Iterator;
|
---|
19 | import java.util.List;
|
---|
20 | import java.util.Map;
|
---|
21 | import java.util.Map.Entry;
|
---|
22 | import java.util.SortedMap;
|
---|
23 | import java.util.TreeMap;
|
---|
24 | import java.util.regex.Matcher;
|
---|
25 | import java.util.regex.Pattern;
|
---|
26 |
|
---|
27 | import javax.script.ScriptEngine;
|
---|
28 | import javax.script.ScriptEngineManager;
|
---|
29 | import javax.script.ScriptException;
|
---|
30 | import javax.swing.JOptionPane;
|
---|
31 | import javax.swing.SwingUtilities;
|
---|
32 | import javax.xml.parsers.DocumentBuilder;
|
---|
33 | import javax.xml.parsers.DocumentBuilderFactory;
|
---|
34 | import javax.xml.transform.OutputKeys;
|
---|
35 | import javax.xml.transform.Transformer;
|
---|
36 | import javax.xml.transform.TransformerFactory;
|
---|
37 | import javax.xml.transform.dom.DOMSource;
|
---|
38 | import javax.xml.transform.stream.StreamResult;
|
---|
39 |
|
---|
40 | import org.openstreetmap.josm.Main;
|
---|
41 | import org.openstreetmap.josm.data.Preferences.ListListSetting;
|
---|
42 | import org.openstreetmap.josm.data.Preferences.ListSetting;
|
---|
43 | import org.openstreetmap.josm.data.Preferences.MapListSetting;
|
---|
44 | import org.openstreetmap.josm.data.Preferences.Setting;
|
---|
45 | import org.openstreetmap.josm.data.Preferences.StringSetting;
|
---|
46 | import org.openstreetmap.josm.gui.io.DownloadFileTask;
|
---|
47 | import org.openstreetmap.josm.plugins.PluginDownloadTask;
|
---|
48 | import org.openstreetmap.josm.plugins.PluginInformation;
|
---|
49 | import org.openstreetmap.josm.plugins.ReadLocalPluginInformationTask;
|
---|
50 | import org.openstreetmap.josm.tools.LanguageInfo;
|
---|
51 | import org.openstreetmap.josm.tools.Utils;
|
---|
52 | import org.w3c.dom.Document;
|
---|
53 | import org.w3c.dom.Element;
|
---|
54 | import org.w3c.dom.Node;
|
---|
55 | import org.w3c.dom.NodeList;
|
---|
56 |
|
---|
57 | /**
|
---|
58 | * Class to process configuration changes stored in XML
|
---|
59 | * can be used to modify preferences, store/delete files in .josm folders etc
|
---|
60 | */
|
---|
61 | public final class CustomConfigurator {
|
---|
62 |
|
---|
63 | private CustomConfigurator() {
|
---|
64 | // Hide default constructor for utils classes
|
---|
65 | }
|
---|
66 |
|
---|
67 | private static StringBuilder summary = new StringBuilder();
|
---|
68 |
|
---|
69 | public static void log(String fmt, Object... vars) {
|
---|
70 | summary.append(String.format(fmt, vars));
|
---|
71 | }
|
---|
72 |
|
---|
73 | public static void log(String s) {
|
---|
74 | summary.append(s);
|
---|
75 | summary.append("\n");
|
---|
76 | }
|
---|
77 |
|
---|
78 | public static String getLog() {
|
---|
79 | return summary.toString();
|
---|
80 | }
|
---|
81 |
|
---|
82 | public static void readXML(String dir, String fileName) {
|
---|
83 | readXML(new File(dir, fileName));
|
---|
84 | }
|
---|
85 |
|
---|
86 | /**
|
---|
87 | * Read configuration script from XML file, modifying given preferences object
|
---|
88 | * @param file - file to open for reading XML
|
---|
89 | * @param prefs - arbitrary Preferences object to modify by script
|
---|
90 | */
|
---|
91 | public static void readXML(final File file, final Preferences prefs) {
|
---|
92 | synchronized(CustomConfigurator.class) {
|
---|
93 | busy=true;
|
---|
94 | }
|
---|
95 | new XMLCommandProcessor(prefs).openAndReadXML(file);
|
---|
96 | synchronized(CustomConfigurator.class) {
|
---|
97 | CustomConfigurator.class.notifyAll();
|
---|
98 | busy=false;
|
---|
99 | }
|
---|
100 | }
|
---|
101 |
|
---|
102 | /**
|
---|
103 | * Read configuration script from XML file, modifying main preferences
|
---|
104 | * @param file - file to open for reading XML
|
---|
105 | */
|
---|
106 | public static void readXML(File file) {
|
---|
107 | readXML(file, Main.pref);
|
---|
108 | }
|
---|
109 |
|
---|
110 | /**
|
---|
111 | * Downloads file to one of JOSM standard folders
|
---|
112 | * @param address - URL to download
|
---|
113 | * @param path - file path relative to base where to put downloaded file
|
---|
114 | * @param base - only "prefs", "cache" and "plugins" allowed for standard folders
|
---|
115 | */
|
---|
116 | public static void downloadFile(String address, String path, String base) {
|
---|
117 | processDownloadOperation(address, path, getDirectoryByAbbr(base), true, false);
|
---|
118 | }
|
---|
119 |
|
---|
120 | /**
|
---|
121 | * Downloads file to one of JOSM standard folders nad unpack it as ZIP/JAR file
|
---|
122 | * @param address - URL to download
|
---|
123 | * @param path - file path relative to base where to put downloaded file
|
---|
124 | * @param base - only "prefs", "cache" and "plugins" allowed for standard folders
|
---|
125 | */
|
---|
126 | public static void downloadAndUnpackFile(String address, String path, String base) {
|
---|
127 | processDownloadOperation(address, path, getDirectoryByAbbr(base), true, true);
|
---|
128 | }
|
---|
129 |
|
---|
130 | /**
|
---|
131 | * Downloads file to arbitrary folder
|
---|
132 | * @param address - URL to download
|
---|
133 | * @param path - file path relative to parentDir where to put downloaded file
|
---|
134 | * @param parentDir - folder where to put file
|
---|
135 | * @param mkdir - if true, non-existing directories will be created
|
---|
136 | * @param unzip - if true file wil be unzipped and deleted after download
|
---|
137 | */
|
---|
138 | public static void processDownloadOperation(String address, String path, String parentDir, boolean mkdir, boolean unzip) {
|
---|
139 | String dir = parentDir;
|
---|
140 | if (path.contains("..") || path.startsWith("/") || path.contains(":")) {
|
---|
141 | return; // some basic protection
|
---|
142 | }
|
---|
143 | File fOut = new File(dir, path);
|
---|
144 | DownloadFileTask downloadFileTask = new DownloadFileTask(Main.parent, address, fOut, mkdir, unzip);
|
---|
145 |
|
---|
146 | Main.worker.submit(downloadFileTask);
|
---|
147 | log("Info: downloading file from %s to %s in background ", parentDir, fOut.getAbsolutePath());
|
---|
148 | if (unzip) log("and unpacking it"); else log("");
|
---|
149 |
|
---|
150 | }
|
---|
151 |
|
---|
152 | /**
|
---|
153 | * Simple function to show messageBox, may be used from JS API and from other code
|
---|
154 | * @param type - 'i','w','e','q','p' for Information, Warning, Error, Question, Message
|
---|
155 | * @param text - message to display, HTML allowed
|
---|
156 | */
|
---|
157 | public static void messageBox(String type, String text) {
|
---|
158 | if (type==null || type.length()==0) type="plain";
|
---|
159 |
|
---|
160 | switch (type.charAt(0)) {
|
---|
161 | case 'i': JOptionPane.showMessageDialog(Main.parent, text, tr("Information"), JOptionPane.INFORMATION_MESSAGE); break;
|
---|
162 | case 'w': JOptionPane.showMessageDialog(Main.parent, text, tr("Warning"), JOptionPane.WARNING_MESSAGE); break;
|
---|
163 | case 'e': JOptionPane.showMessageDialog(Main.parent, text, tr("Error"), JOptionPane.ERROR_MESSAGE); break;
|
---|
164 | case 'q': JOptionPane.showMessageDialog(Main.parent, text, tr("Question"), JOptionPane.QUESTION_MESSAGE); break;
|
---|
165 | case 'p': JOptionPane.showMessageDialog(Main.parent, text, tr("Message"), JOptionPane.PLAIN_MESSAGE); break;
|
---|
166 | }
|
---|
167 | }
|
---|
168 |
|
---|
169 | /**
|
---|
170 | * Simple function for choose window, may be used from JS API and from other code
|
---|
171 | * @param text - message to show, HTML allowed
|
---|
172 | * @param opts -
|
---|
173 | * @return number of pressed button, -1 if cancelled
|
---|
174 | */
|
---|
175 | public static int askForOption(String text, String opts) {
|
---|
176 | Integer answer;
|
---|
177 | if (opts.length()>0) {
|
---|
178 | String[] options = opts.split(";");
|
---|
179 | answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0);
|
---|
180 | } else {
|
---|
181 | answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, 2);
|
---|
182 | }
|
---|
183 | if (answer==null) return -1; else return answer;
|
---|
184 | }
|
---|
185 |
|
---|
186 | public static String askForText(String text) {
|
---|
187 | String s = JOptionPane.showInputDialog(Main.parent, text, tr("Enter text"), JOptionPane.QUESTION_MESSAGE);
|
---|
188 | if (s!=null && (s=s.trim()).length()>0) {
|
---|
189 | return s;
|
---|
190 | } else {
|
---|
191 | return "";
|
---|
192 | }
|
---|
193 | }
|
---|
194 |
|
---|
195 | /**
|
---|
196 | * This function exports part of user preferences to specified file.
|
---|
197 | * Default values are not saved.
|
---|
198 | * @param filename - where to export
|
---|
199 | * @param append - if true, resulting file cause appending to exuisting preferences
|
---|
200 | * @param keys - which preferences keys you need to export ("imagery.entries", for example)
|
---|
201 | */
|
---|
202 | public static void exportPreferencesKeysToFile(String filename, boolean append, String... keys) {
|
---|
203 | HashSet<String> keySet = new HashSet<String>();
|
---|
204 | Collections.addAll(keySet, keys);
|
---|
205 | exportPreferencesKeysToFile(filename, append, keySet);
|
---|
206 | }
|
---|
207 |
|
---|
208 | /**
|
---|
209 | * This function exports part of user preferences to specified file.
|
---|
210 | * Default values are not saved.
|
---|
211 | * Preference keys matching specified pattern are saved
|
---|
212 | * @param fileName - where to export
|
---|
213 | * @param append - if true, resulting file cause appending to exuisting preferences
|
---|
214 | * @param pattern - Regexp pattern forh preferences keys you need to export (".*imagery.*", for example)
|
---|
215 | */
|
---|
216 | public static void exportPreferencesKeysByPatternToFile(String fileName, boolean append, String pattern) {
|
---|
217 | List<String> keySet = new ArrayList<String>();
|
---|
218 | Map<String, Setting> allSettings = Main.pref.getAllSettings();
|
---|
219 | for (String key: allSettings.keySet()) {
|
---|
220 | if (key.matches(pattern)) keySet.add(key);
|
---|
221 | }
|
---|
222 | exportPreferencesKeysToFile(fileName, append, keySet);
|
---|
223 | }
|
---|
224 |
|
---|
225 | /**
|
---|
226 | * Export specified preferences keys to configuration file
|
---|
227 | * @param filename - name of file
|
---|
228 | * @param append - will the preferences be appended to existing ones when file is imported later. Elsewhere preferences from file will replace existing keys.
|
---|
229 | * @param keys - collection of preferences key names to save
|
---|
230 | */
|
---|
231 | public static void exportPreferencesKeysToFile(String filename, boolean append, Collection<String> keys) {
|
---|
232 | Element root = null;
|
---|
233 | Document document = null;
|
---|
234 | Document exportDocument = null;
|
---|
235 |
|
---|
236 | try {
|
---|
237 | String toXML = Main.pref.toXML(true);
|
---|
238 | InputStream is = new ByteArrayInputStream(toXML.getBytes(Utils.UTF_8));
|
---|
239 | DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
|
---|
240 | builderFactory.setValidating(false);
|
---|
241 | builderFactory.setNamespaceAware(false);
|
---|
242 | DocumentBuilder builder = builderFactory.newDocumentBuilder();
|
---|
243 | document = builder.parse(is);
|
---|
244 | exportDocument = builder.newDocument();
|
---|
245 | root = document.getDocumentElement();
|
---|
246 | } catch (Exception ex) {
|
---|
247 | Main.warn("Error getting preferences to save:" +ex.getMessage());
|
---|
248 | }
|
---|
249 | if (root==null) return;
|
---|
250 | try {
|
---|
251 |
|
---|
252 | Element newRoot = exportDocument.createElement("config");
|
---|
253 | exportDocument.appendChild(newRoot);
|
---|
254 |
|
---|
255 | Element prefElem = exportDocument.createElement("preferences");
|
---|
256 | prefElem.setAttribute("operation", append?"append":"replace");
|
---|
257 | newRoot.appendChild(prefElem);
|
---|
258 |
|
---|
259 | NodeList childNodes = root.getChildNodes();
|
---|
260 | int n = childNodes.getLength();
|
---|
261 | for (int i = 0; i < n ; i++) {
|
---|
262 | Node item = childNodes.item(i);
|
---|
263 | if (item.getNodeType() == Node.ELEMENT_NODE) {
|
---|
264 | String currentKey = ((Element) item).getAttribute("key");
|
---|
265 | if (keys.contains(currentKey)) {
|
---|
266 | Node imported = exportDocument.importNode(item, true);
|
---|
267 | prefElem.appendChild(imported);
|
---|
268 | }
|
---|
269 | }
|
---|
270 | }
|
---|
271 | File f = new File(filename);
|
---|
272 | Transformer ts = TransformerFactory.newInstance().newTransformer();
|
---|
273 | ts.setOutputProperty(OutputKeys.INDENT, "yes");
|
---|
274 | ts.transform(new DOMSource(exportDocument), new StreamResult(f.toURI().getPath()));
|
---|
275 | } catch (Exception ex) {
|
---|
276 | Main.warn("Error saving preferences part: " +ex.getMessage());
|
---|
277 | ex.printStackTrace();
|
---|
278 | }
|
---|
279 | }
|
---|
280 |
|
---|
281 |
|
---|
282 | public static void deleteFile(String path, String base) {
|
---|
283 | String dir = getDirectoryByAbbr(base);
|
---|
284 | if (dir==null) {
|
---|
285 | log("Error: Can not find base, use base=cache, base=prefs or base=plugins attribute.");
|
---|
286 | return;
|
---|
287 | }
|
---|
288 | log("Delete file: %s\n", path);
|
---|
289 | if (path.contains("..") || path.startsWith("/") || path.contains(":")) {
|
---|
290 | return; // some basic protection
|
---|
291 | }
|
---|
292 | File fOut = new File(dir, path);
|
---|
293 | if (fOut.exists()) {
|
---|
294 | deleteFileOrDirectory(fOut);
|
---|
295 | }
|
---|
296 | }
|
---|
297 |
|
---|
298 | public static void deleteFileOrDirectory(String path) {
|
---|
299 | deleteFileOrDirectory(new File(path));
|
---|
300 | }
|
---|
301 |
|
---|
302 | public static void deleteFileOrDirectory(File f) {
|
---|
303 | if (f.isDirectory()) {
|
---|
304 | for (File f1: f.listFiles()) {
|
---|
305 | deleteFileOrDirectory(f1);
|
---|
306 | }
|
---|
307 | }
|
---|
308 | try {
|
---|
309 | f.delete();
|
---|
310 | } catch (Exception e) {
|
---|
311 | log("Warning: Can not delete file "+f.getPath());
|
---|
312 | }
|
---|
313 | }
|
---|
314 |
|
---|
315 | private static boolean busy=false;
|
---|
316 |
|
---|
317 |
|
---|
318 | public static void pluginOperation(String install, String uninstall, String delete) {
|
---|
319 | final List<String> installList = new ArrayList<String>();
|
---|
320 | final List<String> removeList = new ArrayList<String>();
|
---|
321 | final List<String> deleteList = new ArrayList<String>();
|
---|
322 | Collections.addAll(installList, install.toLowerCase().split(";"));
|
---|
323 | Collections.addAll(removeList, uninstall.toLowerCase().split(";"));
|
---|
324 | Collections.addAll(deleteList, delete.toLowerCase().split(";"));
|
---|
325 | installList.remove("");removeList.remove("");deleteList.remove("");
|
---|
326 |
|
---|
327 | if (!installList.isEmpty()) {
|
---|
328 | log("Plugins install: "+installList);
|
---|
329 | }
|
---|
330 | if (!removeList.isEmpty()) {
|
---|
331 | log("Plugins turn off: "+removeList);
|
---|
332 | }
|
---|
333 | if (!deleteList.isEmpty()) {
|
---|
334 | log("Plugins delete: "+deleteList);
|
---|
335 | }
|
---|
336 |
|
---|
337 | final ReadLocalPluginInformationTask task = new ReadLocalPluginInformationTask();
|
---|
338 | Runnable r = new Runnable() {
|
---|
339 | @Override
|
---|
340 | public void run() {
|
---|
341 | if (task.isCanceled()) return;
|
---|
342 | synchronized (CustomConfigurator.class) {
|
---|
343 | try { // proceed only after all other tasks were finished
|
---|
344 | while (busy) CustomConfigurator.class.wait();
|
---|
345 | } catch (InterruptedException ex) {
|
---|
346 | Main.warn("InterruptedException while reading local plugin information");
|
---|
347 | }
|
---|
348 |
|
---|
349 | SwingUtilities.invokeLater(new Runnable() {
|
---|
350 | @Override
|
---|
351 | public void run() {
|
---|
352 | List<PluginInformation> availablePlugins = task.getAvailablePlugins();
|
---|
353 | List<PluginInformation> toInstallPlugins = new ArrayList<PluginInformation>();
|
---|
354 | List<PluginInformation> toRemovePlugins = new ArrayList<PluginInformation>();
|
---|
355 | List<PluginInformation> toDeletePlugins = new ArrayList<PluginInformation>();
|
---|
356 | for (PluginInformation pi: availablePlugins) {
|
---|
357 | String name = pi.name.toLowerCase();
|
---|
358 | if (installList.contains(name)) toInstallPlugins.add(pi);
|
---|
359 | if (removeList.contains(name)) toRemovePlugins.add(pi);
|
---|
360 | if (deleteList.contains(name)) toDeletePlugins.add(pi);
|
---|
361 | }
|
---|
362 | if (!installList.isEmpty()) {
|
---|
363 | PluginDownloadTask pluginDownloadTask = new PluginDownloadTask(Main.parent, toInstallPlugins, tr ("Installing plugins"));
|
---|
364 | Main.worker.submit(pluginDownloadTask);
|
---|
365 | }
|
---|
366 | Collection<String> pls = new ArrayList<String>(Main.pref.getCollection("plugins"));
|
---|
367 | for (PluginInformation pi: toInstallPlugins) {
|
---|
368 | if (!pls.contains(pi.name)) {
|
---|
369 | pls.add(pi.name);
|
---|
370 | }
|
---|
371 | }
|
---|
372 | for (PluginInformation pi: toRemovePlugins) {
|
---|
373 | pls.remove(pi.name);
|
---|
374 | }
|
---|
375 | for (PluginInformation pi: toDeletePlugins) {
|
---|
376 | pls.remove(pi.name);
|
---|
377 | new File(Main.pref.getPluginsDirectory(), pi.name+".jar").deleteOnExit();
|
---|
378 | }
|
---|
379 | Main.pref.putCollection("plugins",pls);
|
---|
380 | }
|
---|
381 | });
|
---|
382 | }
|
---|
383 | }
|
---|
384 |
|
---|
385 | };
|
---|
386 | Main.worker.submit(task);
|
---|
387 | Main.worker.submit(r);
|
---|
388 | }
|
---|
389 |
|
---|
390 | private static String getDirectoryByAbbr(String base) {
|
---|
391 | String dir;
|
---|
392 | if ("prefs".equals(base) || base.length()==0) {
|
---|
393 | dir = Main.pref.getPreferencesDir();
|
---|
394 | } else if ("cache".equals(base)) {
|
---|
395 | dir = Main.pref.getCacheDirectory().getAbsolutePath();
|
---|
396 | } else if ("plugins".equals(base)) {
|
---|
397 | dir = Main.pref.getPluginsDirectory().getAbsolutePath();
|
---|
398 | } else {
|
---|
399 | dir = null;
|
---|
400 | }
|
---|
401 | return dir;
|
---|
402 | }
|
---|
403 |
|
---|
404 | public static Preferences clonePreferences(Preferences pref) {
|
---|
405 | Preferences tmp = new Preferences();
|
---|
406 | tmp.settingsMap.putAll(pref.settingsMap);
|
---|
407 | tmp.defaultsMap.putAll(pref.defaultsMap);
|
---|
408 | tmp.colornames.putAll( pref.colornames );
|
---|
409 |
|
---|
410 | return tmp;
|
---|
411 | }
|
---|
412 |
|
---|
413 |
|
---|
414 | public static class XMLCommandProcessor {
|
---|
415 |
|
---|
416 | Preferences mainPrefs;
|
---|
417 | Map<String,Element> tasksMap = new HashMap<String,Element>();
|
---|
418 |
|
---|
419 | private boolean lastV; // last If condition result
|
---|
420 |
|
---|
421 |
|
---|
422 | ScriptEngine engine ;
|
---|
423 |
|
---|
424 | public void openAndReadXML(File file) {
|
---|
425 | log("-- Reading custom preferences from " + file.getAbsolutePath() + " --");
|
---|
426 | try {
|
---|
427 | String fileDir = file.getParentFile().getAbsolutePath();
|
---|
428 | if (fileDir!=null) engine.eval("scriptDir='"+normalizeDirName(fileDir) +"';");
|
---|
429 | openAndReadXML(new BufferedInputStream(new FileInputStream(file)));
|
---|
430 | } catch (Exception ex) {
|
---|
431 | log("Error reading custom preferences: " + ex.getMessage());
|
---|
432 | }
|
---|
433 | }
|
---|
434 |
|
---|
435 | public void openAndReadXML(InputStream is) {
|
---|
436 | try {
|
---|
437 | DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
|
---|
438 | builderFactory.setValidating(false);
|
---|
439 | builderFactory.setNamespaceAware(true);
|
---|
440 | DocumentBuilder builder = builderFactory.newDocumentBuilder();
|
---|
441 | Document document = builder.parse(is);
|
---|
442 | synchronized (CustomConfigurator.class) {
|
---|
443 | processXML(document);
|
---|
444 | }
|
---|
445 | } catch (Exception ex) {
|
---|
446 | log("Error reading custom preferences: "+ex.getMessage());
|
---|
447 | } finally {
|
---|
448 | Utils.close(is);
|
---|
449 | }
|
---|
450 | log("-- Reading complete --");
|
---|
451 | }
|
---|
452 |
|
---|
453 | public XMLCommandProcessor(Preferences mainPrefs) {
|
---|
454 | try {
|
---|
455 | this.mainPrefs = mainPrefs;
|
---|
456 | CustomConfigurator.summary = new StringBuilder();
|
---|
457 | engine = new ScriptEngineManager().getEngineByName("rhino");
|
---|
458 | engine.eval("API={}; API.pref={}; API.fragments={};");
|
---|
459 |
|
---|
460 | engine.eval("homeDir='"+normalizeDirName(Main.pref.getPreferencesDir()) +"';");
|
---|
461 | engine.eval("josmVersion="+Version.getInstance().getVersion()+";");
|
---|
462 | String className = CustomConfigurator.class.getName();
|
---|
463 | engine.eval("API.messageBox="+className+".messageBox");
|
---|
464 | engine.eval("API.askText=function(text) { return String("+className+".askForText(text));}");
|
---|
465 | engine.eval("API.askOption="+className+".askForOption");
|
---|
466 | engine.eval("API.downloadFile="+className+".downloadFile");
|
---|
467 | engine.eval("API.downloadAndUnpackFile="+className+".downloadAndUnpackFile");
|
---|
468 | engine.eval("API.deleteFile="+className+".deleteFile");
|
---|
469 | engine.eval("API.plugin ="+className+".pluginOperation");
|
---|
470 | engine.eval("API.pluginInstall = function(names) { "+className+".pluginOperation(names,'','');}");
|
---|
471 | engine.eval("API.pluginUninstall = function(names) { "+className+".pluginOperation('',names,'');}");
|
---|
472 | engine.eval("API.pluginDelete = function(names) { "+className+".pluginOperation('','',names);}");
|
---|
473 | } catch (Exception ex) {
|
---|
474 | log("Error: initializing script engine: "+ex.getMessage());
|
---|
475 | }
|
---|
476 | }
|
---|
477 |
|
---|
478 | private void processXML(Document document) {
|
---|
479 | Element root = document.getDocumentElement();
|
---|
480 | processXmlFragment(root);
|
---|
481 | }
|
---|
482 |
|
---|
483 | private void processXmlFragment(Element root) {
|
---|
484 | NodeList childNodes = root.getChildNodes();
|
---|
485 | int nops = childNodes.getLength();
|
---|
486 | for (int i = 0; i < nops; i++) {
|
---|
487 | Node item = childNodes.item(i);
|
---|
488 | if (item.getNodeType() != Node.ELEMENT_NODE) continue;
|
---|
489 | String elementName = item.getNodeName();
|
---|
490 | Element elem = (Element) item;
|
---|
491 |
|
---|
492 | if ("var".equals(elementName)) {
|
---|
493 | setVar(elem.getAttribute("name"), evalVars(elem.getAttribute("value")));
|
---|
494 | } else if ("task".equals(elementName)) {
|
---|
495 | tasksMap.put(elem.getAttribute("name"), elem);
|
---|
496 | } else if ("runtask".equals(elementName)) {
|
---|
497 | if (processRunTaskElement(elem)) return;
|
---|
498 | } else if ("ask".equals(elementName)) {
|
---|
499 | processAskElement(elem);
|
---|
500 | } else if ("if".equals(elementName)) {
|
---|
501 | processIfElement(elem);
|
---|
502 | } else if ("else".equals(elementName)) {
|
---|
503 | processElseElement(elem);
|
---|
504 | } else if ("break".equals(elementName)) {
|
---|
505 | return;
|
---|
506 | } else if ("plugin".equals(elementName)) {
|
---|
507 | processPluginInstallElement(elem);
|
---|
508 | } else if ("messagebox".equals(elementName)){
|
---|
509 | processMsgBoxElement(elem);
|
---|
510 | } else if ("preferences".equals(elementName)) {
|
---|
511 | processPreferencesElement(elem);
|
---|
512 | } else if ("download".equals(elementName)) {
|
---|
513 | processDownloadElement(elem);
|
---|
514 | } else if ("delete".equals(elementName)) {
|
---|
515 | processDeleteElement(elem);
|
---|
516 | } else if ("script".equals(elementName)) {
|
---|
517 | processScriptElement(elem);
|
---|
518 | } else {
|
---|
519 | log("Error: Unknown element " + elementName);
|
---|
520 | }
|
---|
521 |
|
---|
522 | }
|
---|
523 | }
|
---|
524 |
|
---|
525 |
|
---|
526 |
|
---|
527 | private void processPreferencesElement(Element item) {
|
---|
528 | String oper = evalVars(item.getAttribute("operation"));
|
---|
529 | String id = evalVars(item.getAttribute("id"));
|
---|
530 |
|
---|
531 |
|
---|
532 | if ("delete-keys".equals(oper)) {
|
---|
533 | String pattern = evalVars(item.getAttribute("pattern"));
|
---|
534 | String key = evalVars(item.getAttribute("key"));
|
---|
535 | if (key != null) {
|
---|
536 | PreferencesUtils.deletePreferenceKey(key, mainPrefs);
|
---|
537 | }
|
---|
538 | if (pattern != null) {
|
---|
539 | PreferencesUtils.deletePreferenceKeyByPattern(pattern, mainPrefs);
|
---|
540 | }
|
---|
541 | return;
|
---|
542 | }
|
---|
543 |
|
---|
544 | Preferences tmpPref = readPreferencesFromDOMElement(item);
|
---|
545 | PreferencesUtils.showPrefs(tmpPref);
|
---|
546 |
|
---|
547 | if (id.length()>0) {
|
---|
548 | try {
|
---|
549 | String fragmentVar = "API.fragments['"+id+"']";
|
---|
550 | engine.eval(fragmentVar+"={};");
|
---|
551 | PreferencesUtils.loadPrefsToJS(engine, tmpPref, fragmentVar, false);
|
---|
552 | // we store this fragment as API.fragments['id']
|
---|
553 | } catch (ScriptException ex) {
|
---|
554 | log("Error: can not load preferences fragment : "+ex.getMessage());
|
---|
555 | }
|
---|
556 | }
|
---|
557 |
|
---|
558 | if ("replace".equals(oper)) {
|
---|
559 | log("Preferences replace: %d keys: %s\n",
|
---|
560 | tmpPref.getAllSettings().size(), tmpPref.getAllSettings().keySet().toString());
|
---|
561 | PreferencesUtils.replacePreferences(tmpPref, mainPrefs);
|
---|
562 | } else if ("append".equals(oper)) {
|
---|
563 | log("Preferences append: %d keys: %s\n",
|
---|
564 | tmpPref.getAllSettings().size(), tmpPref.getAllSettings().keySet().toString());
|
---|
565 | PreferencesUtils.appendPreferences(tmpPref, mainPrefs);
|
---|
566 | } else if ("delete-values".equals(oper)) {
|
---|
567 | PreferencesUtils.deletePreferenceValues(tmpPref, mainPrefs);
|
---|
568 | }
|
---|
569 | }
|
---|
570 |
|
---|
571 | private void processDeleteElement(Element item) {
|
---|
572 | String path = evalVars(item.getAttribute("path"));
|
---|
573 | String base = evalVars(item.getAttribute("base"));
|
---|
574 | deleteFile(base, path);
|
---|
575 | }
|
---|
576 |
|
---|
577 | private void processDownloadElement(Element item) {
|
---|
578 | String address = evalVars(item.getAttribute("url"));
|
---|
579 | String path = evalVars(item.getAttribute("path"));
|
---|
580 | String unzip = evalVars(item.getAttribute("unzip"));
|
---|
581 | String mkdir = evalVars(item.getAttribute("mkdir"));
|
---|
582 |
|
---|
583 | String base = evalVars(item.getAttribute("base"));
|
---|
584 | String dir = getDirectoryByAbbr(base);
|
---|
585 | if (dir==null) {
|
---|
586 | log("Error: Can not find directory to place file, use base=cache, base=prefs or base=plugins attribute.");
|
---|
587 | return;
|
---|
588 | }
|
---|
589 |
|
---|
590 | if (path.contains("..") || path.startsWith("/") || path.contains(":")) {
|
---|
591 | return; // some basic protection
|
---|
592 | }
|
---|
593 | if (address == null || path == null || address.length() == 0 || path.length() == 0) {
|
---|
594 | log("Error: Please specify url=\"where to get file\" and path=\"where to place it\"");
|
---|
595 | return;
|
---|
596 | }
|
---|
597 | processDownloadOperation(address, path, dir, "true".equals(mkdir), "true".equals(unzip));
|
---|
598 | }
|
---|
599 |
|
---|
600 | private void processPluginInstallElement(Element elem) {
|
---|
601 | String install = elem.getAttribute("install");
|
---|
602 | String uninstall = elem.getAttribute("remove");
|
---|
603 | String delete = elem.getAttribute("delete");
|
---|
604 | pluginOperation(install, uninstall, delete);
|
---|
605 | }
|
---|
606 |
|
---|
607 | private void processMsgBoxElement(Element elem) {
|
---|
608 | String text = evalVars(elem.getAttribute("text"));
|
---|
609 | String locText = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".text"));
|
---|
610 | if (locText!=null && locText.length()>0) text=locText;
|
---|
611 |
|
---|
612 | String type = evalVars(elem.getAttribute("type"));
|
---|
613 | messageBox(type, text);
|
---|
614 | }
|
---|
615 |
|
---|
616 |
|
---|
617 | private void processAskElement(Element elem) {
|
---|
618 | String text = evalVars(elem.getAttribute("text"));
|
---|
619 | String locText = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".text"));
|
---|
620 | if (locText.length()>0) text=locText;
|
---|
621 | String var = elem.getAttribute("var");
|
---|
622 | if (var.length()==0) var="result";
|
---|
623 |
|
---|
624 | String input = evalVars(elem.getAttribute("input"));
|
---|
625 | if ("true".equals(input)) {
|
---|
626 | setVar(var, askForText(text));
|
---|
627 | } else {
|
---|
628 | String opts = evalVars(elem.getAttribute("options"));
|
---|
629 | String locOpts = evalVars(elem.getAttribute(LanguageInfo.getJOSMLocaleCode()+".options"));
|
---|
630 | if (locOpts.length()>0) opts=locOpts;
|
---|
631 | setVar(var, String.valueOf(askForOption(text, opts)));
|
---|
632 | }
|
---|
633 | }
|
---|
634 |
|
---|
635 | public void setVar(String name, String value) {
|
---|
636 | try {
|
---|
637 | engine.eval(name+"='"+value+"';");
|
---|
638 | } catch (ScriptException ex) {
|
---|
639 | log("Error: Can not assign variable: %s=%s : %s\n", name, value, ex.getMessage());
|
---|
640 | }
|
---|
641 | }
|
---|
642 |
|
---|
643 | private void processIfElement(Element elem) {
|
---|
644 | String realValue = evalVars(elem.getAttribute("test"));
|
---|
645 | boolean v=false;
|
---|
646 | if ("true".equals(realValue)) v=true; else
|
---|
647 | if ("fales".equals(realValue)) v=true; else
|
---|
648 | {
|
---|
649 | log("Error: Illegal test expression in if: %s=%s\n", elem.getAttribute("test"), realValue);
|
---|
650 | }
|
---|
651 |
|
---|
652 | if (v) processXmlFragment(elem);
|
---|
653 | lastV = v;
|
---|
654 | }
|
---|
655 |
|
---|
656 | private void processElseElement(Element elem) {
|
---|
657 | if (!lastV) {
|
---|
658 | processXmlFragment(elem);
|
---|
659 | }
|
---|
660 | }
|
---|
661 |
|
---|
662 | private boolean processRunTaskElement(Element elem) {
|
---|
663 | String taskName = elem.getAttribute("name");
|
---|
664 | Element task = tasksMap.get(taskName);
|
---|
665 | if (task!=null) {
|
---|
666 | log("EXECUTING TASK "+taskName);
|
---|
667 | processXmlFragment(task); // process task recursively
|
---|
668 | } else {
|
---|
669 | log("Error: Can not execute task "+taskName);
|
---|
670 | return true;
|
---|
671 | }
|
---|
672 | return false;
|
---|
673 | }
|
---|
674 |
|
---|
675 |
|
---|
676 | private void processScriptElement(Element elem) {
|
---|
677 | String js = elem.getChildNodes().item(0).getTextContent();
|
---|
678 | log("Processing script...");
|
---|
679 | try {
|
---|
680 | PreferencesUtils.modifyPreferencesByScript(engine, mainPrefs, js);
|
---|
681 | } catch (ScriptException ex) {
|
---|
682 | messageBox("e", ex.getMessage());
|
---|
683 | log("JS error: "+ex.getMessage());
|
---|
684 | }
|
---|
685 | log("Script finished");
|
---|
686 | }
|
---|
687 |
|
---|
688 | /**
|
---|
689 | * substitute ${expression} = expression evaluated by JavaScript
|
---|
690 | */
|
---|
691 | private String evalVars(String s) {
|
---|
692 | Pattern p = Pattern.compile("\\$\\{([^\\}]*)\\}");
|
---|
693 | Matcher mr = p.matcher(s);
|
---|
694 | StringBuffer sb = new StringBuffer();
|
---|
695 | while (mr.find()) {
|
---|
696 | try {
|
---|
697 | String result = engine.eval(mr.group(1)).toString();
|
---|
698 | mr.appendReplacement(sb, result);
|
---|
699 | } catch (ScriptException ex) {
|
---|
700 | log("Error: Can not evaluate expression %s : %s", mr.group(1), ex.getMessage());
|
---|
701 | }
|
---|
702 | }
|
---|
703 | mr.appendTail(sb);
|
---|
704 | return sb.toString();
|
---|
705 | }
|
---|
706 |
|
---|
707 | private Preferences readPreferencesFromDOMElement(Element item) {
|
---|
708 | Preferences tmpPref = new Preferences();
|
---|
709 | try {
|
---|
710 | Transformer xformer = TransformerFactory.newInstance().newTransformer();
|
---|
711 | CharArrayWriter outputWriter = new CharArrayWriter(8192);
|
---|
712 | StreamResult out = new StreamResult(outputWriter);
|
---|
713 |
|
---|
714 | xformer.transform(new DOMSource(item), out);
|
---|
715 |
|
---|
716 | String fragmentWithReplacedVars= evalVars(outputWriter.toString());
|
---|
717 |
|
---|
718 | CharArrayReader reader = new CharArrayReader(fragmentWithReplacedVars.toCharArray());
|
---|
719 | tmpPref.fromXML(reader);
|
---|
720 | } catch (Exception ex) {
|
---|
721 | log("Error: can not read XML fragment :" + ex.getMessage());
|
---|
722 | }
|
---|
723 |
|
---|
724 | return tmpPref;
|
---|
725 | }
|
---|
726 |
|
---|
727 | private String normalizeDirName(String dir) {
|
---|
728 | String s = dir.replace("\\", "/");
|
---|
729 | if (s.endsWith("/")) s=s.substring(0,s.length()-1);
|
---|
730 | return s;
|
---|
731 | }
|
---|
732 |
|
---|
733 |
|
---|
734 | }
|
---|
735 |
|
---|
736 | /**
|
---|
737 | * Helper class to do specific Preferences operation - appending, replacing,
|
---|
738 | * deletion by key and by value
|
---|
739 | * Also contains functions that convert preferences object to JavaScript object and back
|
---|
740 | */
|
---|
741 | public static class PreferencesUtils {
|
---|
742 |
|
---|
743 | private static void replacePreferences(Preferences fragment, Preferences mainpref) {
|
---|
744 | for (Entry<String, Setting> entry: fragment.settingsMap.entrySet()) {
|
---|
745 | mainpref.putSetting(entry.getKey(), entry.getValue());
|
---|
746 | }
|
---|
747 | }
|
---|
748 |
|
---|
749 | private static void appendPreferences(Preferences fragment, Preferences mainpref) {
|
---|
750 | for (Entry<String, Setting> entry: fragment.settingsMap.entrySet()) {
|
---|
751 | String key = entry.getKey();
|
---|
752 | if (entry.getValue() instanceof StringSetting) {
|
---|
753 | mainpref.putSetting(key, entry.getValue());
|
---|
754 | } else if (entry.getValue() instanceof ListSetting) {
|
---|
755 | ListSetting lSetting = (ListSetting) entry.getValue();
|
---|
756 | Collection<String> newItems = getCollection(mainpref, key, true);
|
---|
757 | if (newItems == null) continue;
|
---|
758 | for (String item : lSetting.getValue()) {
|
---|
759 | // add nonexisting elements to then list
|
---|
760 | if (!newItems.contains(item)) {
|
---|
761 | newItems.add(item);
|
---|
762 | }
|
---|
763 | }
|
---|
764 | mainpref.putCollection(key, newItems);
|
---|
765 | } else if (entry.getValue() instanceof ListListSetting) {
|
---|
766 | ListListSetting llSetting = (ListListSetting) entry.getValue();
|
---|
767 | Collection<Collection<String>> newLists = getArray(mainpref, key, true);
|
---|
768 | if (newLists == null) continue;
|
---|
769 |
|
---|
770 | for (Collection<String> list : llSetting.getValue()) {
|
---|
771 | // add nonexisting list (equals comparison for lists is used implicitly)
|
---|
772 | if (!newLists.contains(list)) {
|
---|
773 | newLists.add(list);
|
---|
774 | }
|
---|
775 | }
|
---|
776 | mainpref.putArray(key, newLists);
|
---|
777 | } else if (entry.getValue() instanceof MapListSetting) {
|
---|
778 | MapListSetting mlSetting = (MapListSetting) entry.getValue();
|
---|
779 | List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
|
---|
780 | if (newMaps == null) continue;
|
---|
781 |
|
---|
782 | // get existing properties as list of maps
|
---|
783 |
|
---|
784 | for (Map<String, String> map : mlSetting.getValue()) {
|
---|
785 | // add nonexisting map (equals comparison for maps is used implicitly)
|
---|
786 | if (!newMaps.contains(map)) {
|
---|
787 | newMaps.add(map);
|
---|
788 | }
|
---|
789 | }
|
---|
790 | mainpref.putListOfStructs(entry.getKey(), newMaps);
|
---|
791 | }
|
---|
792 | }
|
---|
793 | }
|
---|
794 |
|
---|
795 | /**
|
---|
796 | * Delete items from @param mainpref collections that match items from @param fragment collections
|
---|
797 | */
|
---|
798 | private static void deletePreferenceValues(Preferences fragment, Preferences mainpref) {
|
---|
799 |
|
---|
800 | for (Entry<String, Setting> entry : fragment.settingsMap.entrySet()) {
|
---|
801 | String key = entry.getKey();
|
---|
802 | if (entry.getValue() instanceof StringSetting) {
|
---|
803 | StringSetting sSetting = (StringSetting) entry.getValue();
|
---|
804 | // if mentioned value found, delete it
|
---|
805 | if (sSetting.equals(mainpref.settingsMap.get(key))) {
|
---|
806 | mainpref.put(key, null);
|
---|
807 | }
|
---|
808 | } else if (entry.getValue() instanceof ListSetting) {
|
---|
809 | ListSetting lSetting = (ListSetting) entry.getValue();
|
---|
810 | Collection<String> newItems = getCollection(mainpref, key, true);
|
---|
811 | if (newItems == null) continue;
|
---|
812 |
|
---|
813 | // remove mentioned items from collection
|
---|
814 | for (String item : lSetting.getValue()) {
|
---|
815 | log("Deleting preferences: from list %s: %s\n", key, item);
|
---|
816 | newItems.remove(item);
|
---|
817 | }
|
---|
818 | mainpref.putCollection(entry.getKey(), newItems);
|
---|
819 | } else if (entry.getValue() instanceof ListListSetting) {
|
---|
820 | ListListSetting llSetting = (ListListSetting) entry.getValue();
|
---|
821 | Collection<Collection<String>> newLists = getArray(mainpref, key, true);
|
---|
822 | if (newLists == null) continue;
|
---|
823 |
|
---|
824 | // if items are found in one of lists, remove that list!
|
---|
825 | Iterator<Collection<String>> listIterator = newLists.iterator();
|
---|
826 | while (listIterator.hasNext()) {
|
---|
827 | Collection<String> list = listIterator.next();
|
---|
828 | for (Collection<String> removeList : llSetting.getValue()) {
|
---|
829 | if (list.containsAll(removeList)) {
|
---|
830 | // remove current list, because it matches search criteria
|
---|
831 | log("Deleting preferences: list from lists %s: %s\n", key, list);
|
---|
832 | listIterator.remove();
|
---|
833 | }
|
---|
834 | }
|
---|
835 | }
|
---|
836 |
|
---|
837 | mainpref.putArray(key, newLists);
|
---|
838 | } else if (entry.getValue() instanceof MapListSetting) {
|
---|
839 | MapListSetting mlSetting = (MapListSetting) entry.getValue();
|
---|
840 | List<Map<String, String>> newMaps = getListOfStructs(mainpref, key, true);
|
---|
841 | if (newMaps == null) continue;
|
---|
842 |
|
---|
843 | Iterator<Map<String, String>> mapIterator = newMaps.iterator();
|
---|
844 | while (mapIterator.hasNext()) {
|
---|
845 | Map<String, String> map = mapIterator.next();
|
---|
846 | for (Map<String, String> removeMap : mlSetting.getValue()) {
|
---|
847 | if (map.entrySet().containsAll(removeMap.entrySet())) {
|
---|
848 | // the map contain all mentioned key-value pair, so it should be deleted from "maps"
|
---|
849 | log("Deleting preferences: deleting map from maps %s: %s\n", key, map);
|
---|
850 | mapIterator.remove();
|
---|
851 | }
|
---|
852 | }
|
---|
853 | }
|
---|
854 | mainpref.putListOfStructs(entry.getKey(), newMaps);
|
---|
855 | }
|
---|
856 | }
|
---|
857 | }
|
---|
858 |
|
---|
859 | private static void deletePreferenceKeyByPattern(String pattern, Preferences pref) {
|
---|
860 | Map<String, Setting> allSettings = pref.getAllSettings();
|
---|
861 | for (Entry<String, Setting> entry : allSettings.entrySet()) {
|
---|
862 | String key = entry.getKey();
|
---|
863 | if (key.matches(pattern)) {
|
---|
864 | log("Deleting preferences: deleting key from preferences: " + key);
|
---|
865 | pref.putSetting(key, null);
|
---|
866 | }
|
---|
867 | }
|
---|
868 | }
|
---|
869 |
|
---|
870 | private static void deletePreferenceKey(String key, Preferences pref) {
|
---|
871 | Map<String, Setting> allSettings = pref.getAllSettings();
|
---|
872 | if (allSettings.containsKey(key)) {
|
---|
873 | log("Deleting preferences: deleting key from preferences: " + key);
|
---|
874 | pref.putSetting(key, null);
|
---|
875 | }
|
---|
876 | }
|
---|
877 |
|
---|
878 | private static Collection<String> getCollection(Preferences mainpref, String key, boolean warnUnknownDefault) {
|
---|
879 | ListSetting existing = Utils.cast(mainpref.settingsMap.get(key), ListSetting.class);
|
---|
880 | ListSetting defaults = Utils.cast(mainpref.defaultsMap.get(key), ListSetting.class);
|
---|
881 | if (existing == null && defaults == null) {
|
---|
882 | if (warnUnknownDefault) defaultUnknownWarning(key);
|
---|
883 | return null;
|
---|
884 | }
|
---|
885 | if (existing != null)
|
---|
886 | return new ArrayList<String>(existing.getValue());
|
---|
887 | else
|
---|
888 | return defaults.getValue() == null ? null : new ArrayList<String>(defaults.getValue());
|
---|
889 | }
|
---|
890 |
|
---|
891 | private static Collection<Collection<String>> getArray(Preferences mainpref, String key, boolean warnUnknownDefault) {
|
---|
892 | ListListSetting existing = Utils.cast(mainpref.settingsMap.get(key), ListListSetting.class);
|
---|
893 | ListListSetting defaults = Utils.cast(mainpref.defaultsMap.get(key), ListListSetting.class);
|
---|
894 |
|
---|
895 | if (existing == null && defaults == null) {
|
---|
896 | if (warnUnknownDefault) defaultUnknownWarning(key);
|
---|
897 | return null;
|
---|
898 | }
|
---|
899 | if (existing != null)
|
---|
900 | return new ArrayList<Collection<String>>(existing.getValue());
|
---|
901 | else
|
---|
902 | return defaults.getValue() == null ? null : new ArrayList<Collection<String>>(defaults.getValue());
|
---|
903 | }
|
---|
904 |
|
---|
905 | private static List<Map<String, String>> getListOfStructs(Preferences mainpref, String key, boolean warnUnknownDefault) {
|
---|
906 | MapListSetting existing = Utils.cast(mainpref.settingsMap.get(key), MapListSetting.class);
|
---|
907 | MapListSetting defaults = Utils.cast(mainpref.settingsMap.get(key), MapListSetting.class);
|
---|
908 |
|
---|
909 | if (existing == null && defaults == null) {
|
---|
910 | if (warnUnknownDefault) defaultUnknownWarning(key);
|
---|
911 | return null;
|
---|
912 | }
|
---|
913 |
|
---|
914 | if (existing != null)
|
---|
915 | return new ArrayList<Map<String, String>>(existing.getValue());
|
---|
916 | else
|
---|
917 | return defaults.getValue() == null ? null : new ArrayList<Map<String, String>>(defaults.getValue());
|
---|
918 | }
|
---|
919 |
|
---|
920 | private static void defaultUnknownWarning(String key) {
|
---|
921 | log("Warning: Unknown default value of %s , skipped\n", key);
|
---|
922 | JOptionPane.showMessageDialog(
|
---|
923 | Main.parent,
|
---|
924 | tr("<html>Settings file asks to append preferences to <b>{0}</b>,<br/> but its default value is unknown at this moment.<br/> Please activate corresponding function manually and retry importing.", key),
|
---|
925 | tr("Warning"),
|
---|
926 | JOptionPane.WARNING_MESSAGE);
|
---|
927 | }
|
---|
928 |
|
---|
929 | private static void showPrefs(Preferences tmpPref) {
|
---|
930 | Main.info("properties: " + tmpPref.settingsMap);
|
---|
931 | }
|
---|
932 |
|
---|
933 | private static void modifyPreferencesByScript(ScriptEngine engine, Preferences tmpPref, String js) throws ScriptException {
|
---|
934 | loadPrefsToJS(engine, tmpPref, "API.pref", true);
|
---|
935 | engine.eval(js);
|
---|
936 | readPrefsFromJS(engine, tmpPref, "API.pref");
|
---|
937 | }
|
---|
938 |
|
---|
939 | /**
|
---|
940 | * Convert JavaScript preferences object to preferences data structures
|
---|
941 | * @param engine - JS engine to put object
|
---|
942 | * @param tmpPref - preferences to fill from JS
|
---|
943 | * @param varInJS - JS variable name, where preferences are stored
|
---|
944 | * @throws ScriptException
|
---|
945 | */
|
---|
946 | public static void readPrefsFromJS(ScriptEngine engine, Preferences tmpPref, String varInJS) throws ScriptException {
|
---|
947 | String finish =
|
---|
948 | "stringMap = new java.util.TreeMap ;"+
|
---|
949 | "listMap = new java.util.TreeMap ;"+
|
---|
950 | "listlistMap = new java.util.TreeMap ;"+
|
---|
951 | "listmapMap = new java.util.TreeMap ;"+
|
---|
952 | "for (key in "+varInJS+") {"+
|
---|
953 | " val = "+varInJS+"[key];"+
|
---|
954 | " type = typeof val == 'string' ? 'string' : val.type;"+
|
---|
955 | " if (type == 'string') {"+
|
---|
956 | " stringMap.put(key, val);"+
|
---|
957 | " } else if (type == 'list') {"+
|
---|
958 | " l = new java.util.ArrayList;"+
|
---|
959 | " for (i=0; i<val.length; i++) {"+
|
---|
960 | " l.add(java.lang.String.valueOf(val[i]));"+
|
---|
961 | " }"+
|
---|
962 | " listMap.put(key, l);"+
|
---|
963 | " } else if (type == 'listlist') {"+
|
---|
964 | " l = new java.util.ArrayList;"+
|
---|
965 | " for (i=0; i<val.length; i++) {"+
|
---|
966 | " list=val[i];"+
|
---|
967 | " jlist=new java.util.ArrayList;"+
|
---|
968 | " for (j=0; j<list.length; j++) {"+
|
---|
969 | " jlist.add(java.lang.String.valueOf(list[j]));"+
|
---|
970 | " }"+
|
---|
971 | " l.add(jlist);"+
|
---|
972 | " }"+
|
---|
973 | " listlistMap.put(key, l);"+
|
---|
974 | " } else if (type == 'listmap') {"+
|
---|
975 | " l = new java.util.ArrayList;"+
|
---|
976 | " for (i=0; i<val.length; i++) {"+
|
---|
977 | " map=val[i];"+
|
---|
978 | " jmap=new java.util.TreeMap;"+
|
---|
979 | " for (var key2 in map) {"+
|
---|
980 | " jmap.put(key2,java.lang.String.valueOf(map[key2]));"+
|
---|
981 | " }"+
|
---|
982 | " l.add(jmap);"+
|
---|
983 | " }"+
|
---|
984 | " listmapMap.put(key, l);"+
|
---|
985 | " } else {" +
|
---|
986 | " org.openstreetmap.josm.data.CustomConfigurator.log('Unknown type:'+val.type+ '- use list, listlist or listmap'); }"+
|
---|
987 | " }";
|
---|
988 | engine.eval(finish);
|
---|
989 |
|
---|
990 | @SuppressWarnings("unchecked")
|
---|
991 | Map<String, String> stringMap = (Map<String, String>) engine.get("stringMap");
|
---|
992 | @SuppressWarnings("unchecked")
|
---|
993 | Map<String, List<String>> listMap = (SortedMap<String, List<String>> ) engine.get("listMap");
|
---|
994 | @SuppressWarnings("unchecked")
|
---|
995 | Map<String, List<Collection<String>>> listlistMap = (SortedMap<String, List<Collection<String>>>) engine.get("listlistMap");
|
---|
996 | @SuppressWarnings("unchecked")
|
---|
997 | Map<String, List<Map<String, String>>> listmapMap = (SortedMap<String, List<Map<String,String>>>) engine.get("listmapMap");
|
---|
998 |
|
---|
999 | tmpPref.settingsMap.clear();
|
---|
1000 |
|
---|
1001 | Map<String, Setting> tmp = new HashMap<String, Setting>();
|
---|
1002 | for (Entry<String, String> e : stringMap.entrySet()) {
|
---|
1003 | tmp.put(e.getKey(), new StringSetting(e.getValue()));
|
---|
1004 | }
|
---|
1005 | for (Entry<String, List<String>> e : listMap.entrySet()) {
|
---|
1006 | tmp.put(e.getKey(), new ListSetting(e.getValue()));
|
---|
1007 | }
|
---|
1008 |
|
---|
1009 | for (Entry<String, List<Collection<String>>> e : listlistMap.entrySet()) {
|
---|
1010 | @SuppressWarnings("unchecked") List<List<String>> value = (List)e.getValue();
|
---|
1011 | tmp.put(e.getKey(), new ListListSetting(value));
|
---|
1012 | }
|
---|
1013 | for (Entry<String, List<Map<String, String>>> e : listmapMap.entrySet()) {
|
---|
1014 | tmp.put(e.getKey(), new MapListSetting(e.getValue()));
|
---|
1015 | }
|
---|
1016 | for (Entry<String, Setting> e : tmp.entrySet()) {
|
---|
1017 | if (e.getValue().equals(tmpPref.defaultsMap.get(e.getKey()))) continue;
|
---|
1018 | tmpPref.settingsMap.put(e.getKey(), e.getValue());
|
---|
1019 | }
|
---|
1020 | }
|
---|
1021 |
|
---|
1022 | /**
|
---|
1023 | * Convert preferences data structures to JavaScript object
|
---|
1024 | * @param engine - JS engine to put object
|
---|
1025 | * @param tmpPref - preferences to convert
|
---|
1026 | * @param whereToPutInJS - variable name to store preferences in JS
|
---|
1027 | * @param includeDefaults - include known default values to JS objects
|
---|
1028 | * @throws ScriptException
|
---|
1029 | */
|
---|
1030 | public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults) throws ScriptException {
|
---|
1031 | Map<String, String> stringMap = new TreeMap<String, String>();
|
---|
1032 | Map<String, List<String>> listMap = new TreeMap<String, List<String>>();
|
---|
1033 | Map<String, List<List<String>>> listlistMap = new TreeMap<String, List<List<String>>>();
|
---|
1034 | Map<String, List<Map<String, String>>> listmapMap = new TreeMap<String, List<Map<String, String>>>();
|
---|
1035 |
|
---|
1036 | if (includeDefaults) {
|
---|
1037 | for (Map.Entry<String, Setting> e: tmpPref.defaultsMap.entrySet()) {
|
---|
1038 | Setting setting = e.getValue();
|
---|
1039 | if (setting instanceof StringSetting) {
|
---|
1040 | stringMap.put(e.getKey(), ((StringSetting) setting).getValue());
|
---|
1041 | } else if (setting instanceof ListSetting) {
|
---|
1042 | listMap.put(e.getKey(), ((ListSetting) setting).getValue());
|
---|
1043 | } else if (setting instanceof ListListSetting) {
|
---|
1044 | listlistMap.put(e.getKey(), ((ListListSetting) setting).getValue());
|
---|
1045 | } else if (setting instanceof MapListSetting) {
|
---|
1046 | listmapMap.put(e.getKey(), ((MapListSetting) setting).getValue());
|
---|
1047 | }
|
---|
1048 | }
|
---|
1049 | }
|
---|
1050 | Iterator<Map.Entry<String, Setting>> it = tmpPref.settingsMap.entrySet().iterator();
|
---|
1051 | while (it.hasNext()) {
|
---|
1052 | Map.Entry<String, Setting> e = it.next();
|
---|
1053 | if (e.getValue().getValue() == null) {
|
---|
1054 | it.remove();
|
---|
1055 | }
|
---|
1056 | }
|
---|
1057 |
|
---|
1058 | for (Map.Entry<String, Setting> e: tmpPref.settingsMap.entrySet()) {
|
---|
1059 | Setting setting = e.getValue();
|
---|
1060 | if (setting instanceof StringSetting) {
|
---|
1061 | stringMap.put(e.getKey(), ((StringSetting) setting).getValue());
|
---|
1062 | } else if (setting instanceof ListSetting) {
|
---|
1063 | listMap.put(e.getKey(), ((ListSetting) setting).getValue());
|
---|
1064 | } else if (setting instanceof ListListSetting) {
|
---|
1065 | listlistMap.put(e.getKey(), ((ListListSetting) setting).getValue());
|
---|
1066 | } else if (setting instanceof MapListSetting) {
|
---|
1067 | listmapMap.put(e.getKey(), ((MapListSetting) setting).getValue());
|
---|
1068 | }
|
---|
1069 | }
|
---|
1070 |
|
---|
1071 | engine.put("stringMap", stringMap);
|
---|
1072 | engine.put("listMap", listMap);
|
---|
1073 | engine.put("listlistMap", listlistMap);
|
---|
1074 | engine.put("listmapMap", listmapMap);
|
---|
1075 |
|
---|
1076 | String init =
|
---|
1077 | "function getJSList( javaList ) {"+
|
---|
1078 | " var jsList; var i; "+
|
---|
1079 | " if (javaList == null) return null;"+
|
---|
1080 | "jsList = [];"+
|
---|
1081 | " for (i = 0; i < javaList.size(); i++) {"+
|
---|
1082 | " jsList.push(String(list.get(i)));"+
|
---|
1083 | " }"+
|
---|
1084 | "return jsList;"+
|
---|
1085 | "}"+
|
---|
1086 | "function getJSMap( javaMap ) {"+
|
---|
1087 | " var jsMap; var it; var e; "+
|
---|
1088 | " if (javaMap == null) return null;"+
|
---|
1089 | " jsMap = {};"+
|
---|
1090 | " for (it = javaMap.entrySet().iterator(); it.hasNext();) {"+
|
---|
1091 | " e = it.next();"+
|
---|
1092 | " jsMap[ String(e.getKey()) ] = String(e.getValue()); "+
|
---|
1093 | " }"+
|
---|
1094 | " return jsMap;"+
|
---|
1095 | "}"+
|
---|
1096 | "for (it = stringMap.entrySet().iterator(); it.hasNext();) {"+
|
---|
1097 | " e = it.next();"+
|
---|
1098 | whereToPutInJS+"[String(e.getKey())] = String(e.getValue());"+
|
---|
1099 | "}\n"+
|
---|
1100 | "for (it = listMap.entrySet().iterator(); it.hasNext();) {"+
|
---|
1101 | " e = it.next();"+
|
---|
1102 | " list = e.getValue();"+
|
---|
1103 | " jslist = getJSList(list);"+
|
---|
1104 | " jslist.type = 'list';"+
|
---|
1105 | whereToPutInJS+"[String(e.getKey())] = jslist;"+
|
---|
1106 | "}\n"+
|
---|
1107 | "for (it = listlistMap.entrySet().iterator(); it.hasNext(); ) {"+
|
---|
1108 | " e = it.next();"+
|
---|
1109 | " listlist = e.getValue();"+
|
---|
1110 | " jslistlist = [];"+
|
---|
1111 | " for (it2 = listlist.iterator(); it2.hasNext(); ) {"+
|
---|
1112 | " list = it2.next(); "+
|
---|
1113 | " jslistlist.push(getJSList(list));"+
|
---|
1114 | " }"+
|
---|
1115 | " jslistlist.type = 'listlist';"+
|
---|
1116 | whereToPutInJS+"[String(e.getKey())] = jslistlist;"+
|
---|
1117 | "}\n"+
|
---|
1118 | "for (it = listmapMap.entrySet().iterator(); it.hasNext();) {"+
|
---|
1119 | " e = it.next();"+
|
---|
1120 | " listmap = e.getValue();"+
|
---|
1121 | " jslistmap = [];"+
|
---|
1122 | " for (it2 = listmap.iterator(); it2.hasNext();) {"+
|
---|
1123 | " map = it2.next();"+
|
---|
1124 | " jslistmap.push(getJSMap(map));"+
|
---|
1125 | " }"+
|
---|
1126 | " jslistmap.type = 'listmap';"+
|
---|
1127 | whereToPutInJS+"[String(e.getKey())] = jslistmap;"+
|
---|
1128 | "}\n";
|
---|
1129 |
|
---|
1130 | // Execute conversion script
|
---|
1131 | engine.eval(init);
|
---|
1132 | }
|
---|
1133 | }
|
---|
1134 | }
|
---|