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

Last change on this file since 32950 was 32950, checked in by donvip, 9 years ago

fix deprecation/checkstyle warning

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