source: josm/trunk/src/org/openstreetmap/josm/gui/layer/NoteLayer.java@ 13437

Last change on this file since 13437 was 13437, checked in by Don-vip, 7 years ago

fix #15967 - proper loading of notes layers

  • Property svn:eol-style set to native
File size: 17.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui.layer;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5import static org.openstreetmap.josm.tools.I18n.trn;
6
7import java.awt.Color;
8import java.awt.Dimension;
9import java.awt.Graphics2D;
10import java.awt.Point;
11import java.awt.event.MouseEvent;
12import java.awt.event.MouseListener;
13import java.awt.event.MouseWheelEvent;
14import java.awt.event.MouseWheelListener;
15import java.io.File;
16import java.text.DateFormat;
17import java.util.ArrayList;
18import java.util.Collection;
19import java.util.Collections;
20import java.util.List;
21import java.util.regex.Matcher;
22import java.util.regex.Pattern;
23
24import javax.swing.Action;
25import javax.swing.BorderFactory;
26import javax.swing.Icon;
27import javax.swing.ImageIcon;
28import javax.swing.JEditorPane;
29import javax.swing.JWindow;
30import javax.swing.SwingUtilities;
31import javax.swing.UIManager;
32import javax.swing.plaf.basic.BasicHTML;
33import javax.swing.text.View;
34
35import org.openstreetmap.josm.Main;
36import org.openstreetmap.josm.actions.SaveActionBase;
37import org.openstreetmap.josm.data.Bounds;
38import org.openstreetmap.josm.data.notes.Note;
39import org.openstreetmap.josm.data.notes.Note.State;
40import org.openstreetmap.josm.data.notes.NoteComment;
41import org.openstreetmap.josm.data.osm.NoteData;
42import org.openstreetmap.josm.data.osm.NoteData.NoteDataUpdateListener;
43import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
44import org.openstreetmap.josm.gui.MainApplication;
45import org.openstreetmap.josm.gui.MainFrame;
46import org.openstreetmap.josm.gui.MapView;
47import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
48import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
49import org.openstreetmap.josm.gui.io.AbstractIOTask;
50import org.openstreetmap.josm.gui.io.UploadNoteLayerTask;
51import org.openstreetmap.josm.gui.io.importexport.NoteExporter;
52import org.openstreetmap.josm.gui.progress.ProgressMonitor;
53import org.openstreetmap.josm.gui.widgets.HtmlPanel;
54import org.openstreetmap.josm.io.XmlWriter;
55import org.openstreetmap.josm.spi.preferences.Config;
56import org.openstreetmap.josm.tools.ColorHelper;
57import org.openstreetmap.josm.tools.ImageProvider;
58import org.openstreetmap.josm.tools.Logging;
59import org.openstreetmap.josm.tools.date.DateUtils;
60
61/**
62 * A layer to hold Note objects.
63 * @since 7522
64 */
65public class NoteLayer extends AbstractModifiableLayer implements MouseListener, NoteDataUpdateListener {
66
67 /**
68 * Pattern to detect end of sentences followed by another one, or a link, in western script.
69 * Group 1 (capturing): period, interrogation mark, exclamation mark
70 * Group non capturing: at least one horizontal or vertical whitespace
71 * Group 2 (capturing): a letter (any script), or any punctuation
72 */
73 private static final Pattern SENTENCE_MARKS_WESTERN = Pattern.compile("([\\.\\?\\!])(?:[\\h\\v]+)([\\p{L}\\p{Punct}])");
74
75 /**
76 * Pattern to detect end of sentences followed by another one, or a link, in eastern script.
77 * Group 1 (capturing): ideographic full stop
78 * Group 2 (capturing): a letter (any script), or any punctuation
79 */
80 private static final Pattern SENTENCE_MARKS_EASTERN = Pattern.compile("(\\u3002)([\\p{L}\\p{Punct}])");
81
82 private static final Pattern HTTP_LINK = Pattern.compile("(https?://[^\\s\\(\\)<>]+)");
83 private static final Pattern HTML_LINK = Pattern.compile("<a href=\"[^\"]+\">([^<]+)</a>");
84 private static final Pattern HTML_LINK_MARK = Pattern.compile("<a href=\"([^\"]+)([\\.\\?\\!])\">([^<]+)(?:[\\.\\?\\!])</a>");
85 private static final Pattern SLASH = Pattern.compile("([^/])/([^/])");
86
87 private final NoteData noteData;
88
89 private Note displayedNote;
90 private HtmlPanel displayedPanel;
91 private JWindow displayedWindow;
92
93 /**
94 * Create a new note layer with a set of notes
95 * @param notes A list of notes to show in this layer
96 * @param name The name of the layer. Typically "Notes"
97 */
98 public NoteLayer(Collection<Note> notes, String name) {
99 super(name);
100 noteData = new NoteData(notes);
101 noteData.addNoteDataUpdateListener(this);
102 }
103
104 /** Convenience constructor that creates a layer with an empty note list */
105 public NoteLayer() {
106 this(Collections.<Note>emptySet(), tr("Notes"));
107 }
108
109 @Override
110 public void hookUpMapView() {
111 MainApplication.getMap().mapView.addMouseListener(this);
112 }
113
114 @Override
115 public synchronized void destroy() {
116 MainApplication.getMap().mapView.removeMouseListener(this);
117 noteData.removeNoteDataUpdateListener(this);
118 hideNoteWindow();
119 super.destroy();
120 }
121
122 /**
123 * Returns the note data store being used by this layer
124 * @return noteData containing layer notes
125 */
126 public NoteData getNoteData() {
127 return noteData;
128 }
129
130 @Override
131 public boolean isModified() {
132 return noteData.isModified();
133 }
134
135 @Override
136 public boolean isUploadable() {
137 return true;
138 }
139
140 @Override
141 public boolean requiresUploadToServer() {
142 return isModified();
143 }
144
145 @Override
146 public boolean isSavable() {
147 return true;
148 }
149
150 @Override
151 public boolean requiresSaveToFile() {
152 return getAssociatedFile() != null && isModified();
153 }
154
155 @Override
156 public void paint(Graphics2D g, MapView mv, Bounds box) {
157 final int iconHeight = ImageProvider.ImageSizes.SMALLICON.getAdjustedHeight();
158 final int iconWidth = ImageProvider.ImageSizes.SMALLICON.getAdjustedWidth();
159
160 for (Note note : noteData.getNotes()) {
161 Point p = mv.getPoint(note.getLatLon());
162
163 ImageIcon icon;
164 if (note.getId() < 0) {
165 icon = ImageProvider.get("dialogs/notes", "note_new", ImageProvider.ImageSizes.SMALLICON);
166 } else if (note.getState() == State.CLOSED) {
167 icon = ImageProvider.get("dialogs/notes", "note_closed", ImageProvider.ImageSizes.SMALLICON);
168 } else {
169 icon = ImageProvider.get("dialogs/notes", "note_open", ImageProvider.ImageSizes.SMALLICON);
170 }
171 int width = icon.getIconWidth();
172 int height = icon.getIconHeight();
173 g.drawImage(icon.getImage(), p.x - (width / 2), p.y - height, MainApplication.getMap().mapView);
174 }
175 Note selectedNote = noteData.getSelectedNote();
176 if (selectedNote != null) {
177 paintSelectedNote(g, mv, iconHeight, iconWidth, selectedNote);
178 } else {
179 hideNoteWindow();
180 }
181 }
182
183 private void hideNoteWindow() {
184 if (displayedWindow != null) {
185 displayedWindow.setVisible(false);
186 for (MouseWheelListener listener : displayedWindow.getMouseWheelListeners()) {
187 displayedWindow.removeMouseWheelListener(listener);
188 }
189 displayedWindow.dispose();
190 displayedWindow = null;
191 displayedPanel = null;
192 displayedNote = null;
193 }
194 }
195
196 private void paintSelectedNote(Graphics2D g, MapView mv, final int iconHeight, final int iconWidth, Note selectedNote) {
197 Point p = mv.getPoint(selectedNote.getLatLon());
198
199 g.setColor(ColorHelper.html2color(Config.getPref().get("color.selected")));
200 g.drawRect(p.x - (iconWidth / 2), p.y - iconHeight, iconWidth - 1, iconHeight - 1);
201
202 if (displayedNote != null && !displayedNote.equals(selectedNote)) {
203 hideNoteWindow();
204 }
205
206 int xl = p.x - (iconWidth / 2) - 5;
207 int xr = p.x + (iconWidth / 2) + 5;
208 int yb = p.y - iconHeight - 1;
209 int yt = p.y + (iconHeight / 2) + 2;
210 Point pTooltip;
211
212 String text = getNoteToolTip(selectedNote);
213
214 if (displayedWindow == null) {
215 displayedPanel = new HtmlPanel(text);
216 displayedPanel.setBackground(UIManager.getColor("ToolTip.background"));
217 displayedPanel.setForeground(UIManager.getColor("ToolTip.foreground"));
218 displayedPanel.setFont(UIManager.getFont("ToolTip.font"));
219 displayedPanel.setBorder(BorderFactory.createLineBorder(Color.black));
220 displayedPanel.enableClickableHyperlinks();
221 pTooltip = fixPanelSizeAndLocation(mv, text, xl, xr, yt, yb);
222 displayedWindow = new JWindow((MainFrame) Main.parent);
223 displayedWindow.setAutoRequestFocus(false);
224 displayedWindow.add(displayedPanel);
225 // Forward mouse wheel scroll event to MapMover
226 displayedWindow.addMouseWheelListener(e -> mv.getMapMover().mouseWheelMoved(
227 (MouseWheelEvent) SwingUtilities.convertMouseEvent(displayedWindow, e, mv)));
228 } else {
229 displayedPanel.setText(text);
230 pTooltip = fixPanelSizeAndLocation(mv, text, xl, xr, yt, yb);
231 }
232
233 displayedWindow.pack();
234 displayedWindow.setLocation(pTooltip);
235 displayedWindow.setVisible(mv.contains(p));
236 displayedNote = selectedNote;
237 }
238
239 private Point fixPanelSizeAndLocation(MapView mv, String text, int xl, int xr, int yt, int yb) {
240 int leftMaxWidth = (int) (0.95 * xl);
241 int rightMaxWidth = (int) (0.95 * mv.getWidth() - xr);
242 int topMaxHeight = (int) (0.95 * yt);
243 int bottomMaxHeight = (int) (0.95 * mv.getHeight() - yb);
244 int maxWidth = Math.max(leftMaxWidth, rightMaxWidth);
245 int maxHeight = Math.max(topMaxHeight, bottomMaxHeight);
246 JEditorPane pane = displayedPanel.getEditorPane();
247 Dimension d = pane.getPreferredSize();
248 if ((d.width > maxWidth || d.height > maxHeight) && Config.getPref().getBoolean("note.text.break-on-sentence-mark", false)) {
249 // To make sure long notes are displayed correctly
250 displayedPanel.setText(insertLineBreaks(text));
251 }
252 // If still too large, enforce maximum size
253 d = pane.getPreferredSize();
254 if (d.width > maxWidth || d.height > maxHeight) {
255 View v = (View) pane.getClientProperty(BasicHTML.propertyKey);
256 if (v == null) {
257 BasicHTML.updateRenderer(pane, text);
258 v = (View) pane.getClientProperty(BasicHTML.propertyKey);
259 }
260 if (v != null) {
261 v.setSize(maxWidth, 0);
262 int w = (int) Math.ceil(v.getPreferredSpan(View.X_AXIS));
263 int h = (int) Math.ceil(v.getPreferredSpan(View.Y_AXIS)) + 10;
264 pane.setPreferredSize(new Dimension(w, h));
265 }
266 }
267 d = pane.getPreferredSize();
268 // place tooltip on left or right side of icon, based on its width
269 Point screenloc = mv.getLocationOnScreen();
270 return new Point(
271 screenloc.x + (d.width > rightMaxWidth && d.width <= leftMaxWidth ? xl - d.width : xr),
272 screenloc.y + (d.height > bottomMaxHeight && d.height <= topMaxHeight ? yt - d.height - 10 : yb));
273 }
274
275 /**
276 * Inserts HTML line breaks ({@code <br>} at the end of each sentence mark
277 * (period, interrogation mark, exclamation mark, ideographic full stop).
278 * @param longText a long text that does not fit on a single line without exceeding half of the map view
279 * @return text with line breaks
280 */
281 static String insertLineBreaks(String longText) {
282 return SENTENCE_MARKS_WESTERN.matcher(SENTENCE_MARKS_EASTERN.matcher(longText).replaceAll("$1<br>$2")).replaceAll("$1<br>$2");
283 }
284
285 /**
286 * Returns the HTML-formatted tooltip text for the given note.
287 * @param note note to display
288 * @return the HTML-formatted tooltip text for the given note
289 * @since 13111
290 */
291 public static String getNoteToolTip(Note note) {
292 StringBuilder sb = new StringBuilder("<html>");
293 sb.append(tr("Note"))
294 .append(' ').append(note.getId());
295 for (NoteComment comment : note.getComments()) {
296 String commentText = comment.getText();
297 //closing a note creates an empty comment that we don't want to show
298 if (commentText != null && !commentText.trim().isEmpty()) {
299 sb.append("<hr/>");
300 String userName = XmlWriter.encode(comment.getUser().getName());
301 if (userName == null || userName.trim().isEmpty()) {
302 userName = "&lt;Anonymous&gt;";
303 }
304 sb.append(userName)
305 .append(" on ")
306 .append(DateUtils.getDateFormat(DateFormat.MEDIUM).format(comment.getCommentTimestamp()))
307 .append(":<br>");
308 String htmlText = XmlWriter.encode(comment.getText(), true);
309 // encode method leaves us with entity instead of \n
310 htmlText = htmlText.replace("&#xA;", "<br>");
311 // convert URLs to proper HTML links
312 htmlText = replaceLinks(htmlText);
313 sb.append(htmlText);
314 }
315 }
316 sb.append("</html>");
317 String result = sb.toString();
318 Logging.debug(result);
319 return result;
320 }
321
322 static String replaceLinks(String htmlText) {
323 String result = HTTP_LINK.matcher(htmlText).replaceAll("<a href=\"$1\">$1</a>");
324 result = HTML_LINK_MARK.matcher(result).replaceAll("<a href=\"$1\">$3</a>$2");
325 Matcher m1 = HTML_LINK.matcher(result);
326 if (m1.find()) {
327 int last = 0;
328 StringBuffer sb = new StringBuffer(); // Switch to StringBuilder when switching to Java 9
329 do {
330 sb.append(result, last, m1.start());
331 last = m1.end();
332 String link = m1.group(0);
333 Matcher m2 = SLASH.matcher(link).region(link.indexOf('>'), link.lastIndexOf('<'));
334 while (m2.find()) {
335 m2.appendReplacement(sb, "$1/\u200b$2"); //zero width space to wrap long URLs (see #10864, #15550)
336 }
337 m2.appendTail(sb);
338 } while (m1.find());
339 result = sb.append(result, last, result.length()).toString();
340 }
341 return result;
342 }
343
344 @Override
345 public Icon getIcon() {
346 return ImageProvider.get("dialogs/notes", "note_open", ImageProvider.ImageSizes.SMALLICON);
347 }
348
349 @Override
350 public String getToolTipText() {
351 int size = noteData.getNotes().size();
352 return trn("{0} note", "{0} notes", size, size);
353 }
354
355 @Override
356 public void mergeFrom(Layer from) {
357 if (from instanceof NoteLayer && this != from) {
358 noteData.mergeFrom(((NoteLayer) from).noteData);
359 }
360 }
361
362 @Override
363 public boolean isMergable(Layer other) {
364 return false;
365 }
366
367 @Override
368 public void visitBoundingBox(BoundingXYVisitor v) {
369 for (Note note : noteData.getNotes()) {
370 v.visit(note.getLatLon());
371 }
372 }
373
374 @Override
375 public Object getInfoComponent() {
376 StringBuilder sb = new StringBuilder();
377 sb.append(tr("Notes layer"))
378 .append('\n')
379 .append(tr("Total notes:"))
380 .append(' ')
381 .append(noteData.getNotes().size())
382 .append('\n')
383 .append(tr("Changes need uploading?"))
384 .append(' ')
385 .append(isModified());
386 return sb.toString();
387 }
388
389 @Override
390 public Action[] getMenuEntries() {
391 List<Action> actions = new ArrayList<>();
392 actions.add(LayerListDialog.getInstance().createShowHideLayerAction());
393 actions.add(LayerListDialog.getInstance().createDeleteLayerAction());
394 actions.add(new LayerListPopup.InfoAction(this));
395 actions.add(new LayerSaveAction(this));
396 actions.add(new LayerSaveAsAction(this));
397 return actions.toArray(new Action[0]);
398 }
399
400 @Override
401 public void mouseClicked(MouseEvent e) {
402 if (!SwingUtilities.isLeftMouseButton(e)) {
403 return;
404 }
405 Point clickPoint = e.getPoint();
406 double snapDistance = 10;
407 double minDistance = Double.MAX_VALUE;
408 final int iconHeight = ImageProvider.ImageSizes.SMALLICON.getAdjustedHeight();
409 Note closestNote = null;
410 for (Note note : noteData.getNotes()) {
411 Point notePoint = MainApplication.getMap().mapView.getPoint(note.getLatLon());
412 //move the note point to the center of the icon where users are most likely to click when selecting
413 notePoint.setLocation(notePoint.getX(), notePoint.getY() - iconHeight / 2);
414 double dist = clickPoint.distanceSq(notePoint);
415 if (minDistance > dist && clickPoint.distance(notePoint) < snapDistance) {
416 minDistance = dist;
417 closestNote = note;
418 }
419 }
420 noteData.setSelectedNote(closestNote);
421 }
422
423 @Override
424 public File createAndOpenSaveFileChooser() {
425 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save Note file"), NoteExporter.FILE_FILTER);
426 }
427
428 @Override
429 public AbstractIOTask createUploadTask(ProgressMonitor monitor) {
430 return new UploadNoteLayerTask(this, monitor);
431 }
432
433 @Override
434 public void mousePressed(MouseEvent e) {
435 // Do nothing
436 }
437
438 @Override
439 public void mouseReleased(MouseEvent e) {
440 // Do nothing
441 }
442
443 @Override
444 public void mouseEntered(MouseEvent e) {
445 // Do nothing
446 }
447
448 @Override
449 public void mouseExited(MouseEvent e) {
450 // Do nothing
451 }
452
453 @Override
454 public void noteDataUpdated(NoteData data) {
455 invalidate();
456 }
457
458 @Override
459 public void selectedNoteChanged(NoteData noteData) {
460 invalidate();
461 }
462}
Note: See TracBrowser for help on using the repository browser.