source: josm/trunk/src/org/openstreetmap/josm/tools/TextTagParser.java@ 6113

Last change on this file since 6113 was 6085, checked in by Don-vip, 11 years ago

see #8902 - c-like array definitions changed to java-like (patch by shinigami)

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