Changeset 31627 in osm for applications/editors/josm/plugins/OSMRecPlugin/src
- Timestamp:
- 2015-10-14T16:29:26+02:00 (9 years ago)
- Location:
- applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec
- Files:
-
- 2 edited
Legend:
- Unmodified
- Added
- Removed
-
applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecPluginHelper.java
r31615 r31627 37 37 import java.beans.PropertyChangeEvent; 38 38 import java.beans.PropertyChangeListener; 39 import java.io.EOFException;40 39 import java.io.File; 41 40 import java.io.FileInputStream; … … 80 79 import javax.swing.JDialog; 81 80 import javax.swing.JFileChooser; 82 import javax.swing.JFrame;83 81 import javax.swing.JLabel; 84 82 import javax.swing.JList; … … 122 120 import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionListItem; 123 121 import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionManager; 124 import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;122 //import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset; 125 123 import org.openstreetmap.josm.gui.util.GuiHelper; 126 124 import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher; … … 350 348 351 349 public final class TrainingDialog extends AbstractTagsDialog { 352 // final String key;353 // final Map<String, Integer> m;354 // final int row;355 356 // Comparator<AutoCompletionListItem> usedValuesAwareComparator = new Comparator<AutoCompletionListItem>() {357 // @Override358 // public int compare(AutoCompletionListItem o1, AutoCompletionListItem o2) {359 // boolean c1 = m.containsKey(o1.getValue());360 // boolean c2 = m.containsKey(o2.getValue());361 // if (c1 == c2)362 // return String.CASE_INSENSITIVE_ORDER.compare(o1.getValue(), o2.getValue());363 // else if (c1)364 // return -1;365 // else366 // return +1;367 // }368 // };369 350 370 351 ListCellRenderer<AutoCompletionListItem> cellRenderer = new ListCellRenderer<AutoCompletionListItem>() { … … 433 414 setButtonIcons(new String[] {"ok","cancel"}); 434 415 setCancelButton(2); 435 //configureContextsensitiveHelp("/Dialog/EditValue", true /* show help button */);436 // this.key = key;437 // this.row = row;438 // this.m = map;439 416 440 417 JPanel mainPanel = new JPanel(new BorderLayout(10,10)); //6,6 … … 488 465 daysField.setEnabled(false); 489 466 userNameField.setColumns(FIELD_COLUMNS); 490 daysField.setColumns(FIELD_COLUMNS); 491 467 daysField.setColumns(FIELD_COLUMNS); 492 468 493 469 Collection<String> fileHistory = Main.pref.getCollection("file-open.history"); … … 765 741 List<AutoCompletionListItem> keyList = autocomplete.getKeys(); 766 742 Collections.sort(keyList, defaultACItemComparator); 767 768 // keys = new AutoCompletingComboBox(key);769 // keys.setPossibleACItems(keyList);770 // keys.setEditable(true);771 // keys.setSelectedItem(key);772 773 // List<AutoCompletionListItem> valueList = autocomplete.getValues(getAutocompletionKeys(key));774 // Collections.sort(valueList, usedValuesAwareComparator);775 // final String selection= m.size()!=1?tr("<different>"):m.entrySet().iterator().next().getKey();776 // values = new AutoCompletingComboBox(selection);777 // values.setRenderer(cellRenderer);778 // values.setEditable(true);779 // values.setPossibleACItems(valueList);780 // values.setSelectedItem(selection);781 // values.getEditor().setItem(selection);782 // values.getEditor().addActionListener(new ActionListener() {783 // @Override784 // public void actionPerformed(ActionEvent e) {785 // buttonAction(0, null); // emulate OK button click786 // }787 // });788 // addFocusAdapter(autocomplete, usedValuesAwareComparator);789 743 790 744 setContent(mainPanel, false); … … 1022 976 } 1023 977 } 1024 1025 // /**1026 // * Edit tags of multiple selected objects according to selected ComboBox values1027 // * If value == "", tag will be deleted1028 // * Confirmations may be needed.1029 // */1030 // private void performTagEdit() {1031 // String value = Tag.removeWhiteSpaces(values.getEditor().getItem().toString());1032 // value = Normalizer.normalize(value, java.text.Normalizer.Form.NFC);1033 // if (value.isEmpty()) {1034 // value = null; // delete the key1035 // }1036 // String newkey = Tag.removeWhiteSpaces(keys.getEditor().getItem().toString());1037 // newkey = Normalizer.normalize(newkey, java.text.Normalizer.Form.NFC);1038 // if (newkey.isEmpty()) {1039 // newkey = key;1040 // value = null; // delete the key instead1041 // }1042 // if (key.equals(newkey) && tr("<different>").equals(value))1043 // return;1044 // if (key.equals(newkey) || value == null) {1045 // Main.main.undoRedo.add(new ChangePropertyCommand(sel, newkey, value));1046 // AutoCompletionManager.rememberUserInput(newkey, value, true);1047 // } else {1048 // for (OsmPrimitive osm: sel) {1049 // if (osm.get(newkey) != null) {1050 // if (!warnOverwriteKey(tr("You changed the key from ''{0}'' to ''{1}''.", key, newkey),1051 // "overwriteEditKey"))1052 // return;1053 // break;1054 // }1055 // }1056 // Collection<Command> commands = new ArrayList<>();1057 // commands.add(new ChangePropertyCommand(sel, key, null));1058 // if (value.equals(tr("<different>"))) {1059 // Map<String, List<OsmPrimitive>> map = new HashMap<>();1060 // for (OsmPrimitive osm: sel) {1061 // String val = osm.get(key);1062 // if (val != null) {1063 // if (map.containsKey(val)) {1064 // map.get(val).add(osm);1065 // } else {1066 // List<OsmPrimitive> v = new ArrayList<>();1067 // v.add(osm);1068 // map.put(val, v);1069 // }1070 // }1071 // }1072 // for (Map.Entry<String, List<OsmPrimitive>> e: map.entrySet()) {1073 // commands.add(new ChangePropertyCommand(e.getValue(), newkey, e.getKey()));1074 // }1075 // } else {1076 // commands.add(new ChangePropertyCommand(sel, newkey, value));1077 // AutoCompletionManager.rememberUserInput(newkey, value, false);1078 // }1079 // Main.main.undoRedo.add(new SequenceCommand(1080 // trn("Change properties of up to {0} object",1081 // "Change properties of up to {0} objects", sel.size(), sel.size()),1082 // commands));1083 // }1084 //1085 // changedKey = newkey;1086 // }1087 978 } 1088 979 … … 1424 1315 } 1425 1316 }; 1426 1427 1428 //pane.showConfirmDialog(); 1429 //pane.addPropertyChangeListener(JOptionPane.VALUE_PROPERTY); 1430 1431 1432 //JButton ok = dlg.getRootPane().getDefaultButton(); 1317 1433 1318 dlg = pane.createDialog(Main.parent, tr("Model Settings")); 1434 1319 dlg.setVisible(true); 1435 1320 1436 /*1437 //returned value of pane.getValue indicates the key pressed by the user. "0" is for the OK button1438 int buttonValue = -1;1439 if(pane.getValue() != null){1440 //System.out.println("type? " + pane.getValue());1441 buttonValue = (int) pane.getValue();1442 }1443 1444 System.out.println("value of model sel button: " + pane.getValue());1445 1446 if(buttonValue == 0 && useModelCombinationCheckbox.isSelected()){1447 useCombinedModel = true;1448 System.out.println("\nold - USE COMBINED MODEL\n");1449 //recompute predictions with combination1450 1451 //modelWithClasses = false;1452 addDialog.loadSVMmodel();1453 addDialog.createOSMObject(sel);1454 saveCombinedModel();1455 dlg.setVisible(false);1456 //this.setVisible(false);1457 }1458 else if(useModelCombinationCheckbox.isSelected()){1459 useCombinedModel = true;1460 System.out.println("old - use combined model");1461 1462 addDialog.loadSVMmodel();1463 addDialog.createOSMObject(sel);1464 dlg.setVisible(false);1465 }1466 else{1467 System.out.println("old - don t use combined model, use custom model");1468 useCombinedModel = false;1469 useCustomSVMModel = true;1470 addDialog.loadSVMmodel();1471 addDialog.createOSMObject(sel);1472 dlg.setVisible(false);1473 }1474 */1475 1321 } 1476 1322 … … 1505 1351 else{ 1506 1352 if(svmModelPath.contains("\\")){ 1507 svmModelText = svmModelPath.substring(svmModelPath.lastIndexOf(" /"));1353 svmModelText = svmModelPath.substring(svmModelPath.lastIndexOf("\\")); 1508 1354 } 1509 1355 else{ … … 1572 1418 1573 1419 try{ 1420 //TODO replace "," with "." to parse doubles with commas 1574 1421 Double weightValue = Double.parseDouble(weightField.getText()); 1575 1422 … … 1660 1507 } finally { 1661 1508 try { 1662 in.close(); 1663 fileIn.close(); 1509 if(in!=null){ 1510 in.close(); 1511 } 1512 if(fileIn!=null){ 1513 fileIn.close(); 1514 } 1515 1664 1516 } catch (IOException ex) { 1665 1517 Logger.getLogger(OSMRecPluginHelper.class.getName()).log(Level.SEVERE, null, ex); … … 1734 1586 JPanel mainPanel = new JPanel(new GridBagLayout()); //original panel, will be wrapped by the splitPanel 1735 1587 JPanel recommendPanel = new JPanel(new BorderLayout(10,10)); //will contain listPanel, action panel 1736 JPanel 1737 JPanel 1588 JPanel listPanel = new JPanel(new BorderLayout(10,10)); //class recommend label, recommendation list 1589 JPanel actionsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); //model selection buttons or configuration 1738 1590 1739 1591 addAndContinueButton = new javax.swing.JButton("Add and continue"); … … 2063 1915 Map<String, String> map = new HashMap<>(); 2064 1916 map.put(t.getKey(), t.getValue()); 2065 for (TaggingPreset tp : TaggingPreset.getMatchingPresets(null, map, false)) {2066 icon = tp.getIcon();2067 if (icon != null) {2068 break;2069 }2070 }1917 // for (TaggingPreset tp : TaggingPreset.getMatchingPresets(null, map, false)) { 1918 // icon = tp.getIcon(); 1919 // if (icon != null) { 1920 // break; 1921 // } 1922 // } 2071 1923 // If still nothing display an empty icon 2072 1924 if (icon == null) { … … 2168 2020 private void loadSVMmodel() { 2169 2021 File modelDirectory = new File(MODEL_PATH); 2170 File modelFile = null;2022 File modelFile; 2171 2023 if(useCombinedModel){ 2172 2024 if(filesAndWeights.isEmpty()){ … … 2175 2027 System.out.println("Using default/last model with classes: " + modelDirectory.getAbsolutePath() + "/model_with_classes"); 2176 2028 modelFile = new File(modelDirectory.getAbsolutePath() + "/model_with_classes"); 2029 try { 2030 System.out.println("try to load model: " + modelFile.getAbsolutePath()); 2031 modelSVM = Model.load(modelFile); 2032 System.out.println("model loaded!"); 2033 2034 } catch (IOException ex) { 2035 Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex); 2036 } 2037 modelSVMLabelSize = modelSVM.getLabels().length; 2038 modelSVMLabels = modelSVM.getLabels(); 2177 2039 } 2178 2040 else{ 2179 2041 System.out.println("Using default/last model without classes: " + modelDirectory.getAbsolutePath() + "/best_model"); 2180 2042 modelFile = new File(modelDirectory.getAbsolutePath() + "/best_model"); 2043 try { 2044 System.out.println("try to load model: " + modelFile.getAbsolutePath()); 2045 modelSVM = Model.load(modelFile); 2046 System.out.println("model loaded!"); 2047 2048 } catch (IOException ex) { 2049 Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex); 2050 } 2051 modelSVMLabelSize = modelSVM.getLabels().length; 2052 modelSVMLabels = modelSVM.getLabels(); 2181 2053 } 2182 2054 } … … 2273 2145 modelSVMLabelSize = modelSVM.getLabels().length; 2274 2146 modelSVMLabels = modelSVM.getLabels(); 2275 } 2276 2277 2278 2279 //try to use last SVM model 2280 /* 2281 if(useCombinedModel){ 2282 System.out.println("Using combined model."); 2283 if(modelWithClasses){ //check filenames to define if model with classes is selected 2284 useCombinedSVMmodels(sel, true); 2285 } 2286 else{ 2287 useCombinedSVMmodels(sel, false); 2288 } 2289 2290 return; 2291 } 2292 //String modelDirectoryPath = new File(MAIN_PATH).getParentFile() + "/OSMRec_models"; 2293 //File modelDirectory = new File(MODEL_PATH); 2294 2295 //File modelFile; 2296 if(useCustomSVMModel){ 2297 System.out.println("using custom model: " + customSVMModelPath); 2298 modelFile = new File(customSVMModelPath); 2299 } 2300 else{ 2301 if(modelWithClasses){ 2302 System.out.println("using model with classes: " + modelDirectory.getAbsolutePath() + "/model_with_classes"); 2303 modelFile = new File(modelDirectory.getAbsolutePath() + "/model_with_classes"); 2304 } 2305 else { 2306 System.out.println("using best model: " + modelDirectory.getAbsolutePath() + "/best_model"); 2307 modelFile = new File(modelDirectory.getAbsolutePath() + "/best_model"); 2308 } 2309 } 2310 2311 try { 2312 modelSVM = Model.load(modelFile); 2313 //System.out.println("model loaded: " + modelFile.getAbsolutePath()); 2314 } catch (IOException ex) { 2315 Logger.getLogger(TrainWorker.class.getName()).log(Level.SEVERE, null, ex); 2316 } 2317 modelSVMLabelSize = modelSVM.getLabels().length; 2318 modelSVMLabels = modelSVM.getLabels(); 2319 //System.out.println("is model path same as this? " + MODEL_PATH + "\n" + modelDirectoryPath); 2320 */ 2147 } 2321 2148 } 2322 2149 … … 2752 2579 } 2753 2580 2754 /*2755 int predicted1 = modelSVMLabels[scoresValues.get(scores[scores.length-1])];2756 int predicted2 = modelSVMLabels[scoresValues.get(scores[scores.length-2])];2757 int predicted3 = modelSVMLabels[scoresValues.get(scores[scores.length-3])];2758 int predicted4 = modelSVMLabels[scoresValues.get(scores[scores.length-4])];2759 int predicted5 = modelSVMLabels[scoresValues.get(scores[scores.length-5])];2760 int predicted6 = modelSVMLabels[scoresValues.get(scores[scores.length-6])];2761 int predicted7 = modelSVMLabels[scoresValues.get(scores[scores.length-7])];2762 int predicted8 = modelSVMLabels[scoresValues.get(scores[scores.length-8])];2763 int predicted9 = modelSVMLabels[scoresValues.get(scores[scores.length-9])];2764 int predicted10 = modelSVMLabels[scoresValues.get(scores[scores.length-10])];2765 2766 //System.out.println("classes predicted: " + na1 + " " + na2 + " " + na3);2767 String[] predictedTags = new String[10];2768 for( Map.Entry<String, Integer> entry : mapperWithIDs.entrySet()){2769 2770 if(entry.getValue().equals(predicted1)){2771 //System.out.println("1st predicted class: " +entry.getKey());2772 predictedTags[0] = entry.getKey();2773 }2774 else if(entry.getValue().equals(predicted2)){2775 predictedTags[1] = entry.getKey();2776 //System.out.println("2nd predicted class: " +entry.getKey());2777 }2778 else if(entry.getValue().equals(predicted3)){2779 predictedTags[2] = entry.getKey();2780 //System.out.println("3rd predicted class: " +entry.getKey());2781 }2782 else if(entry.getValue().equals(predicted4)){2783 predictedTags[3] = entry.getKey();2784 //System.out.println("2nd predicted class: " +entry.getKey());2785 }2786 else if(entry.getValue().equals(predicted5)){2787 predictedTags[4] = entry.getKey();2788 //System.out.println("3rd predicted class: " +entry.getKey());2789 }2790 else if(entry.getValue().equals(predicted6)){2791 predictedTags[5] = entry.getKey();2792 //System.out.println("2nd predicted class: " +entry.getKey());2793 }2794 else if(entry.getValue().equals(predicted7)){2795 predictedTags[6] = entry.getKey();2796 //System.out.println("3rd predicted class: " +entry.getKey());2797 }2798 else if(entry.getValue().equals(predicted8)){2799 predictedTags[7] = entry.getKey();2800 //System.out.println("2nd predicted class: " +entry.getKey());2801 }2802 else if(entry.getValue().equals(predicted9)){2803 predictedTags[8] = entry.getKey();2804 //System.out.println("3rd predicted class: " +entry.getKey());2805 }2806 else if(entry.getValue().equals(predicted10)){2807 predictedTags[9] = entry.getKey();2808 //System.out.println("3rd predicted class: " +entry.getKey());2809 }2810 }2811 */2812 2581 //clearing model, to add the new computed classes in jlist 2813 2582 model.clear(); -
applications/editors/josm/plugins/OSMRecPlugin/src/org/openstreetmap/josm/plugins/osmrec/OSMRecToggleDialog.java
r31618 r31627 2 2 package org.openstreetmap.josm.plugins.osmrec; 3 3 4 import java.awt.Component;5 import java.awt.Container;6 import java.awt.Font;7 4 import java.awt.GridBagLayout; 8 import java.awt.Point;9 5 import java.awt.event.ActionEvent; 10 import java.awt.event.InputEvent;11 6 import java.awt.event.KeyEvent; 12 7 import java.awt.event.MouseAdapter; 13 8 import java.awt.event.MouseEvent; 14 import java.net.HttpURLConnection;15 import java.net.URI;16 import java.net.URISyntaxException;17 9 import java.util.ArrayList; 18 10 import java.util.Arrays; … … 20 12 import java.util.Collections; 21 13 import java.util.Comparator; 22 import java.util.EnumSet;23 14 import java.util.HashMap; 24 15 import java.util.HashSet; 25 import java.util.LinkedList;26 16 import java.util.List; 27 17 import java.util.Map; … … 29 19 import java.util.Set; 30 20 import java.util.TreeMap; 31 import java.util.TreeSet;32 33 import javax.swing.AbstractAction;34 import javax.swing.JComponent;35 21 import javax.swing.JLabel; 36 22 import javax.swing.JPanel; 37 import javax.swing.JPopupMenu;38 23 import javax.swing.JScrollPane; 39 24 import javax.swing.JTable; 40 import javax.swing.KeyStroke;41 import javax.swing.ListSelectionModel;42 25 import javax.swing.event.ListSelectionEvent; 43 26 import javax.swing.event.ListSelectionListener; 44 import javax.swing.table.DefaultTableCellRenderer;45 27 import javax.swing.table.DefaultTableModel; 46 import javax.swing.table.TableColumnModel;47 28 import javax.swing.table.TableModel; 48 29 49 30 import org.openstreetmap.josm.Main; 50 31 import org.openstreetmap.josm.actions.JosmAction; 51 import org.openstreetmap.josm.actions.relation.DownloadMembersAction;52 import org.openstreetmap.josm.actions.relation.DownloadSelectedIncompleteMembersAction;53 import org.openstreetmap.josm.actions.relation.SelectInRelationListAction;54 import org.openstreetmap.josm.actions.relation.SelectMembersAction;55 import org.openstreetmap.josm.actions.relation.SelectRelationAction;56 import org.openstreetmap.josm.actions.search.SearchAction.SearchMode;57 import org.openstreetmap.josm.actions.search.SearchAction.SearchSetting;58 import org.openstreetmap.josm.command.ChangeCommand;59 import org.openstreetmap.josm.command.ChangePropertyCommand;60 import org.openstreetmap.josm.command.Command;61 import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;62 32 import org.openstreetmap.josm.data.SelectionChangedListener; 63 33 import org.openstreetmap.josm.data.osm.IRelation; 64 import org.openstreetmap.josm.data.osm.Node;65 34 import org.openstreetmap.josm.data.osm.OsmPrimitive; 66 35 import org.openstreetmap.josm.data.osm.Relation; 67 36 import org.openstreetmap.josm.data.osm.RelationMember; 68 37 import org.openstreetmap.josm.data.osm.Tag; 69 import org.openstreetmap.josm.data.osm.Way;70 38 import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent; 71 39 import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter; 72 import org.openstreetmap.josm.data.osm.event.DatasetEventManager;73 import org.openstreetmap.josm.data.osm.event.DatasetEventManager.FireMode;74 import org.openstreetmap.josm.data.osm.event.SelectionEventManager;75 import org.openstreetmap.josm.gui.ConditionalOptionPaneUtil;76 40 import org.openstreetmap.josm.gui.DefaultNameFormatter; 77 import org.openstreetmap.josm.gui.ExtendedDialog;78 import org.openstreetmap.josm.gui.MapView;79 import org.openstreetmap.josm.gui.PopupMenuHandler;80 41 import org.openstreetmap.josm.gui.SideButton; 81 42 import org.openstreetmap.josm.gui.dialogs.ToggleDialog; 82 import org.openstreetmap.josm.gui.dialogs.properties.PresetListPanel;83 import org.openstreetmap.josm.gui.dialogs.properties.PropertiesCellRenderer;84 import org.openstreetmap.josm.gui.dialogs.relation.RelationEditor;85 import org.openstreetmap.josm.gui.help.HelpUtil;86 import org.openstreetmap.josm.gui.layer.OsmDataLayer;87 import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetHandler;88 import org.openstreetmap.josm.gui.tagging.presets.TaggingPreset;89 import org.openstreetmap.josm.gui.tagging.presets.TaggingPresetType;90 import org.openstreetmap.josm.gui.util.GuiHelper;91 import org.openstreetmap.josm.gui.util.HighlightHelper;92 import org.openstreetmap.josm.gui.widgets.PopupMenuLauncher;93 import org.openstreetmap.josm.tools.GBC;94 43 import static org.openstreetmap.josm.tools.I18n.tr; 95 import org.openstreetmap.josm.tools.ImageProvider;96 import org.openstreetmap.josm.tools.InputMapUtils;97 import org.openstreetmap.josm.tools.LanguageInfo;98 import org.openstreetmap.josm.tools.OpenBrowser;99 44 import org.openstreetmap.josm.tools.Predicates; 100 45 import org.openstreetmap.josm.tools.Shortcut; … … 102 47 103 48 /** 104 * This class is a modification of the PropertiesDialog .49 * This class is a modification of the PropertiesDialog for the OSMRec. 105 50 * 106 51 * … … 120 65 * 121 66 * @author imi 67 * @author nkaragiannakis 122 68 */ 123 69 public class OSMRecToggleDialog extends ToggleDialog 124 implements SelectionChangedListener, MapView.EditLayerChangeListener,DataSetListenerAdapter.Listener {70 implements SelectionChangedListener, DataSetListenerAdapter.Listener { 125 71 126 72 /** … … 152 98 private final JPanel bothTables = new JPanel(); 153 99 154 // Popup menus155 private final JPopupMenu tagMenu = new JPopupMenu();156 private final JPopupMenu membershipMenu = new JPopupMenu();157 private final JPopupMenu blankSpaceMenu = new JPopupMenu();158 159 // Popup menu handlers160 private final transient PopupMenuHandler tagMenuHandler = new PopupMenuHandler(tagMenu);161 private final transient PopupMenuHandler membershipMenuHandler = new PopupMenuHandler(membershipMenu);162 private final transient PopupMenuHandler blankSpaceMenuHandler = new PopupMenuHandler(blankSpaceMenu);163 164 100 private final transient Map<String, Map<String, Integer>> valueCount = new TreeMap<>(); 165 101 /** … … 168 104 private final transient OSMRecPluginHelper editHelper = new OSMRecPluginHelper(tagData, valueCount); 169 105 170 private final transient DataSetListenerAdapter dataChangedAdapter = new DataSetListenerAdapter(this);171 private final HelpAction helpAction = new HelpAction();172 private final PasteValueAction pasteValueAction = new PasteValueAction();173 private final CopyValueAction copyValueAction = new CopyValueAction();174 private final CopyKeyValueAction copyKeyValueAction = new CopyKeyValueAction();175 private final CopyAllKeyValueAction copyAllKeyValueAction = new CopyAllKeyValueAction();176 private final SearchAction searchActionSame = new SearchAction(true);177 private final SearchAction searchActionAny = new SearchAction(false);178 106 private final AddAction addAction = new AddAction(); 179 107 private final EditActionTrain editAction = new EditActionTrain(); 180 private final DeleteAction deleteAction = new DeleteAction(); 181 private final JosmAction[] josmActions = new JosmAction[]{addAction, editAction, deleteAction}; 182 183 // relation actions 184 private final SelectInRelationListAction setRelationSelectionAction = new SelectInRelationListAction(); 185 private final SelectRelationAction selectRelationAction = new SelectRelationAction(false); 186 private final SelectRelationAction addRelationToSelectionAction = new SelectRelationAction(true); 187 188 private final DownloadMembersAction downloadMembersAction = new DownloadMembersAction(); 189 private final DownloadSelectedIncompleteMembersAction downloadSelectedIncompleteMembersAction = 190 new DownloadSelectedIncompleteMembersAction(); 191 192 private final SelectMembersAction selectMembersAction = new SelectMembersAction(false); 193 private final SelectMembersAction addMembersToSelectionAction = new SelectMembersAction(true); 194 195 private final transient HighlightHelper highlightHelper= new HighlightHelper(); 108 // private final DeleteAction deleteAction = new DeleteAction(); 109 // private final JosmAction[] josmActions = new JosmAction[]{addAction, editAction, deleteAction}; 196 110 197 111 /** … … 203 117 */ 204 118 private final SideButton btnEdit = new SideButton(editAction); 205 /**206 * The Delete button (needed to be able to disable it)207 */208 private final SideButton btnDel = new SideButton(deleteAction);209 /**210 * Matching preset display class211 */212 private final PresetListPanel presets = new PresetListPanel();213 119 214 120 /** … … 218 124 + tr("Select objects or create new objects and get recommendation.") + "</p></html>"); 219 125 220 private final transient TaggingPresetHandler presetHandler = new TaggingPresetHandler() {221 @Override public void updateTags(List<Tag> tags) {222 Command command = TaggingPreset.createCommand(getSelection(), tags);223 if (command != null) Main.main.undoRedo.add(command);224 }225 226 @Override public Collection<OsmPrimitive> getSelection() {227 if (Main.main == null) return null;228 return Main.main.getInProgressSelection();229 }230 };231 232 126 // <editor-fold defaultstate="collapsed" desc="Dialog construction and helper methods"> 233 127 234 128 /** 235 * Create a new PropertiesDialog129 * Create a new OSMRecToggleDialog 236 130 */ 237 131 public OSMRecToggleDialog() { … … 239 133 Shortcut.registerShortcut("subwindow:properties", tr("Toggle: {0}", tr("Tags/Memberships")), KeyEvent.VK_P, 240 134 Shortcut.ALT_SHIFT), 150, true); 241 HelpUtil.setHelpContext(this, HelpUtil.ht("/Dialog/TagsMembership")); 242 243 setupTagsMenu(); 244 buildTagsTable(); //my 245 246 setupMembershipMenu(); //my 247 buildMembershipTable(); 248 249 // combine both tables and wrap them in a scrollPane 250 boolean top = Main.pref.getBoolean("properties.presets.top", true); 135 136 System.out.println("cleaning test.."); 251 137 bothTables.setLayout(new GridBagLayout()); 252 if(top) {253 bothTables.add(presets, GBC.std().fill(GBC.HORIZONTAL).insets(5, 2, 5, 2).anchor(GBC.NORTHWEST));254 double epsilon = Double.MIN_VALUE; // need to set a weight or else anchor value is ignored255 bothTables.add(pluginHook, GBC.eol().insets(0,1,1,1).anchor(GBC.NORTHEAST).weight(epsilon, epsilon));256 }257 bothTables.add(selectSth, GBC.eol().fill().insets(10, 10, 10, 10));258 bothTables.add(tagTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));259 bothTables.add(tagTable, GBC.eol().fill(GBC.BOTH));260 bothTables.add(membershipTable.getTableHeader(), GBC.eol().fill(GBC.HORIZONTAL));261 bothTables.add(membershipTable, GBC.eol().fill(GBC.BOTH));262 if(!top) {263 bothTables.add(presets, GBC.eol().fill(GBC.HORIZONTAL).insets(5, 2, 5, 2));264 }265 266 138 bothTables.setVisible(false); //my 267 setupBlankSpaceMenu();268 setupKeyboardShortcuts();269 270 139 // Let the actions know when selection in the tables change 271 140 tagTable.getSelectionModel().addListSelectionListener(editAction); 272 141 membershipTable.getSelectionModel().addListSelectionListener(editAction); 273 tagTable.getSelectionModel().addListSelectionListener(deleteAction);274 membershipTable.getSelectionModel().addListSelectionListener(deleteAction);275 142 276 143 JScrollPane scrollPane = (JScrollPane) createLayout(bothTables, true, 277 Arrays.asList(this.btnAdd, this.btnEdit , this.btnDel));144 Arrays.asList(this.btnAdd, this.btnEdit)); 278 145 279 146 MouseClickWatch mouseClickWatch = new MouseClickWatch(); … … 281 148 membershipTable.addMouseListener(mouseClickWatch); 282 149 scrollPane.addMouseListener(mouseClickWatch); 283 284 selectSth.setPreferredSize(scrollPane.getSize());285 presets.setSize(scrollPane.getSize());286 287 150 editHelper.loadTagsIfNeeded(); 288 151 289 Main.pref.addPreferenceChangeListener(this);290 scrollPane.setVisible(false); //my //hide the tags/memberships altogether291 }292 293 private void buildTagsTable() {294 // setting up the tags table295 tagData.setColumnIdentifiers(new String[]{tr("Key"),tr("Value")});296 297 tagTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);298 tagTable.getTableHeader().setReorderingAllowed(false);299 300 PropertiesCellRenderer cellRenderer = new PropertiesCellRenderer();301 tagTable.getColumnModel().getColumn(0).setCellRenderer(cellRenderer);302 tagTable.getColumnModel().getColumn(1).setCellRenderer(cellRenderer);303 304 }305 306 private void buildMembershipTable() {307 membershipData.setColumnIdentifiers(new String[]{tr("Member Of"),tr("Role"),tr("Position")});308 membershipTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);309 310 TableColumnModel mod = membershipTable.getColumnModel();311 membershipTable.getTableHeader().setReorderingAllowed(false);312 mod.getColumn(0).setCellRenderer(new DefaultTableCellRenderer() {313 @Override public Component getTableCellRendererComponent(JTable table, Object value,314 boolean isSelected, boolean hasFocus, int row, int column) {315 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);316 if (value == null)317 return this;318 if (c instanceof JLabel) {319 JLabel label = (JLabel)c;320 Relation r = (Relation)value;321 label.setText(r.getDisplayName(DefaultNameFormatter.getInstance()));322 if (r.isDisabledAndHidden()) {323 label.setFont(label.getFont().deriveFont(Font.ITALIC));324 }325 }326 return c;327 }328 });329 330 mod.getColumn(1).setCellRenderer(new DefaultTableCellRenderer() {331 @Override public Component getTableCellRendererComponent(JTable table, Object value,332 boolean isSelected, boolean hasFocus, int row, int column) {333 if (value == null)334 return this;335 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);336 boolean isDisabledAndHidden = ((Relation) table.getValueAt(row, 0)).isDisabledAndHidden();337 if (c instanceof JLabel) {338 JLabel label = (JLabel) c;339 label.setText(((MemberInfo) value).getRoleString());340 if (isDisabledAndHidden) {341 label.setFont(label.getFont().deriveFont(Font.ITALIC));342 }343 }344 return c;345 }346 });347 348 mod.getColumn(2).setCellRenderer(new DefaultTableCellRenderer() {349 @Override public Component getTableCellRendererComponent(JTable table, Object value,350 boolean isSelected, boolean hasFocus, int row, int column) {351 Component c = super.getTableCellRendererComponent(table, value, isSelected, false, row, column);352 boolean isDisabledAndHidden = ((Relation) table.getValueAt(row, 0)).isDisabledAndHidden();353 if (c instanceof JLabel) {354 JLabel label = (JLabel)c;355 label.setText(((MemberInfo) table.getValueAt(row, 1)).getPositionString());356 if (isDisabledAndHidden) {357 label.setFont(label.getFont().deriveFont(Font.ITALIC));358 }359 }360 return c;361 }362 });363 mod.getColumn(2).setPreferredWidth(20);364 mod.getColumn(1).setPreferredWidth(40);365 mod.getColumn(0).setPreferredWidth(200);366 }367 368 /**369 * Creates the popup menu @field blankSpaceMenu and its launcher on main panel.370 */371 private void setupBlankSpaceMenu() {372 if (Main.pref.getBoolean("properties.menu.add_edit_delete", true)) {373 blankSpaceMenuHandler.addAction(addAction);374 PopupMenuLauncher launcher = new PopupMenuLauncher(blankSpaceMenu) {375 @Override376 protected boolean checkSelection(Component component, Point p) {377 if (component instanceof JTable) {378 return ((JTable) component).rowAtPoint(p) == -1;379 }380 return true;381 }382 };383 bothTables.addMouseListener(launcher);384 tagTable.addMouseListener(launcher);385 }386 }387 388 /**389 * Creates the popup menu @field membershipMenu and its launcher on membership table.390 */391 private void setupMembershipMenu() {392 // setting up the membership table393 if (Main.pref.getBoolean("properties.menu.add_edit_delete", true)) {394 membershipMenuHandler.addAction(editAction);395 membershipMenuHandler.addAction(deleteAction);396 membershipMenu.addSeparator();397 }398 membershipMenuHandler.addAction(setRelationSelectionAction);399 membershipMenuHandler.addAction(selectRelationAction);400 membershipMenuHandler.addAction(addRelationToSelectionAction);401 membershipMenuHandler.addAction(selectMembersAction);402 membershipMenuHandler.addAction(addMembersToSelectionAction);403 membershipMenu.addSeparator();404 membershipMenuHandler.addAction(downloadMembersAction);405 membershipMenuHandler.addAction(downloadSelectedIncompleteMembersAction);406 membershipMenu.addSeparator();407 membershipMenu.add(helpAction);408 409 membershipTable.addMouseListener(new PopupMenuLauncher(membershipMenu) {410 @Override411 protected int checkTableSelection(JTable table, Point p) {412 int row = super.checkTableSelection(table, p);413 List<Relation> rels = new ArrayList<>();414 for (int i: table.getSelectedRows()) {415 rels.add((Relation) table.getValueAt(i, 0));416 }417 membershipMenuHandler.setPrimitives(rels);418 return row;419 }420 421 @Override422 public void mouseClicked(MouseEvent e) {423 //update highlights424 if (Main.isDisplayingMapView()) {425 int row = membershipTable.rowAtPoint(e.getPoint());426 if (row>=0) {427 if (highlightHelper.highlightOnly((Relation) membershipTable.getValueAt(row, 0))) {428 Main.map.mapView.repaint();429 }430 }431 }432 super.mouseClicked(e);433 }434 435 @Override436 public void mouseExited(MouseEvent me) {437 highlightHelper.clear();438 }439 });440 }441 442 /**443 * Creates the popup menu @field tagMenu and its launcher on tag table.444 */445 private void setupTagsMenu() {446 if (Main.pref.getBoolean("properties.menu.add_edit_delete", true)) {447 tagMenu.add(addAction);448 tagMenu.add(editAction);449 tagMenu.add(deleteAction);450 tagMenu.addSeparator();451 }452 tagMenu.add(pasteValueAction);453 tagMenu.add(copyValueAction);454 tagMenu.add(copyKeyValueAction);455 tagMenu.add(copyAllKeyValueAction);456 tagMenu.addSeparator();457 tagMenu.add(searchActionAny);458 tagMenu.add(searchActionSame);459 tagMenu.addSeparator();460 tagMenu.add(helpAction);461 tagTable.addMouseListener(new PopupMenuLauncher(tagMenu));462 }463 464 /**465 * Assigns all needed keys like Enter and Spacebar to most important actions.466 */467 private void setupKeyboardShortcuts() {468 469 // ENTER = editAction, open "edit" dialog470 tagTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)471 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "onTableEnter");472 tagTable.getActionMap().put("onTableEnter",editAction);473 membershipTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)474 .put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),"onTableEnter");475 membershipTable.getActionMap().put("onTableEnter",editAction);476 477 // INSERT button = addAction, open "add tag" dialog478 tagTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)479 .put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0),"onTableInsert");480 tagTable.getActionMap().put("onTableInsert",addAction);481 482 // unassign some standard shortcuts for JTable to allow upload / download / image browsing483 InputMapUtils.unassignCtrlShiftUpDown(tagTable, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);484 InputMapUtils.unassignPageUpDown(tagTable, JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);485 486 // unassign some standard shortcuts for correct copy-pasting, fix #8508487 tagTable.setTransferHandler(null);488 489 tagTable.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT)490 .put(KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_MASK),"onCopy");491 tagTable.getActionMap().put("onCopy",copyKeyValueAction);492 493 // allow using enter to add tags for all look&feel configurations494 InputMapUtils.enableEnter(this.btnAdd);495 496 // DEL button = deleteAction497 getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(498 KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),"delete"499 );500 getActionMap().put("delete", deleteAction);501 502 // F1 button = custom help action503 getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(504 KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0), "onHelp");505 getActionMap().put("onHelp", helpAction);506 152 } 507 153 … … 515 161 Relation relation = (Relation)membershipData.getValueAt(row, 0); 516 162 Main.map.relationListDialog.selectRelation(relation); 517 RelationEditor.getEditor(518 Main.main.getEditLayer(),519 relation,520 ((MemberInfo) membershipData.getValueAt(row, 1)).role521 ).setVisible(true);522 163 } 523 164 … … 543 184 544 185 @Override 545 public void showNotify() {546 DatasetEventManager.getInstance().addDatasetListener(dataChangedAdapter, FireMode.IN_EDT_CONSOLIDATED);547 SelectionEventManager.getInstance().addSelectionListener(this, FireMode.IN_EDT_CONSOLIDATED);548 MapView.addEditLayerChangeListener(this);549 for (JosmAction action : josmActions) {550 Main.registerActionShortcut(action);551 }552 updateSelection();553 }554 555 @Override556 public void hideNotify() {557 DatasetEventManager.getInstance().removeDatasetListener(dataChangedAdapter);558 SelectionEventManager.getInstance().removeSelectionListener(this);559 MapView.removeEditLayerChangeListener(this);560 for (JosmAction action : josmActions) {561 Main.unregisterActionShortcut(action);562 }563 }564 565 @Override566 public void setVisible(boolean b) {567 super.setVisible(b);568 if (b && Main.main.getCurrentDataSet() != null) {569 updateSelection();570 }571 }572 573 @Override574 public void destroy() {575 super.destroy();576 Main.pref.removePreferenceChangeListener(this);577 for (JosmAction action : josmActions) {578 action.destroy();579 }580 Container parent = pluginHook.getParent();581 if (parent != null) {582 parent.remove(pluginHook);583 }584 }585 586 @Override587 186 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) { 588 if (!isVisible())589 return;590 187 if (tagTable == null) 591 188 return; // selection changed may be received in base class constructor before init … … 613 210 tagData.setRowCount(0); 614 211 615 final boolean displayDiscardableKeys = Main.pref.getBoolean("display.discardable-keys", false);616 final Map<String, Integer> keyCount = new HashMap<>();617 212 final Map<String, String> tags = new HashMap<>(); 618 213 valueCount.clear(); 619 Set<TaggingPresetType> types = EnumSet.noneOf(TaggingPresetType.class);620 for (OsmPrimitive osm : newSel) {621 types.add(TaggingPresetType.forPrimitive(osm));622 for (String key : osm.keySet()) {623 if (displayDiscardableKeys || !OsmPrimitive.getDiscardableKeys().contains(key)) {624 String value = osm.get(key);625 keyCount.put(key, keyCount.containsKey(key) ? keyCount.get(key) + 1 : 1);626 if (valueCount.containsKey(key)) {627 Map<String, Integer> v = valueCount.get(key);628 v.put(value, v.containsKey(value) ? v.get(value) + 1 : 1);629 } else {630 Map<String, Integer> v = new TreeMap<>();631 v.put(value, 1);632 valueCount.put(key, v);633 }634 }635 }636 }637 214 for (Entry<String, Map<String, Integer>> e : valueCount.entrySet()) { 638 215 int count = 0; … … 683 260 } 684 261 685 presets.updatePresets(types, tags, presetHandler);686 687 262 membershipTable.getTableHeader().setVisible(membershipData.getRowCount() > 0); 688 263 membershipTable.setVisible(membershipData.getRowCount() > 0); … … 691 266 boolean hasTags = hasSelection && tagData.getRowCount() > 0; 692 267 boolean hasMemberships = hasSelection && membershipData.getRowCount() > 0; 693 694 //temp commenting out to fix enable button bug 695 268 696 269 addAction.setEnabled(hasSelection); 697 270 //editAction.setEnabled(hasTags || hasMemberships); 698 271 editAction.setEnabled(true); 699 deleteAction.setEnabled(hasTags || hasMemberships);700 272 tagTable.setVisible(hasTags); 701 273 tagTable.getTableHeader().setVisible(hasTags); 702 274 selectSth.setVisible(!hasSelection); 703 pluginHook.setVisible(hasSelection); 704 705 //end of commenting out 706 707 //temp code 708 /* 709 addAction.setEnabled(true); 710 editAction.setEnabled(true); 711 deleteAction.setEnabled(true); 712 713 714 tagTable.setVisible(true); 715 tagTable.getTableHeader().setVisible(true); 716 selectSth.setVisible(false); 717 pluginHook.setVisible(true); 718 */ 719 //end of temp code 275 pluginHook.setVisible(hasSelection); 720 276 721 277 int selectedIndex; … … 729 285 membershipTable.changeSelection(0, 0, false, false); 730 286 } 731 732 if(tagData.getRowCount() != 0 || membershipData.getRowCount() != 0) {733 setTitle(tr("Tags: {0} / Memberships: {1}",734 tagData.getRowCount(), membershipData.getRowCount()));735 } else {736 setTitle(tr("Tags / Memberships"));737 }738 }739 740 /* ---------------------------------------------------------------------------------- */741 /* EditLayerChangeListener */742 /* ---------------------------------------------------------------------------------- */743 @Override744 public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) {745 if (newLayer == null) editHelper.saveTagsIfNeeded();746 // it is time to save history of tags747 GuiHelper.runInEDT(new Runnable() {748 @Override public void run() {749 updateSelection();750 }751 });752 287 } 753 288 … … 761 296 // <editor-fold defaultstate="collapsed" desc="Methods that are called by plugins to extend fuctionality "> 762 297 763 /**764 * Replies the tag popup menu handler.765 * @return The tag popup menu handler766 */767 public PopupMenuHandler getPropertyPopupMenuHandler() {768 return tagMenuHandler;769 }770 298 771 299 /** … … 784 312 785 313 /** 786 * Replies the membership popup menu handler.787 * @return The membership popup menu handler788 */789 public PopupMenuHandler getMembershipPopupMenuHandler() {790 return membershipMenuHandler;791 }792 793 /**794 314 * Returns the selected relation membership. 795 315 * @return The current selected relation membership … … 824 344 } else { 825 345 editHelper.addTag(); 826 btnAdd.requestFocusInWindow();346 //btnAdd.requestFocusInWindow(); 827 347 } 828 348 } else if (e.getSource() == membershipTable) { … … 833 353 } else { 834 354 editHelper.addTag(); 835 btnAdd.requestFocusInWindow();355 //btnAdd.requestFocusInWindow(); 836 356 } 837 357 } … … 913 433 public Class<?> getColumnClass(int columnIndex) { 914 434 return String.class; 915 }916 }917 918 /**919 * Action handling delete button press in properties dialog.920 */921 class DeleteAction extends JosmAction implements ListSelectionListener {922 923 private static final String DELETE_FROM_RELATION_PREF = "delete_from_relation";924 925 DeleteAction() {926 super(tr("Delete"), /* ICON() */ "dialogs/delete", tr("Delete the selected key in all objects"),927 Shortcut.registerShortcut("properties:delete", tr("Delete Tags"), KeyEvent.VK_D,928 Shortcut.ALT_CTRL_SHIFT), false);929 updateEnabledState();930 }931 932 protected void deleteTags(int[] rows){933 // convert list of rows to HashMap (and find gap for nextKey)934 Map<String, String> tags = new HashMap<>(rows.length);935 int nextKeyIndex = rows[0];936 for (int row : rows) {937 String key = tagData.getValueAt(row, 0).toString();938 if (row == nextKeyIndex + 1) {939 nextKeyIndex = row; // no gap yet940 }941 tags.put(key, null);942 }943 944 // find key to select after deleting other tags945 String nextKey = null;946 int rowCount = tagData.getRowCount();947 if (rowCount > rows.length) {948 if (nextKeyIndex == rows[rows.length-1]) {949 // no gap found, pick next or previous key in list950 nextKeyIndex = (nextKeyIndex + 1 < rowCount ? nextKeyIndex + 1 : rows[0] - 1);951 } else {952 // gap found953 nextKeyIndex++;954 }955 nextKey = (String)tagData.getValueAt(nextKeyIndex, 0);956 }957 958 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();959 Main.main.undoRedo.add(new ChangePropertyCommand(sel, tags));960 961 membershipTable.clearSelection();962 if (nextKey != null) {963 tagTable.changeSelection(findRow(tagData, nextKey), 0, false, false);964 }965 }966 967 protected void deleteFromRelation(int row) {968 Relation cur = (Relation)membershipData.getValueAt(row, 0);969 970 Relation nextRelation = null;971 int rowCount = membershipTable.getRowCount();972 if (rowCount > 1) {973 nextRelation = (Relation) membershipData.getValueAt(row + 1 < rowCount ? row + 1 : row - 1, 0);974 }975 976 ExtendedDialog ed = new ExtendedDialog(Main.parent,977 tr("Change relation"),978 new String[] {tr("Delete from relation"), tr("Cancel")});979 ed.setButtonIcons(new String[] {"dialogs/delete", "cancel"});980 ed.setContent(tr("Really delete selection from relation {0}?", cur.getDisplayName(DefaultNameFormatter.getInstance())));981 ed.toggleEnable(DELETE_FROM_RELATION_PREF);982 ed.showDialog();983 984 if(ed.getValue() != 1)985 return;986 987 Relation rel = new Relation(cur);988 for (OsmPrimitive primitive: Main.main.getInProgressSelection()) {989 rel.removeMembersFor(primitive);990 }991 Main.main.undoRedo.add(new ChangeCommand(cur, rel));992 993 tagTable.clearSelection();994 if (nextRelation != null) {995 membershipTable.changeSelection(findRow(membershipData, nextRelation), 0, false, false);996 }997 }998 999 @Override1000 public void actionPerformed(ActionEvent e) {1001 if (tagTable.getSelectedRowCount() > 0) {1002 int[] rows = tagTable.getSelectedRows();1003 deleteTags(rows);1004 } else if (membershipTable.getSelectedRowCount() > 0) {1005 ConditionalOptionPaneUtil.startBulkOperation(DELETE_FROM_RELATION_PREF);1006 int[] rows = membershipTable.getSelectedRows();1007 // delete from last relation to conserve row numbers in the table1008 for (int i=rows.length-1; i>=0; i--) {1009 deleteFromRelation(rows[i]);1010 }1011 ConditionalOptionPaneUtil.endBulkOperation(DELETE_FROM_RELATION_PREF);1012 }1013 }1014 1015 @Override1016 protected final void updateEnabledState() {1017 setEnabled(1018 (tagTable != null && tagTable.getSelectedRowCount() >= 1)1019 || (membershipTable != null && membershipTable.getSelectedRowCount() > 0)1020 );1021 }1022 1023 @Override1024 public void valueChanged(ListSelectionEvent e) {1025 updateEnabledState();1026 435 } 1027 436 } … … 1088 497 } 1089 498 } 1090 1091 class HelpAction extends AbstractAction {1092 HelpAction() {1093 putValue(NAME, tr("Go to OSM wiki for tag help (F1)"));1094 putValue(SHORT_DESCRIPTION, tr("Launch browser with wiki help for selected object"));1095 putValue(SMALL_ICON, ImageProvider.get("dialogs", "search"));1096 }1097 1098 @Override1099 public void actionPerformed(ActionEvent e) {1100 try {1101 String base = Main.pref.get("url.openstreetmap-wiki", "http://wiki.openstreetmap.org/wiki/");1102 String lang = LanguageInfo.getWikiLanguagePrefix();1103 final List<URI> uris = new ArrayList<>();1104 int row;1105 if (tagTable.getSelectedRowCount() == 1) {1106 row = tagTable.getSelectedRow();1107 String key = Utils.encodeUrl(tagData.getValueAt(row, 0).toString());1108 @SuppressWarnings("unchecked")1109 Map<String, Integer> m = (Map<String, Integer>) tagData.getValueAt(row, 1);1110 String val = Utils.encodeUrl(m.entrySet().iterator().next().getKey());1111 1112 uris.add(new URI(String.format("%s%sTag:%s=%s", base, lang, key, val)));1113 uris.add(new URI(String.format("%sTag:%s=%s", base, key, val)));1114 uris.add(new URI(String.format("%s%sKey:%s", base, lang, key)));1115 uris.add(new URI(String.format("%sKey:%s", base, key)));1116 uris.add(new URI(String.format("%s%sMap_Features", base, lang)));1117 uris.add(new URI(String.format("%sMap_Features", base)));1118 } else if (membershipTable.getSelectedRowCount() == 1) {1119 row = membershipTable.getSelectedRow();1120 String type = ((Relation)membershipData.getValueAt(row, 0)).get("type");1121 if (type != null) {1122 type = Utils.encodeUrl(type);1123 }1124 1125 if (type != null && !type.isEmpty()) {1126 uris.add(new URI(String.format("%s%sRelation:%s", base, lang, type)));1127 uris.add(new URI(String.format("%sRelation:%s", base, type)));1128 }1129 1130 uris.add(new URI(String.format("%s%sRelations", base, lang)));1131 uris.add(new URI(String.format("%sRelations", base)));1132 } else {1133 // give the generic help page, if more than one element is selected1134 uris.add(new URI(String.format("%s%sMap_Features", base, lang)));1135 uris.add(new URI(String.format("%sMap_Features", base)));1136 }1137 1138 Main.worker.execute(new Runnable(){1139 @Override public void run() {1140 try {1141 // find a page that actually exists in the wiki1142 HttpURLConnection conn;1143 for (URI u : uris) {1144 conn = Utils.openHttpConnection(u.toURL());1145 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);1146 1147 if (conn.getResponseCode() != 200) {1148 Main.info("{0} does not exist", u);1149 conn.disconnect();1150 } else {1151 int osize = conn.getContentLength();1152 if (osize > -1) {1153 conn.disconnect();1154 1155 conn = Utils.openHttpConnection(new URI(u.toString()1156 .replace("=", "%3D") /* do not URLencode whole string! */1157 .replaceFirst("/wiki/", "/w/index.php?redirect=no&title=")1158 ).toURL());1159 conn.setConnectTimeout(Main.pref.getInteger("socket.timeout.connect",15)*1000);1160 }1161 1162 /* redirect pages have different content length, but retrieving a "nonredirect"1163 * page using index.php and the direct-link method gives slightly different1164 * content lengths, so we have to be fuzzy.. (this is UGLY, recode if u know better)1165 */1166 if (conn.getContentLength() != -1 && osize > -1 && Math.abs(conn.getContentLength() - osize) > 200) {1167 Main.info("{0} is a mediawiki redirect", u);1168 conn.disconnect();1169 } else {1170 Main.info("browsing to {0}", u);1171 conn.disconnect();1172 1173 OpenBrowser.displayUrl(u.toString());1174 break;1175 }1176 }1177 }1178 } catch (Exception e) {1179 Main.error(e);1180 }1181 }1182 });1183 } catch (URISyntaxException e1) {1184 Main.error(e1);1185 }1186 }1187 }1188 1189 class PasteValueAction extends AbstractAction {1190 PasteValueAction() {1191 putValue(NAME, tr("Paste Value"));1192 putValue(SHORT_DESCRIPTION, tr("Paste the value of the selected tag from clipboard"));1193 }1194 1195 @Override1196 public void actionPerformed(ActionEvent ae) {1197 if (tagTable.getSelectedRowCount() != 1)1198 return;1199 String key = tagData.getValueAt(tagTable.getSelectedRow(), 0).toString();1200 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();1201 String clipboard = Utils.getClipboardContent();1202 if (sel.isEmpty() || clipboard == null)1203 return;1204 Main.main.undoRedo.add(new ChangePropertyCommand(sel, key, Utils.strip(clipboard)));1205 }1206 }1207 1208 abstract class AbstractCopyAction extends AbstractAction {1209 1210 protected abstract Collection<String> getString(OsmPrimitive p, String key);1211 1212 @Override1213 public void actionPerformed(ActionEvent ae) {1214 int[] rows = tagTable.getSelectedRows();1215 Set<String> values = new TreeSet<>();1216 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();1217 if (rows.length == 0 || sel.isEmpty()) return;1218 1219 for (int row: rows) {1220 String key = tagData.getValueAt(row, 0).toString();1221 if (sel.isEmpty())1222 return;1223 for (OsmPrimitive p : sel) {1224 Collection<String> s = getString(p,key);1225 if (s != null) {1226 values.addAll(s);1227 }1228 }1229 }1230 if (!values.isEmpty()) {1231 Utils.copyToClipboard(Utils.join("\n", values));1232 }1233 }1234 }1235 1236 class CopyValueAction extends AbstractCopyAction {1237 1238 /**1239 * Constructs a new {@code CopyValueAction}.1240 */1241 CopyValueAction() {1242 putValue(NAME, tr("Copy Value"));1243 putValue(SHORT_DESCRIPTION, tr("Copy the value of the selected tag to clipboard"));1244 }1245 1246 @Override1247 protected Collection<String> getString(OsmPrimitive p, String key) {1248 String v = p.get(key);1249 return v == null ? null : Collections.singleton(v);1250 }1251 }1252 1253 class CopyKeyValueAction extends AbstractCopyAction {1254 1255 CopyKeyValueAction() {1256 putValue(NAME, tr("Copy selected Key(s)/Value(s)"));1257 putValue(SHORT_DESCRIPTION, tr("Copy the key and value of the selected tag(s) to clipboard"));1258 }1259 1260 @Override1261 protected Collection<String> getString(OsmPrimitive p, String key) {1262 String v = p.get(key);1263 return v == null ? null : Collections.singleton(new Tag(key, v).toString());1264 }1265 }1266 1267 class CopyAllKeyValueAction extends AbstractCopyAction {1268 1269 CopyAllKeyValueAction() {1270 putValue(NAME, tr("Copy all Keys/Values"));1271 putValue(SHORT_DESCRIPTION, tr("Copy the key and value of all the tags to clipboard"));1272 }1273 1274 @Override1275 protected Collection<String> getString(OsmPrimitive p, String key) {1276 List<String> r = new LinkedList<>();1277 for (Entry<String, String> kv : p.getKeys().entrySet()) {1278 r.add(new Tag(kv.getKey(), kv.getValue()).toString());1279 }1280 return r;1281 }1282 }1283 1284 class SearchAction extends AbstractAction {1285 private final boolean sameType;1286 1287 SearchAction(boolean sameType) {1288 this.sameType = sameType;1289 if (sameType) {1290 putValue(NAME, tr("Search Key/Value/Type"));1291 putValue(SHORT_DESCRIPTION, tr("Search with the key and value of the selected tag, restrict to type (i.e., node/way/relation)"));1292 } else {1293 putValue(NAME, tr("Search Key/Value"));1294 putValue(SHORT_DESCRIPTION, tr("Search with the key and value of the selected tag"));1295 }1296 }1297 1298 @Override1299 public void actionPerformed(ActionEvent e) {1300 if (tagTable.getSelectedRowCount() != 1)1301 return;1302 String key = tagData.getValueAt(tagTable.getSelectedRow(), 0).toString();1303 Collection<OsmPrimitive> sel = Main.main.getInProgressSelection();1304 if (sel.isEmpty())1305 return;1306 String sep = "";1307 StringBuilder s = new StringBuilder();1308 for (OsmPrimitive p : sel) {1309 String val = p.get(key);1310 if (val == null) {1311 continue;1312 }1313 String t = "";1314 if (!sameType) {1315 t = "";1316 } else if (p instanceof Node) {1317 t = "type:node ";1318 } else if (p instanceof Way) {1319 t = "type:way ";1320 } else if (p instanceof Relation) {1321 t = "type:relation ";1322 }1323 s.append(sep).append('(').append(t).append('"').append(1324 org.openstreetmap.josm.actions.search.SearchAction.escapeStringForSearch(key)).append("\"=\"").append(1325 org.openstreetmap.josm.actions.search.SearchAction.escapeStringForSearch(val)).append("\")");1326 sep = " OR ";1327 }1328 1329 final SearchSetting ss = new SearchSetting();1330 ss.text = s.toString();1331 ss.mode = SearchMode.replace;1332 ss.caseSensitive = true;1333 org.openstreetmap.josm.actions.search.SearchAction.searchWithoutHistory(ss);1334 }1335 }1336 1337 @Override1338 public void preferenceChanged(PreferenceChangeEvent e) {1339 super.preferenceChanged(e);1340 if ("display.discardable-keys".equals(e.getKey()) && Main.main.getCurrentDataSet() != null) {1341 // Re-load data when display preference change1342 updateSelection();1343 }1344 }1345 499 }
Note:
See TracChangeset
for help on using the changeset viewer.