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

Last change on this file since 28372 was 28372, checked in by pieren, 12 years ago

restore worthy setting to open the address dialog

File size: 22.7 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.MouseListener;
17import java.awt.event.MouseMotionListener;
18import java.awt.event.WindowEvent;
19import java.awt.event.WindowListener;
20import java.util.ArrayList;
21import java.util.Collection;
22import java.util.Collections;
23import java.util.HashMap;
24import java.util.HashSet;
25import java.util.Iterator;
26import java.util.LinkedList;
27import java.util.List;
28import java.util.Map;
29import java.util.Set;
30
31import javax.swing.ButtonGroup;
32import javax.swing.ImageIcon;
33import javax.swing.JButton;
34import javax.swing.JCheckBox;
35import javax.swing.JDialog;
36import javax.swing.JLabel;
37import javax.swing.JOptionPane;
38import javax.swing.JPanel;
39import javax.swing.JRadioButton;
40import javax.swing.JTextField;
41import javax.swing.event.ChangeEvent;
42import javax.swing.event.ChangeListener;
43
44import org.openstreetmap.josm.Main;
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.actions.mapmode.MapMode;
51import org.openstreetmap.josm.data.coor.EastNorth;
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 implements MouseListener, MouseMotionListener, ActionListener {
66 private static final long serialVersionUID = 1L;
67
68 // perhaps make all these tags configurable in the future
69 private String tagHighway = "highway";
70 private String tagHighwayName = "name";
71 private String tagHouseNumber = "addr:housenumber";
72 private String tagHouseStreet = "addr:street";
73 private String tagBuilding = "building";
74 private String relationAddrType = "associatedStreet";
75 private String relationAddrName = "name";
76 private String relationAddrStreetRole = "street";
77 private String relationMemberHouse = "house";
78
79 private JRadioButton plus_one = new JRadioButton("+1", false);
80 private JRadioButton plus_two = new JRadioButton("+2", true); // enable this by default
81 private JRadioButton minus_one = new JRadioButton("-1", false);
82 private JRadioButton minus_two = new JRadioButton("-2", false);
83 final JCheckBox tagPolygon = new JCheckBox(tr("on polygon"));
84
85 JDialog dialog = null;
86 JButton clearButton = null;
87 final JTextField inputNumber = new JTextField();
88 final JTextField inputStreet = new JTextField();
89 JLabel link = new JLabel();
90 private Way selectedWay;
91 private boolean shift;
92 private boolean ctrl;
93
94 public Address(MapFrame mapFrame) {
95 super(tr("Add address"), "buildings",
96 tr("Helping tool for tag address"),
97 Shortcut.registerShortcut("mapmode:cadastre-fr-buildings", tr("Mode: {0}", tr("CadastreFR - Buildings")), KeyEvent.VK_E, Shortcut.DIRECT),
98 mapFrame, getCursor());
99 }
100
101 @Override public void enterMode() {
102 super.enterMode();
103 if (dialog == null) {
104 createDialog();
105 }
106 dialog.setVisible(true);
107 Main.map.mapView.addMouseListener(this);
108 }
109
110 @Override public void exitMode() {
111 if (Main.map.mapView != null) {
112 super.exitMode();
113 Main.map.mapView.removeMouseListener(this);
114 }
115 dialog.setVisible(false);
116 }
117
118 @Override
119 public void mousePressed(MouseEvent e) {
120 if (e.getButton() != MouseEvent.BUTTON1)
121 return;
122 shift = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
123 ctrl = (e.getModifiers() & ActionEvent.CTRL_MASK) != 0;
124 MapView mv = Main.map.mapView;
125 Point mousePos = e.getPoint();
126 List<Way> mouseOnExistingWays = new ArrayList<Way>();
127 List<Way> mouseOnExistingBuildingWays = new ArrayList<Way>();
128 mouseOnExistingWays = new ArrayList<Way>();
129 Node currentMouseNode = mv.getNearestNode(mousePos, OsmPrimitive.isSelectablePredicate);
130 if (currentMouseNode != null) {
131 // click on existing node
132 setNewSelection(currentMouseNode);
133 String num = currentMouseNode.get(tagHouseNumber);
134 if (num != null //
135 && currentMouseNode.get(tagHouseStreet) == null //
136 && findWayInRelationAddr(currentMouseNode) == null //
137 && !inputStreet.getText().equals("")) {
138 // address already present but not linked to a street
139 Collection<Command> cmds = new LinkedList<Command>();
140 addStreetNameOrRelation(currentMouseNode, cmds);
141 Command c = new SequenceCommand("Add node address", cmds);
142 Main.main.undoRedo.add(c);
143 setNewSelection(currentMouseNode);
144 } else {
145 if (num != null) {
146 try {
147 // add new address
148 Integer.parseInt(num);
149 inputNumber.setText(num);
150 applyInputNumberChange();
151 } catch (NumberFormatException en) {
152 System.out.println("Unable to parse house number \"" + num + "\"");
153 }
154 }
155 if (currentMouseNode.get(tagHouseStreet) != null) {
156 inputStreet.setText(currentMouseNode.get(tagHouseStreet));
157 if (ctrl) {
158 Collection<Command> cmds = new LinkedList<Command>();
159 addAddrToPrimitive(currentMouseNode, cmds);
160 if (num == null)
161 applyInputNumberChange();
162 }
163 setSelectedWay((Way)null);
164 } else {
165 // check if the node belongs to an associatedStreet relation
166 Way wayInRelationAddr = findWayInRelationAddr(currentMouseNode);
167 if (wayInRelationAddr == null) {
168 // node exists but doesn't carry address information : add tags like a new node
169 if (ctrl) {
170 applyInputNumberChange();
171 }
172 Collection<Command> cmds = new LinkedList<Command>();
173 addAddrToPrimitive(currentMouseNode, cmds);
174 } else {
175 inputStreet.setText(wayInRelationAddr.get(tagHighwayName));
176 setSelectedWay(wayInRelationAddr);
177 }
178 }
179 }
180 } else {
181 List<WaySegment> wss = mv.getNearestWaySegments(mousePos, OsmPrimitive.isSelectablePredicate);
182 for(WaySegment ws : wss) {
183 if (ws.way.get(tagHighway) != null && ws.way.get(tagHighwayName) != null)
184 mouseOnExistingWays.add(ws.way);
185 else if (ws.way.get(tagBuilding) != null && ws.way.get(tagHouseNumber) == null)
186 mouseOnExistingBuildingWays.add(ws.way);
187 }
188 if (mouseOnExistingWays.size() == 1) {
189 // clicked on existing highway => set new street name
190 inputStreet.setText(mouseOnExistingWays.get(0).get(tagHighwayName));
191 setSelectedWay(mouseOnExistingWays.get(0));
192 inputNumber.setText("");
193 setNewSelection(mouseOnExistingWays.get(0));
194 } else if (mouseOnExistingWays.size() == 0) {
195 // clicked a non highway and not a node => add the new address
196 if (inputStreet.getText().equals("") || inputNumber.getText().equals("")) {
197 Toolkit.getDefaultToolkit().beep();
198 } else {
199 Collection<Command> cmds = new LinkedList<Command>();
200 if (ctrl) {
201 applyInputNumberChange();
202 }
203 if (tagPolygon.isSelected()) {
204 addAddrToPolygon(mouseOnExistingBuildingWays, cmds);
205 } else {
206 Node n = createNewNode(e, cmds);
207 addAddrToPrimitive(n, cmds);
208 }
209 }
210 }
211 }
212
213 }
214
215 private Way findWayInRelationAddr(Node n) {
216 List<OsmPrimitive> l = n.getReferrers();
217 for (OsmPrimitive osm : l) {
218 if (osm instanceof Relation && osm.hasKey("type") && osm.get("type").equals(relationAddrType)) {
219 for (RelationMember rm : ((Relation)osm).getMembers()) {
220 if (rm.getRole().equals(relationAddrStreetRole)) {
221 OsmPrimitive osp = rm.getMember();
222 if (osp instanceof Way && osp.hasKey(tagHighwayName)) {
223 return (Way)osp;
224 }
225 }
226 }
227 }
228 }
229 return null;
230 }
231
232 private void addAddrToPolygon(List<Way> mouseOnExistingBuildingWays, Collection<Command> cmds) {
233 for (Way w:mouseOnExistingBuildingWays) {
234 addAddrToPrimitive(w, cmds);
235 }
236 }
237
238 private void addAddrToPrimitive(OsmPrimitive osm, Collection<Command> cmds) {
239 // add the current tag addr:housenumber in node and member in relation (if so configured)
240 if (shift) {
241 try {
242 revertInputNumberChange();
243 } catch (NumberFormatException en) {
244 System.out.println("Unable to parse house number \"" + inputNumber.getText() + "\"");
245 }
246
247 }
248 cmds.add(new ChangePropertyCommand(osm, tagHouseNumber, inputNumber.getText()));
249 addStreetNameOrRelation(osm, cmds);
250 try {
251 applyInputNumberChange();
252 Command c = new SequenceCommand("Add node address", cmds);
253 Main.main.undoRedo.add(c);
254 setNewSelection(osm);
255 } catch (NumberFormatException en) {
256 System.out.println("Unable to parse house number \"" + inputNumber.getText() + "\"");
257 }
258 }
259
260 private Relation findRelationAddr(Way w) {
261 List<OsmPrimitive> l = w.getReferrers();
262 for (OsmPrimitive osm : l) {
263 if (osm instanceof Relation && osm.hasKey("type") && osm.get("type").equals(relationAddrType)) {
264 return (Relation)osm;
265 }
266 }
267 return null;
268 }
269
270 private void addStreetNameOrRelation(OsmPrimitive osm, Collection<Command> cmds) {
271 if (Main.pref.getBoolean("cadastrewms.addr.dontUseRelation", false)) {
272 cmds.add(new ChangePropertyCommand(osm, tagHouseStreet, inputStreet.getText()));
273 } else if (selectedWay != null) {
274 Relation selectedRelation = findRelationAddr(selectedWay);
275 // add the node to its relation
276 if (selectedRelation != null) {
277 RelationMember rm = new RelationMember(relationMemberHouse, osm);
278 Relation newRel = new Relation(selectedRelation);
279 newRel.addMember(rm);
280 cmds.add(new ChangeCommand(selectedRelation, newRel));
281 } else {
282 // create new relation
283 Relation newRel = new Relation();
284 newRel.put("type", relationAddrType);
285 newRel.put(relationAddrName, selectedWay.get(tagHighwayName));
286 newRel.addMember(new RelationMember(relationAddrStreetRole, selectedWay));
287 newRel.addMember(new RelationMember(relationMemberHouse, osm));
288 cmds.add(new AddCommand(newRel));
289 }
290 }
291 }
292
293 private Node createNewNode(MouseEvent e, Collection<Command> cmds) {
294 // DrawAction.mouseReleased() but without key modifiers
295 Node n = new Node(Main.map.mapView.getLatLon(e.getX(), e.getY()));
296 cmds.add(new AddCommand(n));
297 List<WaySegment> wss = Main.map.mapView.getNearestWaySegments(e.getPoint(), OsmPrimitive.isSelectablePredicate);
298 Map<Way, List<Integer>> insertPoints = new HashMap<Way, List<Integer>>();
299 for (WaySegment ws : wss) {
300 List<Integer> is;
301 if (insertPoints.containsKey(ws.way)) {
302 is = insertPoints.get(ws.way);
303 } else {
304 is = new ArrayList<Integer>();
305 insertPoints.put(ws.way, is);
306 }
307
308 is.add(ws.lowerIndex);
309 }
310 Set<Pair<Node,Node>> segSet = new HashSet<Pair<Node,Node>>();
311 ArrayList<Way> replacedWays = new ArrayList<Way>();
312 ArrayList<Way> reuseWays = new ArrayList<Way>();
313 for (Map.Entry<Way, List<Integer>> insertPoint : insertPoints.entrySet()) {
314 Way w = insertPoint.getKey();
315 List<Integer> is = insertPoint.getValue();
316 Way wnew = new Way(w);
317 pruneSuccsAndReverse(is);
318 for (int i : is) {
319 segSet.add(Pair.sort(new Pair<Node,Node>(w.getNode(i), w.getNode(i+1))));
320 }
321 for (int i : is) {
322 wnew.addNode(i + 1, n);
323 }
324 cmds.add(new ChangeCommand(insertPoint.getKey(), wnew));
325 replacedWays.add(insertPoint.getKey());
326 reuseWays.add(wnew);
327 }
328 adjustNode(segSet, n);
329
330 return n;
331 }
332
333 private static void adjustNode(Collection<Pair<Node,Node>> segs, Node n) {
334
335 switch (segs.size()) {
336 case 0:
337 return;
338 case 2:
339 // This computes the intersection between
340 // the two segments and adjusts the node position.
341 Iterator<Pair<Node,Node>> i = segs.iterator();
342 Pair<Node,Node> seg = i.next();
343 EastNorth A = seg.a.getEastNorth();
344 EastNorth B = seg.b.getEastNorth();
345 seg = i.next();
346 EastNorth C = seg.a.getEastNorth();
347 EastNorth D = seg.b.getEastNorth();
348
349 double u=det(B.east() - A.east(), B.north() - A.north(), C.east() - D.east(), C.north() - D.north());
350
351 // Check for parallel segments and do nothing if they are
352 // In practice this will probably only happen when a way has been duplicated
353
354 if (u == 0) return;
355
356 // q is a number between 0 and 1
357 // It is the point in the segment where the intersection occurs
358 // if the segment is scaled to lenght 1
359
360 double q = det(B.north() - C.north(), B.east() - C.east(), D.north() - C.north(), D.east() - C.east()) / u;
361 EastNorth intersection = new EastNorth(
362 B.east() + q * (A.east() - B.east()),
363 B.north() + q * (A.north() - B.north()));
364
365 int snapToIntersectionThreshold
366 = Main.pref.getInteger("edit.snap-intersection-threshold",10);
367
368 // only adjust to intersection if within snapToIntersectionThreshold pixel of mouse click; otherwise
369 // fall through to default action.
370 // (for semi-parallel lines, intersection might be miles away!)
371 if (Main.map.mapView.getPoint(n).distance(Main.map.mapView.getPoint(intersection)) < snapToIntersectionThreshold) {
372 n.setEastNorth(intersection);
373 return;
374 }
375
376 default:
377 EastNorth P = n.getEastNorth();
378 seg = segs.iterator().next();
379 A = seg.a.getEastNorth();
380 B = seg.b.getEastNorth();
381 double a = P.distanceSq(B);
382 double b = P.distanceSq(A);
383 double c = A.distanceSq(B);
384 q = (a - b + c) / (2*c);
385 n.setEastNorth(new EastNorth(B.east() + q * (A.east() - B.east()), B.north() + q * (A.north() - B.north())));
386 }
387 }
388
389 static double det(double a, double b, double c, double d) {
390 return a * d - b * c;
391 }
392
393 private static void pruneSuccsAndReverse(List<Integer> is) {
394 //if (is.size() < 2) return;
395
396 HashSet<Integer> is2 = new HashSet<Integer>();
397 for (int i : is) {
398 if (!is2.contains(i - 1) && !is2.contains(i + 1)) {
399 is2.add(i);
400 }
401 }
402 is.clear();
403 is.addAll(is2);
404 Collections.sort(is);
405 Collections.reverse(is);
406 }
407
408 private static Cursor getCursor() {
409 try {
410 return ImageProvider.getCursor("crosshair", null);
411 } catch (Exception e) {
412 }
413 return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR);
414 }
415
416 private void applyInputNumberChange() {
417 Integer num = Integer.parseInt(inputNumber.getText());
418 if (plus_one.isSelected())
419 num = num + 1;
420 if (plus_two.isSelected())
421 num = num + 2;
422 if (minus_one.isSelected() && num > 1)
423 num = num - 1;
424 if (minus_two.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 (plus_one.isSelected())
432 num = num - 1;
433 if (plus_two.isSelected())
434 num = num - 2;
435 if (minus_one.isSelected() && num > 1)
436 num = num + 1;
437 if (minus_two.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.png");
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 public void actionPerformed(ActionEvent e) {
460 inputNumber.setText("");
461 inputStreet.setText("");
462 setSelectedWay((Way)null);
463 }
464 });
465 ButtonGroup bgIncremental = new ButtonGroup();
466 bgIncremental.add(plus_one);
467 bgIncremental.add(plus_two);
468 bgIncremental.add(minus_one);
469 bgIncremental.add(minus_two);
470 p.add(minus_one, GBC.std().insets(10, 0, 10, 0));
471// p.add(plus_one, GBC.eol().fill(GBC.HORIZONTAL).insets(10, 0, 0, 0));
472 p.add(plus_one, 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(minus_two, GBC.std().insets(10, 0, 10, 0));
482 p.add(plus_two, 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 WindowListener() {
504 @Override
505 public void windowClosing(WindowEvent arg0) {
506 exitMode();
507 Main.map.selectMapMode((MapMode)Main.map.getDefaultButtonAction());
508 }
509 public void windowClosed(WindowEvent e) {}
510 public void windowActivated(WindowEvent arg0) {}
511 public void windowDeactivated(WindowEvent arg0) {}
512 public void windowDeiconified(WindowEvent arg0) {}
513 public void windowIconified(WindowEvent arg0) {}
514 public void windowOpened(WindowEvent arg0) {}
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 }
531
532 private void setNewSelection(OsmPrimitive osm) {
533 Collection<OsmPrimitive> newSelection = new LinkedList<OsmPrimitive>(Main.main.getCurrentDataSet().getSelected());
534 newSelection.clear();
535 newSelection.add(osm);
536 getCurrentDataSet().setSelected(osm);
537 }
538
539}
Note: See TracBrowser for help on using the repository browser.