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

Last change on this file since 22230 was 22230, checked in by pieren, 15 years ago

fix minor issues before release

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