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