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

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

sonar - fix many issues

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