source: josm/trunk/src/org/openstreetmap/josm/io/remotecontrol/AddTagsDialog.java@ 5876

Last change on this file since 5876 was 5876, checked in by akks, 11 years ago

Remote control: allow adding tags without confirmation for current session (add_tags), see #8612
added parsing of request headers and detecting request sender by IP and "referer" HTTP header

  • Property svn:eol-style set to native
File size: 12.9 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.io.remotecontrol;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.awt.Color;
7import java.awt.Component;
8import java.awt.Font;
9import java.awt.GridBagLayout;
10import java.awt.event.ActionEvent;
11import java.awt.event.KeyEvent;
12import java.awt.event.MouseEvent;
13import java.io.UnsupportedEncodingException;
14import java.net.URLDecoder;
15import java.util.Collection;
16import java.util.HashMap;
17import java.util.HashSet;
18import java.util.Map;
19import java.util.Set;
20import javax.swing.AbstractAction;
21import javax.swing.JCheckBox;
22
23import javax.swing.JPanel;
24import javax.swing.JTable;
25import javax.swing.KeyStroke;
26import javax.swing.table.DefaultTableModel;
27import javax.swing.table.TableCellEditor;
28import javax.swing.table.TableCellRenderer;
29import javax.swing.table.TableModel;
30
31import org.openstreetmap.josm.Main;
32import org.openstreetmap.josm.command.ChangePropertyCommand;
33import org.openstreetmap.josm.data.SelectionChangedListener;
34import org.openstreetmap.josm.data.osm.DataSet;
35import org.openstreetmap.josm.data.osm.OsmPrimitive;
36import org.openstreetmap.josm.gui.ExtendedDialog;
37import org.openstreetmap.josm.gui.util.GuiHelper;
38import org.openstreetmap.josm.gui.util.TableHelper;
39import org.openstreetmap.josm.tools.GBC;
40
41/**
42 *
43 * @author master
44 *
45 * Dialog to add tags as part of the remotecontrol
46 * Existing Keys get grey color and unchecked selectboxes so they will not overwrite the old Key-Value-Pairs by default.
47 * You can choose the tags you want to add by selectboxes. You can edit the tags before you apply them.
48 *
49 */
50public class AddTagsDialog extends ExtendedDialog implements SelectionChangedListener {
51
52
53 /** initially given tags **/
54 String[][] tags;
55
56 private final JTable propertyTable;
57 private Collection<? extends OsmPrimitive> sel;
58 int[] count;
59
60 String sender;
61 static Set<String> trustedSenders = new HashSet<String>();
62
63 /**
64 * Class for displaying "delete from ... objects" in the table
65 */
66 static class DeleteTagMarker {
67 int num;
68 public DeleteTagMarker(int num) {
69 this.num = num;
70 }
71 public String toString() {
72 return tr("<delete from {0} objects>", num);
73 }
74 }
75
76 /**
77 * Class for displaying list of existing tag values in the table
78 */
79 static class ExistingValues {
80 String tag;
81 HashMap<String, Integer> valueCount;
82 public ExistingValues(String tag) {
83 this.tag=tag; valueCount=new HashMap<String, Integer>();
84 }
85
86 int addValue(String val) {
87 Integer c = valueCount.get(val);
88 int r = c==null? 1 : (c.intValue()+1);
89 valueCount.put(val, r);
90 return r;
91 }
92
93 @Override
94 public String toString() {
95 StringBuilder sb=new StringBuilder();
96 for (String k: valueCount.keySet()) {
97 if (sb.length()>0) sb.append(", ");
98 sb.append(k);
99 }
100 return sb.toString();
101 }
102
103 private String getToolTip() {
104 StringBuilder sb=new StringBuilder();
105 sb.append("<html>");
106 sb.append(tr("Old values of"));
107 sb.append(" <b>");
108 sb.append(tag);
109 sb.append("</b><br/>");
110 for (String k: valueCount.keySet()) {
111 sb.append("<b>");
112 sb.append(valueCount.get(k));
113 sb.append(" x </b>");
114 sb.append(k);
115 sb.append("<br/>");
116 }
117 sb.append("</html>");
118 return sb.toString();
119
120 }
121 }
122
123 public AddTagsDialog(String[][] tags, String senderName) {
124 super(Main.parent, tr("Add tags to selected objects"), new String[] { tr("Add selected tags"), tr("Add all tags"), tr("Cancel")},
125 false,
126 true);
127 setToolTipTexts(new String[]{tr("Add checked tags to selected objects"), tr("Shift+Enter: Add all tags to selected objects"), ""});
128
129 this.sender = senderName;
130
131 DataSet.addSelectionListener(this);
132
133
134 final DefaultTableModel tm = new DefaultTableModel(new String[] {tr("Assume"), tr("Key"), tr("Value"), tr("Existing values")}, tags.length) {
135 final Class<?> types[] = {Boolean.class, String.class, Object.class, ExistingValues.class};
136 @Override
137 public Class getColumnClass(int c) {
138 return types[c];
139 }
140
141 };
142
143 sel = Main.main.getCurrentDataSet().getSelected();
144 count = new int[tags.length];
145
146 for (int i = 0; i<tags.length; i++) {
147 count[i] = 0;
148 String key = tags[i][0];
149 String value = tags[i][1], oldValue;
150 Boolean b = Boolean.TRUE;
151 ExistingValues old = new ExistingValues(key);
152 for (OsmPrimitive osm : sel) {
153 oldValue = osm.get(key);
154 if (oldValue!=null) {
155 old.addValue(oldValue);
156 if (!oldValue.equals(value)) {
157 b = Boolean.FALSE;
158 count[i]++;
159 }
160 }
161 }
162 tm.setValueAt(b, i, 0);
163 tm.setValueAt(tags[i][0], i, 1);
164 tm.setValueAt(tags[i][1].isEmpty() ? new DeleteTagMarker(count[i]) : tags[i][1], i, 2);
165 tm.setValueAt(old , i, 3);
166 }
167
168 propertyTable = new JTable(tm) {
169
170 private static final long serialVersionUID = 1L;
171 ///private final DefaultCellEditor textEditor = new DefaultCellEditor( new JTextField() );
172
173 @Override
174 public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
175 Component c = super.prepareRenderer(renderer, row, column);
176 if (count[row]>0) {
177 c.setFont(c.getFont().deriveFont(Font.ITALIC));
178 c.setForeground(new Color(100, 100, 100));
179 } else {
180 c.setFont(c.getFont().deriveFont(Font.PLAIN));
181 c.setForeground(new Color(0, 0, 0));
182 }
183 return c;
184 }
185
186 @Override
187 public TableCellEditor getCellEditor(int row, int column) {
188 Object value = getValueAt(row,column);
189 if (value instanceof DeleteTagMarker) return null;
190 if (value instanceof ExistingValues) return null;
191 return getDefaultEditor(value.getClass());
192 }
193
194 @Override
195 public String getToolTipText(MouseEvent event) {
196 int r = rowAtPoint(event.getPoint());
197 int c = columnAtPoint(event.getPoint());
198 Object o = getValueAt(r, c);
199 if (c==1 || c==2) return o.toString();
200 if (c==3) return ((ExistingValues)o).getToolTip();
201 return tr("Enable the checkbox to accept the value");
202 }
203
204 };
205
206 propertyTable.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN);
207 // a checkbox has a size of 15 px
208 propertyTable.getColumnModel().getColumn(0).setMaxWidth(15);
209 TableHelper.adjustColumnWidth(propertyTable, 1, 150);
210 TableHelper.adjustColumnWidth(propertyTable, 2, 400);
211 TableHelper.adjustColumnWidth(propertyTable, 3, 300);
212 // get edit results if the table looses the focus, for example if a user clicks "add tags"
213 propertyTable.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
214 propertyTable.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, KeyEvent.SHIFT_MASK), "shiftenter");
215 propertyTable.getActionMap().put("shiftenter", new AbstractAction() {
216 @Override public void actionPerformed(ActionEvent e) {
217 buttonAction(1, e); // add all tags on Shift-Enter
218 }
219 });
220
221 // set the content of this AddTagsDialog consisting of the tableHeader and the table itself.
222 JPanel tablePanel = new JPanel();
223 tablePanel.setLayout(new GridBagLayout());
224 tablePanel.add(propertyTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));
225 tablePanel.add(propertyTable, GBC.eol().fill(GBC.BOTH));
226 if (!trustedSenders.contains(sender)) {
227 final JCheckBox c = new JCheckBox();
228 c.setAction(new AbstractAction(tr("Accept all tags from {0} for this session", sender) ) {
229 @Override public void actionPerformed(ActionEvent e) {
230 if (c.isSelected())
231 trustedSenders.add(sender);
232 else
233 trustedSenders.remove(sender);
234 }
235 } );
236 tablePanel.add(c , GBC.eol().insets(20,10,0,0));
237 }
238 setContent(tablePanel);
239 setDefaultButton(2);
240 }
241
242 /**
243 * This method looks for existing tags in the current selection and sets the corresponding boolean in the boolean array existing[]
244 */
245 private void findExistingTags() {
246 TableModel tm = propertyTable.getModel();
247 for (int i=0; i<tm.getRowCount(); i++) {
248 String key = (String)tm.getValueAt(i, 1);
249 String value = (String)tm.getValueAt(i, 1);
250 count[i] = 0;
251 for (OsmPrimitive osm : sel) {
252 if (osm.keySet().contains(key) && !osm.get(key).equals(value)) {
253 count[i]++;
254 break;
255 }
256 }
257 }
258 propertyTable.repaint();
259 }
260
261 /**
262 * If you click the "Add tags" button build a ChangePropertyCommand for every key that has a checked checkbox to apply the key value pair to all selected osm objects.
263 * You get a entry for every key in the command queue.
264 */
265 @Override
266 protected void buttonAction(int buttonIndex, ActionEvent evt) {
267 // if layer all layers were closed, ignore all actions
268 if (Main.main.getCurrentDataSet() != null && buttonIndex != 2) {
269 TableModel tm = propertyTable.getModel();
270 for (int i=0; i<tm.getRowCount(); i++) {
271 if (buttonIndex==1 || (Boolean)tm.getValueAt(i, 0)) {
272 String key =(String)tm.getValueAt(i, 1);
273 Object value = tm.getValueAt(i, 2);
274 Main.main.undoRedo.add(new ChangePropertyCommand(sel,
275 key, value instanceof String ? (String) value : ""));
276 }
277 }
278 }
279 if (buttonIndex == 2) {
280 trustedSenders.remove(sender);
281 }
282 setVisible(false);
283 }
284
285 @Override
286 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
287 sel = newSelection;
288 findExistingTags();
289 }
290
291 /*
292 * parse addtags parameters Example URL (part):
293 * addtags=wikipedia:de%3DResidenzschloss Dresden|name:en%3DDresden Castle
294 */
295 public static void addTags(final Map<String, String> args, final String sender) {
296 if (args.containsKey("addtags")) {
297 GuiHelper.executeByMainWorkerInEDT(new Runnable() {
298
299 public void run() {
300 String[] tags = null;
301 try {
302 tags = URLDecoder.decode(args.get("addtags"), "UTF-8").split("\\|");
303 } catch (UnsupportedEncodingException e) {
304 throw new RuntimeException();
305 }
306 Set<String> tagSet = new HashSet<String>();
307 for (String tag : tags) {
308 if (!tag.trim().isEmpty() && tag.contains("=")) {
309 tagSet.add(tag.trim());
310 }
311 }
312 if (!tagSet.isEmpty()) {
313 String[][] keyValue = new String[tagSet.size()][2];
314 int i = 0;
315 for (String tag : tagSet) {
316 // support a = b===c as "a"="b===c"
317 String [] pair = tag.split("\\s*=\\s*",2);
318 keyValue[i][0] = pair[0];
319 keyValue[i][1] = pair.length<2 ? "": pair[1];
320 i++;
321 }
322 addTagsIfNeeded(keyValue, sender);
323 }
324 }
325
326
327 });
328 }
329 }
330
331 private static void addTagsIfNeeded(String[][] keyValue, String sender) {
332 if (trustedSenders.contains(sender)) {
333 if (Main.main.getCurrentDataSet() != null) {
334 Collection<OsmPrimitive> s = Main.main.getCurrentDataSet().getSelected();
335 for (int j = 0; j < keyValue.length; j++) {
336 Main.main.undoRedo.add(new ChangePropertyCommand(s, keyValue[j][0], keyValue[j][1]));
337 }
338 }
339 } else {
340 new AddTagsDialog(keyValue, sender).showDialog();
341 }
342 }
343}
Note: See TracBrowser for help on using the repository browser.