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

Last change on this file since 8509 was 8509, checked in by Don-vip, 9 years ago

fix many checkstyle violations

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