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