[7937] | 1 | // License: GPL. For details, see LICENSE file.
|
---|
| 2 | package org.openstreetmap.josm.tools;
|
---|
| 3 |
|
---|
| 4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
| 5 | import static org.openstreetmap.josm.tools.I18n.trn;
|
---|
| 6 |
|
---|
| 7 | import java.awt.GridBagLayout;
|
---|
| 8 | import java.util.Arrays;
|
---|
| 9 | import java.util.HashMap;
|
---|
| 10 | import java.util.Map;
|
---|
| 11 | import java.util.Map.Entry;
|
---|
| 12 | import java.util.regex.Matcher;
|
---|
| 13 | import java.util.regex.Pattern;
|
---|
| 14 |
|
---|
| 15 | import javax.swing.JLabel;
|
---|
| 16 | import javax.swing.JOptionPane;
|
---|
| 17 | import javax.swing.JPanel;
|
---|
| 18 |
|
---|
| 19 | import org.openstreetmap.josm.Main;
|
---|
| 20 | import org.openstreetmap.josm.gui.ExtendedDialog;
|
---|
[10604] | 21 | import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils;
|
---|
[7937] | 22 | import org.openstreetmap.josm.gui.help.HelpUtil;
|
---|
| 23 | import org.openstreetmap.josm.gui.widgets.UrlLabel;
|
---|
| 24 | import org.openstreetmap.josm.io.XmlWriter;
|
---|
| 25 | import org.openstreetmap.josm.tools.LanguageInfo.LocaleType;
|
---|
| 26 |
|
---|
| 27 | /**
|
---|
| 28 | * Class that helps to parse tags from arbitrary text
|
---|
| 29 | */
|
---|
| 30 | public final class TextTagParser {
|
---|
| 31 |
|
---|
| 32 | // properties need JOSM restart to apply, modified rarely enough
|
---|
[8468] | 33 | private static final int MAX_KEY_LENGTH = Main.pref.getInteger("tags.paste.max-key-length", 50);
|
---|
| 34 | private static final int MAX_KEY_COUNT = Main.pref.getInteger("tags.paste.max-key-count", 30);
|
---|
| 35 | private static final String KEY_PATTERN = Main.pref.get("tags.paste.tag-pattern", "[0-9a-zA-Z:_]*");
|
---|
| 36 | private static final int MAX_VALUE_LENGTH = 255;
|
---|
[7937] | 37 |
|
---|
| 38 | private TextTagParser() {
|
---|
| 39 | // Hide default constructor for utils classes
|
---|
| 40 | }
|
---|
| 41 |
|
---|
| 42 | public static class TextAnalyzer {
|
---|
[8840] | 43 | private boolean quotesStarted;
|
---|
| 44 | private boolean esc;
|
---|
[9078] | 45 | private final StringBuilder s = new StringBuilder(200);
|
---|
[8285] | 46 | private int pos;
|
---|
[9078] | 47 | private final String data;
|
---|
| 48 | private final int n;
|
---|
[7937] | 49 |
|
---|
| 50 | public TextAnalyzer(String text) {
|
---|
| 51 | pos = 0;
|
---|
| 52 | data = text;
|
---|
| 53 | n = data.length();
|
---|
| 54 | }
|
---|
| 55 |
|
---|
| 56 | /**
|
---|
| 57 | * Read tags from "Free format"
|
---|
[8928] | 58 | * @return map of tags
|
---|
[7937] | 59 | */
|
---|
[8928] | 60 | private Map<String, String> getFreeParsedTags() {
|
---|
[7937] | 61 | String k, v;
|
---|
| 62 | Map<String, String> tags = new HashMap<>();
|
---|
| 63 |
|
---|
| 64 | while (true) {
|
---|
| 65 | skipEmpty();
|
---|
[8513] | 66 | if (pos == n) {
|
---|
| 67 | break;
|
---|
| 68 | }
|
---|
[7937] | 69 | k = parseString("\n\r\t= ");
|
---|
[8513] | 70 | if (pos == n) {
|
---|
| 71 | tags.clear();
|
---|
| 72 | break;
|
---|
| 73 | }
|
---|
[7937] | 74 | skipSign();
|
---|
[8513] | 75 | if (pos == n) {
|
---|
| 76 | tags.clear();
|
---|
| 77 | break;
|
---|
| 78 | }
|
---|
[7937] | 79 | v = parseString("\n\r\t ");
|
---|
| 80 | tags.put(k, v);
|
---|
| 81 | }
|
---|
| 82 | return tags;
|
---|
| 83 | }
|
---|
| 84 |
|
---|
| 85 | private String parseString(String stopChars) {
|
---|
| 86 | char[] stop = stopChars.toCharArray();
|
---|
| 87 | Arrays.sort(stop);
|
---|
| 88 | char c;
|
---|
| 89 | while (pos < n) {
|
---|
| 90 | c = data.charAt(pos);
|
---|
| 91 | if (esc) {
|
---|
| 92 | esc = false;
|
---|
| 93 | s.append(c); // \" \\
|
---|
| 94 | } else if (c == '\\') {
|
---|
| 95 | esc = true;
|
---|
| 96 | } else if (c == '\"' && !quotesStarted) { // opening "
|
---|
[8461] | 97 | if (!s.toString().trim().isEmpty()) { // we had ||some text"||
|
---|
[7937] | 98 | s.append(c); // just add ", not open
|
---|
| 99 | } else {
|
---|
| 100 | s.delete(0, s.length()); // forget that empty characthers and start reading "....
|
---|
| 101 | quotesStarted = true;
|
---|
| 102 | }
|
---|
| 103 | } else if (c == '\"' && quotesStarted) { // closing "
|
---|
| 104 | quotesStarted = false;
|
---|
| 105 | pos++;
|
---|
| 106 | break;
|
---|
[8510] | 107 | } else if (!quotesStarted && (Arrays.binarySearch(stop, c) >= 0)) {
|
---|
[7937] | 108 | // stop-symbol found
|
---|
| 109 | pos++;
|
---|
| 110 | break;
|
---|
| 111 | } else {
|
---|
| 112 | // skip non-printable characters
|
---|
[8510] | 113 | if (c >= 32) s.append(c);
|
---|
[7937] | 114 | }
|
---|
| 115 | pos++;
|
---|
| 116 | }
|
---|
| 117 |
|
---|
| 118 | String res = s.toString();
|
---|
| 119 | s.delete(0, s.length());
|
---|
| 120 | return res.trim();
|
---|
| 121 | }
|
---|
| 122 |
|
---|
| 123 | private void skipSign() {
|
---|
| 124 | char c;
|
---|
| 125 | boolean signFound = false;
|
---|
| 126 | while (pos < n) {
|
---|
| 127 | c = data.charAt(pos);
|
---|
[10378] | 128 | if (c == '\t' || c == '\n' || c == ' ') {
|
---|
[7937] | 129 | pos++;
|
---|
[8510] | 130 | } else if (c == '=') {
|
---|
[7937] | 131 | if (signFound) break; // a = =qwerty means "a"="=qwerty"
|
---|
| 132 | signFound = true;
|
---|
| 133 | pos++;
|
---|
| 134 | } else {
|
---|
| 135 | break;
|
---|
| 136 | }
|
---|
| 137 | }
|
---|
| 138 | }
|
---|
| 139 |
|
---|
| 140 | private void skipEmpty() {
|
---|
| 141 | char c;
|
---|
| 142 | while (pos < n) {
|
---|
| 143 | c = data.charAt(pos);
|
---|
[8443] | 144 | if (c == '\t' || c == '\n' || c == '\r' || c == ' ') {
|
---|
[7937] | 145 | pos++;
|
---|
| 146 | } else {
|
---|
| 147 | break;
|
---|
| 148 | }
|
---|
| 149 | }
|
---|
| 150 | }
|
---|
| 151 | }
|
---|
| 152 |
|
---|
[10763] | 153 | static String unescape(String k) {
|
---|
[8443] | 154 | if (!(k.startsWith("\"") && k.endsWith("\""))) {
|
---|
[7937] | 155 | if (k.contains("=")) {
|
---|
| 156 | // '=' not in quotes will be treated as an error!
|
---|
| 157 | return null;
|
---|
| 158 | } else {
|
---|
| 159 | return k;
|
---|
| 160 | }
|
---|
| 161 | }
|
---|
[8510] | 162 | String text = k.substring(1, k.length()-1);
|
---|
[7937] | 163 | return (new TextAnalyzer(text)).parseString("\r\t\n");
|
---|
| 164 | }
|
---|
| 165 |
|
---|
| 166 | /**
|
---|
| 167 | * Try to find tag-value pairs in given text
|
---|
| 168 | * @param text - text in which tags are looked for
|
---|
| 169 | * @param splitRegex - text is splitted into parts with this delimiter
|
---|
| 170 | * @param tagRegex - each part is matched against this regex
|
---|
| 171 | * @param unescapeTextInQuotes - if true, matched tag and value will be analyzed more thoroughly
|
---|
[8928] | 172 | * @return map of tags
|
---|
[7937] | 173 | */
|
---|
| 174 | public static Map<String, String> readTagsByRegexp(String text, String splitRegex, String tagRegex, boolean unescapeTextInQuotes) {
|
---|
| 175 | String[] lines = text.split(splitRegex);
|
---|
| 176 | Pattern p = Pattern.compile(tagRegex);
|
---|
| 177 | Map<String, String> tags = new HashMap<>();
|
---|
[10308] | 178 | String k;
|
---|
| 179 | String v;
|
---|
[10378] | 180 | for (String line: lines) {
|
---|
[7937] | 181 | if (line.trim().isEmpty()) continue; // skip empty lines
|
---|
| 182 | Matcher m = p.matcher(line);
|
---|
| 183 | if (m.matches()) {
|
---|
[8510] | 184 | k = m.group(1).trim();
|
---|
| 185 | v = m.group(2).trim();
|
---|
[7937] | 186 | if (unescapeTextInQuotes) {
|
---|
| 187 | k = unescape(k);
|
---|
| 188 | v = unescape(v);
|
---|
[8510] | 189 | if (k == null || v == null) return null;
|
---|
[7937] | 190 | }
|
---|
[8510] | 191 | tags.put(k, v);
|
---|
[7937] | 192 | } else {
|
---|
| 193 | return null;
|
---|
| 194 | }
|
---|
| 195 | }
|
---|
| 196 | if (!tags.isEmpty()) {
|
---|
| 197 | return tags;
|
---|
[10378] | 198 | } else {
|
---|
[7937] | 199 | return null;
|
---|
| 200 | }
|
---|
| 201 | }
|
---|
| 202 |
|
---|
[8510] | 203 | public static Map<String, String> getValidatedTagsFromText(String buf) {
|
---|
| 204 | Map<String, String> tags = readTagsFromText(buf);
|
---|
[7937] | 205 | return validateTags(tags) ? tags : null;
|
---|
| 206 | }
|
---|
| 207 |
|
---|
| 208 | /**
|
---|
| 209 | * Apply different methods to extract tag-value pairs from arbitrary text
|
---|
[8470] | 210 | * @param buf buffer
|
---|
[7937] | 211 | * @return null if no format is suitable
|
---|
| 212 | */
|
---|
[8510] | 213 | public static Map<String, String> readTagsFromText(String buf) {
|
---|
| 214 | Map<String, String> tags;
|
---|
[7937] | 215 |
|
---|
| 216 | // Format
|
---|
| 217 | // tag1\tval1\ntag2\tval2\n
|
---|
[8482] | 218 | tags = readTagsByRegexp(buf, "[\\r\\n]+", ".*?([a-zA-Z0-9:_]+).*\\t(.*?)", false);
|
---|
[9073] | 219 | // try "tag\tvalue\n" format
|
---|
[8510] | 220 | if (tags != null) return tags;
|
---|
[7937] | 221 |
|
---|
| 222 | // Format
|
---|
| 223 | // a=b \n c=d \n "a b"=hello
|
---|
| 224 | // SORRY: "a=b" = c is not supported fror now, only first = will be considered
|
---|
| 225 | // a = "b=c" is OK
|
---|
| 226 | // a = b=c - this method of parsing fails intentionally
|
---|
| 227 | tags = readTagsByRegexp(buf, "[\\n\\t\\r]+", "(.*?)=(.*?)", true);
|
---|
[9073] | 228 | // try format t1=v1\n t2=v2\n ...
|
---|
[8510] | 229 | if (tags != null) return tags;
|
---|
[7937] | 230 |
|
---|
| 231 | // JSON-format
|
---|
| 232 | String bufJson = buf.trim();
|
---|
| 233 | // trim { }, if there are any
|
---|
[8443] | 234 | if (bufJson.startsWith("{") && bufJson.endsWith("}"))
|
---|
| 235 | bufJson = bufJson.substring(1, bufJson.length()-1);
|
---|
[7937] | 236 | tags = readTagsByRegexp(bufJson, "[\\s]*,[\\s]*",
|
---|
| 237 | "[\\s]*(\\\".*?[^\\\\]\\\")"+"[\\s]*:[\\s]*"+"(\\\".*?[^\\\\]\\\")[\\s]*", true);
|
---|
[8510] | 238 | if (tags != null) return tags;
|
---|
[7937] | 239 |
|
---|
| 240 | // Free format
|
---|
| 241 | // a 1 "b" 2 c=3 d 4 e "5"
|
---|
[8375] | 242 | return new TextAnalyzer(buf).getFreeParsedTags();
|
---|
[7937] | 243 | }
|
---|
| 244 |
|
---|
| 245 | /**
|
---|
| 246 | * Check tags for correctness and display warnings if needed
|
---|
| 247 | * @param tags - map key->value to check
|
---|
| 248 | * @return true if the tags should be pasted
|
---|
| 249 | */
|
---|
| 250 | public static boolean validateTags(Map<String, String> tags) {
|
---|
| 251 | int r;
|
---|
| 252 | int s = tags.size();
|
---|
| 253 | if (s > MAX_KEY_COUNT) {
|
---|
| 254 | // Use trn() even if for english it makes no sense, as s > 30
|
---|
[8510] | 255 | r = warning(trn("There was {0} tag found in the buffer, it is suspicious!",
|
---|
[7937] | 256 | "There were {0} tags found in the buffer, it is suspicious!", s,
|
---|
| 257 | s), "", "tags.paste.toomanytags");
|
---|
[8510] | 258 | if (r == 2 || r == 3) return false; if (r == 4) return true;
|
---|
[7937] | 259 | }
|
---|
| 260 | for (Entry<String, String> entry : tags.entrySet()) {
|
---|
| 261 | String key = entry.getKey();
|
---|
| 262 | String value = entry.getValue();
|
---|
| 263 | if (key.length() > MAX_KEY_LENGTH) {
|
---|
[8846] | 264 | r = warning(tr("Key is too long (max {0} characters):", MAX_KEY_LENGTH), key+'='+value, "tags.paste.keytoolong");
|
---|
[8510] | 265 | if (r == 2 || r == 3) return false; if (r == 4) return true;
|
---|
[7937] | 266 | }
|
---|
| 267 | if (!key.matches(KEY_PATTERN)) {
|
---|
| 268 | r = warning(tr("Suspicious characters in key:"), key, "tags.paste.keydoesnotmatch");
|
---|
[8510] | 269 | if (r == 2 || r == 3) return false; if (r == 4) return true;
|
---|
[7937] | 270 | }
|
---|
| 271 | if (value.length() > MAX_VALUE_LENGTH) {
|
---|
| 272 | r = warning(tr("Value is too long (max {0} characters):", MAX_VALUE_LENGTH), value, "tags.paste.valuetoolong");
|
---|
[8510] | 273 | if (r == 2 || r == 3) return false; if (r == 4) return true;
|
---|
[7937] | 274 | }
|
---|
| 275 | }
|
---|
| 276 | return true;
|
---|
| 277 | }
|
---|
| 278 |
|
---|
| 279 | private static int warning(String text, String data, String code) {
|
---|
| 280 | ExtendedDialog ed = new ExtendedDialog(
|
---|
| 281 | Main.parent,
|
---|
| 282 | tr("Do you want to paste these tags?"),
|
---|
[12279] | 283 | tr("Ok"), tr("Cancel"), tr("Clear buffer"), tr("Ignore warnings"));
|
---|
| 284 | ed.setButtonIcons("ok", "cancel", "dialogs/delete", "pastetags");
|
---|
[8510] | 285 | ed.setContent("<html><b>"+text + "</b><br/><br/><div width=\"300px\">"+XmlWriter.encode(data, true)+"</html>");
|
---|
[7937] | 286 | ed.setDefaultButton(2);
|
---|
| 287 | ed.setCancelButton(2);
|
---|
| 288 | ed.setIcon(JOptionPane.WARNING_MESSAGE);
|
---|
| 289 | ed.toggleEnable(code);
|
---|
| 290 | ed.showDialog();
|
---|
| 291 | int r = ed.getValue();
|
---|
[8510] | 292 | if (r == 0) r = 2;
|
---|
[7937] | 293 | // clean clipboard if user asked
|
---|
[10604] | 294 | if (r == 3) ClipboardUtils.copyString("");
|
---|
[7937] | 295 | return r;
|
---|
| 296 | }
|
---|
| 297 |
|
---|
| 298 | /**
|
---|
| 299 | * Shows message that the buffer can not be pasted, allowing user to clean the buffer
|
---|
| 300 | * @param helpTopic the help topic of the parent action
|
---|
| 301 | * TODO: Replace by proper HelpAwareOptionPane instead of self-made help link
|
---|
| 302 | */
|
---|
| 303 | public static void showBadBufferMessage(String helpTopic) {
|
---|
| 304 | String msg = tr("<html><p> Sorry, it is impossible to paste tags from buffer. It does not contain any JOSM object"
|
---|
| 305 | + " or suitable text. </p></html>");
|
---|
| 306 | JPanel p = new JPanel(new GridBagLayout());
|
---|
[8510] | 307 | p.add(new JLabel(msg), GBC.eop());
|
---|
[7937] | 308 | String helpUrl = HelpUtil.getHelpTopicUrl(HelpUtil.buildAbsoluteHelpTopic(helpTopic, LocaleType.DEFAULT));
|
---|
| 309 | if (helpUrl != null) {
|
---|
| 310 | p.add(new UrlLabel(helpUrl), GBC.eop());
|
---|
| 311 | }
|
---|
| 312 |
|
---|
| 313 | ExtendedDialog ed = new ExtendedDialog(
|
---|
| 314 | Main.parent,
|
---|
| 315 | tr("Warning"),
|
---|
[12279] | 316 | tr("Ok"), tr("Clear buffer"))
|
---|
| 317 | .setButtonIcons("ok", "dialogs/delete")
|
---|
| 318 | .setContent(p)
|
---|
| 319 | .setDefaultButton(1)
|
---|
| 320 | .setCancelButton(1)
|
---|
| 321 | .setIcon(JOptionPane.WARNING_MESSAGE)
|
---|
| 322 | .toggleEnable("tags.paste.cleanbadbuffer");
|
---|
[7937] | 323 |
|
---|
| 324 | ed.showDialog();
|
---|
| 325 |
|
---|
| 326 | // clean clipboard if user asked
|
---|
[12279] | 327 | if (ed.getValue() == 2) ClipboardUtils.copyString("");
|
---|
[7937] | 328 | }
|
---|
| 329 | }
|
---|