source: osm/applications/editors/josm/plugins/cadastre-fr/src/cadastre_fr/Address.java@ 33514

Last change on this file since 33514 was 33301, checked in by stoecker, 8 years ago

fix #josm14759 - patch found by Binnette

File size: 22.3 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package cadastre_fr;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Cursor;
7import java.awt.GridBagLayout;
8import java.awt.Point;
9import java.awt.Rectangle;
10import java.awt.Toolkit;
11import java.awt.event.ActionEvent;
12import java.awt.event.ActionListener;
13import java.awt.event.ComponentAdapter;
14import java.awt.event.ComponentEvent;
15import java.awt.event.KeyEvent;
16import java.awt.event.MouseEvent;
17import java.awt.event.WindowAdapter;
18import java.awt.event.WindowEvent;
19import java.util.ArrayList;
20import java.util.Collection;
21import java.util.Collections;
22import java.util.HashMap;
23import java.util.HashSet;
24import java.util.Iterator;
25import java.util.LinkedList;
26import java.util.List;
27import java.util.Map;
28import java.util.Set;
29
30import javax.swing.ButtonGroup;
31import javax.swing.ImageIcon;
32import javax.swing.JButton;
33import javax.swing.JCheckBox;
34import javax.swing.JDialog;
35import javax.swing.JLabel;
36import javax.swing.JOptionPane;
37import javax.swing.JPanel;
38import javax.swing.JRadioButton;
39import javax.swing.JTextField;
40import javax.swing.event.ChangeEvent;
41import javax.swing.event.ChangeListener;
42
43import org.openstreetmap.josm.Main;
44import org.openstreetmap.josm.actions.mapmode.MapMode;
45import org.openstreetmap.josm.command.AddCommand;
46import org.openstreetmap.josm.command.ChangeCommand;
47import org.openstreetmap.josm.command.ChangePropertyCommand;
48import org.openstreetmap.josm.command.Command;
49import org.openstreetmap.josm.command.SequenceCommand;
50import org.openstreetmap.josm.data.coor.EastNorth;
51import org.openstreetmap.josm.data.osm.DataSet;
52import org.openstreetmap.josm.data.osm.Node;
53import org.openstreetmap.josm.data.osm.OsmPrimitive;
54import org.openstreetmap.josm.data.osm.Relation;
55import org.openstreetmap.josm.data.osm.RelationMember;
56import org.openstreetmap.josm.data.osm.Way;
57import org.openstreetmap.josm.data.osm.WaySegment;
58import org.openstreetmap.josm.gui.MapView;
59import org.openstreetmap.josm.tools.GBC;
60import org.openstreetmap.josm.tools.ImageProvider;
61import org.openstreetmap.josm.tools.Pair;
62import org.openstreetmap.josm.tools.Shortcut;
63
64public class Address extends MapMode {
65
66 // perhaps make all these tags configurable in the future
67 private String tagHighway = "highway";
68 private String tagHighwayName = "name";
69 private String tagHouseNumber = "addr:housenumber";
70 private String tagHouseStreet = "addr:street";
71 private String tagBuilding = "building";
72 private String relationAddrType = "associatedStreet";
73 private String relationAddrName = "name";
74 private String relationAddrStreetRole = "street";
75 private String relationMemberHouse = "house";
76
77 private JRadioButton plusOne = new JRadioButton("+1", false);
78 private JRadioButton plusTwo = new JRadioButton("+2", true); // enable this by default
79 private JRadioButton minusOne = new JRadioButton("-1", false);
80 private JRadioButton minusTwo = new JRadioButton("-2", false);
81 final JCheckBox tagPolygon = new JCheckBox(tr("on polygon"));
82
83 JDialog dialog;
84 JButton clearButton;
85 final JTextField inputNumber = new JTextField();
86 final JTextField inputStreet = new JTextField();
87 JLabel link = new JLabel();
88 private transient Way selectedWay;
89 private boolean shift;
90 private boolean ctrl;
91
92 /**
93 * Constructs a new {@code Address} map mode.
94 */
95 public Address() {
96 super(tr("Add address"), "buildings",
97 tr("Helping tool for tag address"),
98 // CHECKSTYLE.OFF: LineLength
99 Shortcut.registerShortcut("mapmode:cadastre-fr-buildings", tr("Mode: {0}", tr("CadastreFR - Buildings")), KeyEvent.VK_E, Shortcut.DIRECT),
100 // CHECKSTYLE.ON: LineLength
101 getCursor());
102 }
103
104 @Override public void enterMode() {
105 super.enterMode();
106 if (dialog == null) {
107 createDialog();
108 }
109 dialog.setVisible(true);
110 Main.map.mapView.addMouseListener(this);
111 }
112
113 @Override public void exitMode() {
114 if (Main.map.mapView != null) {
115 super.exitMode();
116 Main.map.mapView.removeMouseListener(this);
117 }
118 // kill the window completely to fix an issue on some linux distro and full screen mode.
119 if (dialog != null) {
120 dialog.dispose();
121 dialog = null;
122 }
123 }
124
125 @Override
126 public void mousePressed(MouseEvent e) {
127 if (e.getButton() != MouseEvent.BUTTON1)
128 return;
129 shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
130 ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
131 MapView mv = Main.map.mapView;
132 Point mousePos = e.getPoint();
133 List<Way> mouseOnExistingWays = new ArrayList<>();
134 List<Way> mouseOnExistingBuildingWays = new ArrayList<>();
135 Node currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive::isSelectable);
136 if (currentMouseNode != null) {
137 // click on existing node
138 setNewSelection(currentMouseNode);
139 String num = currentMouseNode.get(tagHouseNumber);
140 if (num != null
141 && currentMouseNode.get(tagHouseStreet) == null
142 && findWayInRelationAddr(currentMouseNode) == null
143 && !inputStreet.getText().isEmpty()) {
144 // house number already present but not linked to a street
145 Collection<Command> cmds = new LinkedList<>();
146 addStreetNameOrRelation(currentMouseNode, cmds);
147 Command c = new SequenceCommand("Add node address", cmds);
148 Main.main.undoRedo.add(c);
149 setNewSelection(currentMouseNode);
150 } else {
151 if (num != null) {
152 try {
153 // add new address
154 Integer.parseInt(num);
155 inputNumber.setText(num);
156 applyInputNumberChange();
157 } catch (NumberFormatException en) {
158 Main.warn("Unable to parse house number \"" + num + "\"");
159 }
160 }
161 if (currentMouseNode.get(tagHouseStreet) != null) {
162 if (Main.pref.getBoolean("cadastrewms.addr.dontUseRelation", false)) {
163 inputStreet.setText(currentMouseNode.get(tagHouseStreet));
164 if (ctrl) {
165 Collection<Command> cmds = new LinkedList<>();
166 addAddrToPrimitive(currentMouseNode, cmds);
167 if (num == null)
168 applyInputNumberChange();
169 }
170 setSelectedWay((Way) null);
171 }
172 } else {
173 // check if the node belongs to an associatedStreet relation
174 Way wayInRelationAddr = findWayInRelationAddr(currentMouseNode);
175 if (wayInRelationAddr == null) {
176 // node exists but doesn't carry address information : add tags like a new node
177 if (ctrl) {
178 applyInputNumberChange();
179 }
180 Collection<Command> cmds = new LinkedList<>();
181 addAddrToPrimitive(currentMouseNode, cmds);
182 } else {
183 inputStreet.setText(wayInRelationAddr.get(tagHighwayName));
184 setSelectedWay(wayInRelationAddr);
185 }
186 }
187 }
188 } else {
189 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive::isSelectable);
190 for (WaySegment ws : wss) {
191 if (ws.way.get(tagHighway) != null && ws.way.get(tagHighwayName) != null)
192 mouseOnExistingWays.add(ws.way);
193 else if (ws.way.get(tagBuilding) != null && ws.way.get(tagHouseNumber) == null)
194 mouseOnExistingBuildingWays.add(ws.way);
195 }
196 if (mouseOnExistingWays.size() == 1) {
197 // clicked on existing highway => set new street name
198 inputStreet.setText(mouseOnExistingWays.get(0).get(tagHighwayName));
199 setSelectedWay(mouseOnExistingWays.get(0));
200 inputNumber.setText("");
201 setNewSelection(mouseOnExistingWays.get(0));
202 } else if (mouseOnExistingWays.isEmpty()) {
203 // clicked a non highway and not a node => add the new address
204 if (inputStreet.getText().isEmpty() || inputNumber.getText().isEmpty()) {
205 Toolkit.getDefaultToolkit().beep();
206 } else {
207 Collection<Command> cmds = new LinkedList<>();
208 if (ctrl) {
209 applyInputNumberChange();
210 }
211 if (tagPolygon.isSelected()) {
212 addAddrToPolygon(mouseOnExistingBuildingWays, cmds);
213 } else {
214 Node n = createNewNode(e, cmds);
215 addAddrToPrimitive(n, cmds);
216 }
217 }
218 }
219 }
220 }
221
222 private Way findWayInRelationAddr(Node n) {
223 List<OsmPrimitive> l = n.getReferrers();
224 for (OsmPrimitive osm : l) {
225 if (osm instanceof Relation && osm.hasKey("type") && osm.get("type").equals(relationAddrType)) {
226 for (RelationMember rm : ((Relation) osm).getMembers()) {
227 if (rm.getRole().equals(relationAddrStreetRole)) {
228 OsmPrimitive osp = rm.getMember();
229 if (osp instanceof Way && osp.hasKey(tagHighwayName)) {
230 return (Way) osp;
231 }
232 }
233 }
234 }
235 }
236 return null;
237 }
238
239 private void addAddrToPolygon(List<Way> mouseOnExistingBuildingWays, Collection<Command> cmds) {
240 for (Way w:mouseOnExistingBuildingWays) {
241 addAddrToPrimitive(w, cmds);
242 }
243 }
244
245 private void addAddrToPrimitive(OsmPrimitive osm, Collection<Command> cmds) {
246 // add the current tag addr:housenumber in node and member in relation (if so configured)
247 if (shift) {
248 try {
249 revertInputNumberChange();
250 } catch (NumberFormatException en) {
251 Main.warn("Unable to parse house number \"" + inputNumber.getText() + "\"");
252 }
253 }
254 cmds.add(new ChangePropertyCommand(osm, tagHouseNumber, inputNumber.getText()));
255 addStreetNameOrRelation(osm, cmds);
256 try {
257 applyInputNumberChange();
258 Command c = new SequenceCommand("Add node address", cmds);
259 Main.main.undoRedo.add(c);
260 setNewSelection(osm);
261 } catch (NumberFormatException en) {
262 Main.warn("Unable to parse house number \"" + inputNumber.getText() + "\"");
263 }
264 }
265
266 private Relation findRelationAddr(Way w) {
267 List<OsmPrimitive> l = w.getReferrers();
268 for (OsmPrimitive osm : l) {
269 if (osm instanceof Relation && osm.hasKey("type") && osm.get("type").equals(relationAddrType)) {
270 return (Relation) osm;
271 }
272 }
273 return null;
274 }
275
276 private void addStreetNameOrRelation(OsmPrimitive osm, Collection<Command> cmds) {
277 if (Main.pref.getBoolean("cadastrewms.addr.dontUseRelation", false)) {
278 cmds.add(new ChangePropertyCommand(osm, tagHouseStreet, inputStreet.getText()));
279 } else if (selectedWay != null) {
280 Relation selectedRelation = findRelationAddr(selectedWay);
281 // add the node to its relation
282 if (selectedRelation != null) {
283 RelationMember rm = new RelationMember(relationMemberHouse, osm);
284 Relation newRel = new Relation(selectedRelation);
285 newRel.addMember(rm);
286 cmds.add(new ChangeCommand(selectedRelation, newRel));
287 } else {
288 // create new relation
289 Relation newRel = new Relation();
290 newRel.put("type", relationAddrType);
291 newRel.put(relationAddrName, selectedWay.get(tagHighwayName));
292 newRel.addMember(new RelationMember(relationAddrStreetRole, selectedWay));
293 newRel.addMember(new RelationMember(relationMemberHouse, osm));
294 cmds.add(new AddCommand(newRel));
295 }
296 }
297 }
298
299 private static Node createNewNode(MouseEvent e, Collection<Command> cmds) {
300 // DrawAction.mouseReleased() but without key modifiers
301 Node n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
302 cmds.add(new AddCommand(n));
303 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(e.getPoint(), OsmPrimitive::isSelectable);
304 Map<Way, List<Integer>> insertPoints = new HashMap<>();
305 for (WaySegment ws : wss) {
306 List<Integer> is;
307 if (insertPoints.containsKey(ws.way)) {
308 is = insertPoints.get(ws.way);
309 } else {
310 is = new ArrayList<>();
311 insertPoints.put(ws.way, is);
312 }
313
314 is.add(ws.lowerIndex);
315 }
316 Set<Pair<Node, Node>> segSet = new HashSet<>();
317 ArrayList<Way> replacedWays = new ArrayList<>();
318 ArrayList<Way> reuseWays = new ArrayList<>();
319 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
320 Way w = insertPoint.getKey();
321 List<Integer> is = insertPoint.getValue();
322 Way wnew = new Way(w);
323 pruneSuccsAndReverse(is);
324 for (int i : is) {
325 segSet.add(Pair.sort(new Pair<>(w.getNode(i), w.getNode(i+1))));
326 }
327 for (int i : is) {
328 wnew.addNode(i + 1, n);
329 }
330 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
331 replacedWays.add(insertPoint.getKey());
332 reuseWays.add(wnew);
333 }
334 adjustNode(segSet, n);
335
336 return n;
337 }
338
339 private static void adjustNode(Collection<Pair<Node, Node>> segs, Node n) {
340
341 switch (segs.size()) {
342 case 0:
343 return;
344 case 2:
345 // This computes the intersection between
346 // the two segments and adjusts the node position.
347 Iterator<Pair<Node, Node>> i = segs.iterator();
348 Pair<Node, Node> seg = i.next();
349 EastNorth A = seg.a.getEastNorth();
350 EastNorth B = seg.b.getEastNorth();
351 seg = i.next();
352 EastNorth C = seg.a.getEastNorth();
353 EastNorth D = seg.b.getEastNorth();
354
355 double u = det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
356
357 // Check for parallel segments and do nothing if they are
358 // In practice this will probably only happen when a way has been duplicated
359
360 if (u == 0) return;
361
362 // q is a number between 0 and 1
363 // It is the point in the segment where the intersection occurs
364 // if the segment is scaled to lenght 1
365
366 double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
367 EastNorth intersection = new EastNorth(
368 B.east() + q * (A.east() - B.east()),
369 B.north() + q * (A.north() - B.north()));
370
371 int snapToIntersectionThreshold
372 = Main.pref.getInteger("edit.snap-intersection-threshold", 10);
373
374 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
375 // fall through to default action.
376 // (for semi-parallel lines, intersection might be miles away!)
377 if (Main.map.mapView.getPoint(n).distance(Main.map.mapView.getPoint(intersection)) < snapToIntersectionThreshold) {
378 n.setEastNorth(intersection);
379 return;
380 }
381
382 default:
383 EastNorth P = n.getEastNorth();
384 seg = segs.iterator().next();
385 A = seg.a.getEastNorth();
386 B = seg.b.getEastNorth();
387 double a = P.distanceSq(B);
388 double b = P.distanceSq(A);
389 double c = A.distanceSq(B);
390 q = (a - b + c) / (2*c);
391 n.setEastNorth(new EastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north())));
392 }
393 }
394
395 static double det(double a, double b, double c, double d) {
396 return a * d - b * c;
397 }
398
399 private static void pruneSuccsAndReverse(List<Integer> is) {
400 HashSet<Integer> is2 = new HashSet<>();
401 for (int i : is) {
402 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
403 is2.add(i);
404 }
405 }
406 is.clear();
407 is.addAll(is2);
408 Collections.sort(is);
409 Collections.reverse(is);
410 }
411
412 private static Cursor getCursor() {
413 try {
414 return ImageProvider.getCursor("crosshair", null);
415 } catch (RuntimeException e) {
416 Main.warn(e);
417 }
418 return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
419 }
420
421 private void applyInputNumberChange() {
422 Integer num = Integer.parseInt(inputNumber.getText());
423 if (plusOne.isSelected())
424 num = num + 1;
425 if (plusTwo.isSelected())
426 num = num + 2;
427 if (minusOne.isSelected() && num > 1)
428 num = num - 1;
429 if (minusTwo.isSelected() && num > 2)
430 num = num - 2;
431 inputNumber.setText(num.toString());
432 }
433
434 private void revertInputNumberChange() {
435 Integer num = Integer.parseInt(inputNumber.getText());
436 if (plusOne.isSelected())
437 num = num - 1;
438 if (plusTwo.isSelected())
439 num = num - 2;
440 if (minusOne.isSelected() && num > 1)
441 num = num + 1;
442 if (minusTwo.isSelected() && num > 2)
443 num = num + 2;
444 inputNumber.setText(num.toString());
445 }
446
447 private void createDialog() {
448 ImageIcon iconLink = ImageProvider.get(null, "Mf_relation");
449 link.setIcon(iconLink);
450 link.setEnabled(false);
451 JPanel p = new JPanel(new GridBagLayout());
452 JLabel number = new JLabel(tr("Next no"));
453 JLabel street = new JLabel(tr("Street"));
454 p.add(number, GBC.std().insets(0, 0, 0, 0));
455 p.add(inputNumber, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 5, 0, 5));
456 p.add(street, GBC.std().insets(0, 0, 0, 0));
457 JPanel p2 = new JPanel(new GridBagLayout());
458 inputStreet.setEditable(false);
459 p2.add(inputStreet, GBC.std().fill(GBC.HORIZONTAL).insets(5, 0, 0, 0));
460 p2.add(link, GBC.eol().insets(10, 0, 0, 0));
461 p.add(p2, GBC.eol().fill(GBC.HORIZONTAL));
462 clearButton = new JButton("Clear");
463 clearButton.addActionListener(new ActionListener() {
464 @Override
465 public void actionPerformed(ActionEvent e) {
466 inputNumber.setText("");
467 inputStreet.setText("");
468 setSelectedWay((Way) null);
469 }
470 });
471 ButtonGroup bgIncremental = new ButtonGroup();
472 bgIncremental.add(plusOne);
473 bgIncremental.add(plusTwo);
474 bgIncremental.add(minusOne);
475 bgIncremental.add(minusTwo);
476 p.add(minusOne, GBC.std().insets(10, 0, 10, 0));
477 p.add(plusOne, GBC.std().insets(0, 0, 10, 0));
478 tagPolygon.setSelected(Main.pref.getBoolean("cadastrewms.addr.onBuilding", false));
479 tagPolygon.addChangeListener(new ChangeListener() {
480 @Override
481 public void stateChanged(ChangeEvent arg0) {
482 Main.pref.put("cadastrewms.addr.onBuilding", tagPolygon.isSelected());
483 }
484 });
485 p.add(tagPolygon, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 0));
486 p.add(minusTwo, GBC.std().insets(10, 0, 10, 0));
487 p.add(plusTwo, GBC.std().insets(0, 0, 10, 0));
488 p.add(clearButton, GBC.eol().fill(GBC.HORIZONTAL).insets(0, 0, 0, 0));
489
490 final Object[] options = {};
491 final JOptionPane pane = new JOptionPane(p,
492 JOptionPane.PLAIN_MESSAGE, JOptionPane.YES_NO_CANCEL_OPTION,
493 null, options, null);
494 dialog = pane.createDialog(Main.parent, tr("Enter addresses"));
495 dialog.setModal(false);
496 dialog.setAlwaysOnTop(true);
497 dialog.addComponentListener(new ComponentAdapter() {
498 protected void rememberGeometry() {
499 Main.pref.put("cadastrewms.addr.bounds", dialog.getX()+","+dialog.getY()+","+dialog.getWidth()+","+dialog.getHeight());
500 }
501
502 @Override public void componentMoved(ComponentEvent e) {
503 rememberGeometry();
504 }
505
506 @Override public void componentResized(ComponentEvent e) {
507 rememberGeometry();
508 }
509 });
510 dialog.addWindowListener(new WindowAdapter() {
511 @Override
512 public void windowClosing(WindowEvent arg) {
513 Main.map.selectMapMode((MapMode) Main.map.getDefaultButtonAction());
514 }
515 });
516 String bounds = Main.pref.get("cadastrewms.addr.bounds", null);
517 if (bounds != null) {
518 String[] b = bounds.split(",");
519 dialog.setBounds(new Rectangle(
520 Integer.parseInt(b[0]), Integer.parseInt(b[1]), Integer.parseInt(b[2]), Integer.parseInt(b[3])));
521 }
522 }
523
524 private void setSelectedWay(Way w) {
525 this.selectedWay = w;
526 if (w == null) {
527 link.setEnabled(false);
528 } else
529 link.setEnabled(true);
530 link.repaint();
531 }
532
533 private static void setNewSelection(OsmPrimitive osm) {
534 DataSet ds = Main.getLayerManager().getEditDataSet();
535 Collection<OsmPrimitive> newSelection = new LinkedList<>(ds.getSelected());
536 newSelection.clear();
537 newSelection.add(osm);
538 ds.setSelected(osm);
539 }
540}
Note: See TracBrowser for help on using the repository browser.