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