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

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

fix minor issues

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