1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548
|
// License: GPL. For details, see LICENSE file.
package org.openstreetmap.josm.gui.tagging;
import static org.openstreetmap.josm.tools.I18n.tr;
import static org.openstreetmap.josm.tools.I18n.trc;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JToggleButton;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import org.openstreetmap.josm.Main;
import org.openstreetmap.josm.actions.search.SearchCompiler;
import org.openstreetmap.josm.data.osm.OsmPrimitive;
import org.openstreetmap.josm.data.osm.OsmUtils;
import org.openstreetmap.josm.data.osm.Tag;
import org.openstreetmap.josm.data.preferences.BooleanProperty;
import org.openstreetmap.josm.gui.mappaint.MapPaintStyles;
import org.openstreetmap.josm.gui.tagging.ac.AutoCompletingTextField;
import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionItemPriority;
import org.openstreetmap.josm.gui.tagging.ac.AutoCompletionList;
import org.openstreetmap.josm.gui.widgets.JosmComboBox;
import org.openstreetmap.josm.gui.widgets.JosmTextField;
import org.openstreetmap.josm.gui.widgets.QuadStateCheckBox;
import org.openstreetmap.josm.gui.widgets.UrlLabel;
import org.openstreetmap.josm.tools.GBC;
import org.openstreetmap.josm.tools.ImageProvider;
import org.openstreetmap.josm.tools.Predicate;
import org.openstreetmap.josm.tools.Utils;
import org.xml.sax.SAXException;
/**
* Class that contains all subtypes of TaggingPresetItem, static supplementary data, types and methods
* @since 6068
*/
public final class TaggingPresetItems {
private TaggingPresetItems() {
}
private static int auto_increment_selected = 0;
/** Translatation of "<different>". Use in combo boxes to display en entry matching several different values. */
public static final String DIFFERENT = tr("<different>");
private static final BooleanProperty PROP_FILL_DEFAULT = new BooleanProperty("taggingpreset.fill-default-for-tagged-primitives", false);
// cache the parsing of types using a LRU cache (http://java-planet.blogspot.com/2005/08/how-to-set-up-simple-lru-cache-using.html)
private static final Map<String,EnumSet<TaggingPresetType>> TYPE_CACHE = new LinkedHashMap<>(16, 1.1f, true);
/**
* Last value of each key used in presets, used for prefilling corresponding fields
*/
private static final Map<String,String> LAST_VALUES = new HashMap<>();
public static class PresetListEntry {
public String value;
/** The context used for translating {@link #value} */
public String value_context;
public String display_value;
public String short_description;
/** The location of icon file to display */
public String icon;
/** The size of displayed icon. If not set, default is size from icon file */
public String icon_size;
/** The localized version of {@link #display_value}. */
public String locale_display_value;
/** The localized version of {@link #short_description}. */
public String locale_short_description;
private final File zipIcons = TaggingPresetReader.getZipIcons();
// Cached size (currently only for Combo) to speed up preset dialog initialization
private int prefferedWidth = -1;
private int prefferedHeight = -1;
public String getListDisplay() {
if (value.equals(DIFFERENT))
return "<b>"+DIFFERENT.replaceAll("<", "<").replaceAll(">", ">")+"</b>";
if (value.isEmpty())
return " ";
final StringBuilder res = new StringBuilder("<b>");
res.append(getDisplayValue(true));
res.append("</b>");
if (getShortDescription(true) != null) {
// wrap in table to restrict the text width
res.append("<div style=\"width:300px; padding:0 0 5px 5px\">");
res.append(getShortDescription(true));
res.append("</div>");
}
return res.toString();
}
/**
* Returns the entry icon, if any.
* @return the entry icon, or {@code null}
*/
public ImageIcon getIcon() {
return icon == null ? null : loadImageIcon(icon, zipIcons, parseInteger(icon_size));
}
/**
* Construxts a new {@code PresetListEntry}, uninitialized.
*/
public PresetListEntry() {
}
public PresetListEntry(String value) {
this.value = value;
}
public String getDisplayValue(boolean translated) {
return translated
? Utils.firstNonNull(locale_display_value, tr(display_value), trc(value_context, value))
: Utils.firstNonNull(display_value, value);
}
public String getShortDescription(boolean translated) {
return translated
? Utils.firstNonNull(locale_short_description, tr(short_description))
: short_description;
}
// toString is mainly used to initialize the Editor
@Override
public String toString() {
if (value.equals(DIFFERENT))
return DIFFERENT;
return getDisplayValue(true).replaceAll("<.*>", ""); // remove additional markup, e.g. <br>
}
}
public static class Role {
public EnumSet<TaggingPresetType> types;
public String key;
/** The text to display */
public String text;
/** The context used for translating {@link #text} */
public String text_context;
/** The localized version of {@link #text}. */
public String locale_text;
public SearchCompiler.Match memberExpression;
public boolean required = false;
private long count = 0;
public void setType(String types) throws SAXException {
this.types = getType(types);
}
public void setRequisite(String str) throws SAXException {
if("required".equals(str)) {
required = true;
} else if(!"optional".equals(str))
throw new SAXException(tr("Unknown requisite: {0}", str));
}
public void setMember_expression(String member_expression) throws SAXException {
try {
this.memberExpression = SearchCompiler.compile(member_expression, true, true);
} catch (SearchCompiler.ParseError ex) {
throw new SAXException(tr("Illegal member expression: {0}", ex.getMessage()), ex);
}
}
public void setCount(String count) {
this.count = Long.parseLong(count);
}
/**
* Return either argument, the highest possible value or the lowest allowed value
*/
public long getValidCount(long c) {
if (count > 0 && !required)
return c != 0 ? count : 0;
else if (count > 0)
return count;
else if (!required)
return c != 0 ? c : 0;
else
return c != 0 ? c : 1;
}
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel) {
String cstring;
if (count > 0 && !required) {
cstring = "0,"+count;
} else if(count > 0) {
cstring = String.valueOf(count);
} else if(!required) {
cstring = "0-...";
} else {
cstring = "1-...";
}
if (locale_text == null) {
locale_text = getLocaleText(text, text_context, null);
}
p.add(new JLabel(locale_text+":"), GBC.std().insets(0,0,10,0));
p.add(new JLabel(key), GBC.std().insets(0,0,10,0));
p.add(new JLabel(cstring), types == null ? GBC.eol() : GBC.std().insets(0,0,10,0));
if (types != null) {
JPanel pp = new JPanel();
for(TaggingPresetType t : types) {
pp.add(new JLabel(ImageProvider.get(t.getIconName())));
}
p.add(pp, GBC.eol());
}
return true;
}
}
/**
* Enum denoting how a match (see {@link TaggingPresetItem#matches}) is performed.
*/
public static enum MatchType {
/** Neutral, i.e., do not consider this item for matching. */
NONE("none"),
/** Positive if key matches, neutral otherwise. */
KEY("key"),
/** Positive if key matches, negative otherwise. */
KEY_REQUIRED("key!"),
/** Positive if key and value matches, neutral otherwise. */
KEY_VALUE("keyvalue"),
/** Positive if key and value matches, negative otherwise. */
KEY_VALUE_REQUIRED("keyvalue!");
private final String value;
private MatchType(String value) {
this.value = value;
}
/**
* Replies the associated textual value.
* @return the associated textual value
*/
public String getValue() {
return value;
}
/**
* Determines the {@code MatchType} for the given textual value.
* @param type the textual value
* @return the {@code MatchType} for the given textual value
*/
public static MatchType ofString(String type) {
for (MatchType i : EnumSet.allOf(MatchType.class)) {
if (i.getValue().equals(type))
return i;
}
throw new IllegalArgumentException(type + " is not allowed");
}
}
public static class Usage {
TreeSet<String> values;
boolean hadKeys = false;
boolean hadEmpty = false;
public boolean hasUniqueValue() {
return values.size() == 1 && !hadEmpty;
}
public boolean unused() {
return values.isEmpty();
}
public String getFirst() {
return values.first();
}
public boolean hadKeys() {
return hadKeys;
}
}
/**
* A tagging preset item displaying a localizable text.
* @since 6190
*/
public abstract static class TaggingPresetTextItem extends TaggingPresetItem {
/** The text to display */
public String text;
/** The context used for translating {@link #text} */
public String text_context;
/** The localized version of {@link #text} */
public String locale_text;
protected final void initializeLocaleText(String defaultText) {
if (locale_text == null) {
locale_text = getLocaleText(text, text_context, defaultText);
}
}
@Override
void addCommands(List<Tag> changedTags) {
}
protected String fieldsToString() {
return (text != null ? "text=" + text + ", " : "")
+ (text_context != null ? "text_context=" + text_context + ", " : "")
+ (locale_text != null ? "locale_text=" + locale_text : "");
}
@Override
public String toString() {
return getClass().getSimpleName() + " [" + fieldsToString() + "]";
}
}
/**
* Label type.
*/
public static class Label extends TaggingPresetTextItem {
/** The location of icon file to display (optional) */
public String icon;
/** The size of displayed icon. If not set, default is 16px */
public String icon_size;
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
initializeLocaleText(null);
addLabel(p, getIcon(), locale_text);
return true;
}
/**
* Adds a new {@code JLabel} to the given panel.
* @param p The panel
* @param icon the icon (optional, can be null)
* @param label The text label
*/
public static void addLabel(JPanel p, Icon icon, String label) {
p.add(new JLabel(label, icon, JLabel.LEADING), GBC.eol().fill(GBC.HORIZONTAL));
}
/**
* Returns the label icon, if any.
* @return the label icon, or {@code null}
*/
public ImageIcon getIcon() {
Integer size = parseInteger(icon_size);
return icon == null ? null : loadImageIcon(icon, TaggingPresetReader.getZipIcons(), size != null ? size : 16);
}
}
/**
* Hyperlink type.
*/
public static class Link extends TaggingPresetTextItem {
/** The link to display. */
public String href;
/** The localized version of {@link #href}. */
public String locale_href;
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
initializeLocaleText(tr("More information about this feature"));
String url = locale_href;
if (url == null) {
url = href;
}
if (url != null) {
p.add(new UrlLabel(url, locale_text, 2), GBC.eol().insets(0, 10, 0, 0).fill(GBC.HORIZONTAL));
}
return false;
}
@Override
protected String fieldsToString() {
return super.fieldsToString()
+ (href != null ? "href=" + href + ", " : "")
+ (locale_href != null ? "locale_href=" + locale_href + ", " : "");
}
}
public static class PresetLink extends TaggingPresetItem {
public String preset_name = "";
@Override
boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
final String presetName = preset_name;
final TaggingPreset t = Utils.filter(TaggingPresets.getTaggingPresets(), new Predicate<TaggingPreset>() {
@Override
public boolean evaluate(TaggingPreset object) {
return presetName.equals(object.name);
}
}).iterator().next();
if (t == null) return false;
JLabel lbl = new PresetLabel(t);
lbl.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
t.actionPerformed(null);
}
});
p.add(lbl, GBC.eol().fill(GBC.HORIZONTAL));
return false;
}
@Override
void addCommands(List<Tag> changedTags) {
}
}
public static class Roles extends TaggingPresetItem {
public final List<Role> roles = new LinkedList<>();
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
p.add(new JLabel(" "), GBC.eol()); // space
if (!roles.isEmpty()) {
JPanel proles = new JPanel(new GridBagLayout());
proles.add(new JLabel(tr("Available roles")), GBC.std().insets(0, 0, 10, 0));
proles.add(new JLabel(tr("role")), GBC.std().insets(0, 0, 10, 0));
proles.add(new JLabel(tr("count")), GBC.std().insets(0, 0, 10, 0));
proles.add(new JLabel(tr("elements")), GBC.eol());
for (Role i : roles) {
i.addToPanel(proles, sel);
}
p.add(proles, GBC.eol());
}
return false;
}
@Override
public void addCommands(List<Tag> changedTags) {
}
}
public static class Optional extends TaggingPresetTextItem {
// TODO: Draw a box around optional stuff
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
initializeLocaleText(tr("Optional Attributes:"));
p.add(new JLabel(" "), GBC.eol()); // space
p.add(new JLabel(locale_text), GBC.eol());
p.add(new JLabel(" "), GBC.eol()); // space
return false;
}
}
/**
* Horizontal separator type.
*/
public static class Space extends TaggingPresetItem {
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
p.add(new JLabel(" "), GBC.eol()); // space
return false;
}
@Override
public void addCommands(List<Tag> changedTags) {
}
@Override
public String toString() {
return "Space";
}
}
/**
* Class used to represent a {@link JSeparator} inside tagging preset window.
* @since 6198
*/
public static class ItemSeparator extends TaggingPresetItem {
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
p.add(new JSeparator(), GBC.eol().fill(GBC.HORIZONTAL).insets(0, 5, 0, 5));
return false;
}
@Override
public void addCommands(List<Tag> changedTags) {
}
@Override
public String toString() {
return "ItemSeparator";
}
}
/**
* Preset item associated to an OSM key.
*/
public abstract static class KeyedItem extends TaggingPresetItem {
public String key;
/** The text to display */
public String text;
/** The context used for translating {@link #text} */
public String text_context;
public String match = getDefaultMatch().getValue();
public abstract MatchType getDefaultMatch();
public abstract Collection<String> getValues();
@Override
Boolean matches(Map<String, String> tags) {
switch (MatchType.ofString(match)) {
case NONE:
return null;
case KEY:
return tags.containsKey(key) ? true : null;
case KEY_REQUIRED:
return tags.containsKey(key);
case KEY_VALUE:
return tags.containsKey(key) && getValues().contains(tags.get(key)) ? true : null;
case KEY_VALUE_REQUIRED:
return tags.containsKey(key) && getValues().contains(tags.get(key));
default:
throw new IllegalStateException();
}
}
@Override
public String toString() {
return "KeyedItem [key=" + key + ", text=" + text
+ ", text_context=" + text_context + ", match=" + match
+ "]";
}
}
/**
* Invisible type allowing to hardcode an OSM key/value from the preset definition.
*/
public static class Key extends KeyedItem {
/** The hardcoded value for key */
public String value;
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
return false;
}
@Override
public void addCommands(List<Tag> changedTags) {
changedTags.add(new Tag(key, value));
}
@Override
public MatchType getDefaultMatch() {
return MatchType.KEY_VALUE_REQUIRED;
}
@Override
public Collection<String> getValues() {
return Collections.singleton(value);
}
@Override
public String toString() {
return "Key [key=" + key + ", value=" + value + ", text=" + text
+ ", text_context=" + text_context + ", match=" + match
+ "]";
}
}
/**
* Text field type.
*/
public static class Text extends KeyedItem {
/** The localized version of {@link #text}. */
public String locale_text;
public String default_;
public String originalValue;
public String use_last_as_default = "false";
public String auto_increment;
public String length;
public String alternative_autocomplete_keys;
private JComponent value;
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
// find out if our key is already used in the selection.
Usage usage = determineTextUsage(sel, key);
AutoCompletingTextField textField = new AutoCompletingTextField();
if (alternative_autocomplete_keys != null) {
initAutoCompletionField(textField, (key + "," + alternative_autocomplete_keys).split(","));
} else {
initAutoCompletionField(textField, key);
}
if (Main.pref.getBoolean("taggingpreset.display-keys-as-hint", true)) {
textField.setHint(key);
}
if (length != null && !length.isEmpty()) {
textField.setMaxChars(Integer.valueOf(length));
}
if (usage.unused()){
if (auto_increment_selected != 0 && auto_increment != null) {
try {
textField.setText(Integer.toString(Integer.parseInt(LAST_VALUES.get(key)) + auto_increment_selected));
} catch (NumberFormatException ex) {
// Ignore - cannot auto-increment if last was non-numeric
}
}
else if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
// selected osm primitives are untagged or filling default values feature is enabled
if (!"false".equals(use_last_as_default) && LAST_VALUES.containsKey(key) && !presetInitiallyMatches) {
textField.setText(LAST_VALUES.get(key));
} else {
textField.setText(default_);
}
} else {
// selected osm primitives are tagged and filling default values feature is disabled
textField.setText("");
}
value = textField;
originalValue = null;
} else if (usage.hasUniqueValue()) {
// all objects use the same value
textField.setText(usage.getFirst());
value = textField;
originalValue = usage.getFirst();
} else {
// the objects have different values
JosmComboBox<String> comboBox = new JosmComboBox<>(usage.values.toArray(new String[0]));
comboBox.setEditable(true);
comboBox.setEditor(textField);
comboBox.getEditor().setItem(DIFFERENT);
value=comboBox;
originalValue = DIFFERENT;
}
if (locale_text == null) {
locale_text = getLocaleText(text, text_context, null);
}
// if there's an auto_increment setting, then wrap the text field
// into a panel, appending a number of buttons.
// auto_increment has a format like -2,-1,1,2
// the text box being the first component in the panel is relied
// on in a rather ugly fashion further down.
if (auto_increment != null) {
ButtonGroup bg = new ButtonGroup();
JPanel pnl = new JPanel(new GridBagLayout());
pnl.add(value, GBC.std().fill(GBC.HORIZONTAL));
// first, one button for each auto_increment value
for (final String ai : auto_increment.split(",")) {
JToggleButton aibutton = new JToggleButton(ai);
aibutton.setToolTipText(tr("Select auto-increment of {0} for this field", ai));
aibutton.setMargin(new java.awt.Insets(0,0,0,0));
aibutton.setFocusable(false);
bg.add(aibutton);
try {
// TODO there must be a better way to parse a number like "+3" than this.
final int buttonvalue = (NumberFormat.getIntegerInstance().parse(ai.replace("+", ""))).intValue();
if (auto_increment_selected == buttonvalue) aibutton.setSelected(true);
aibutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
auto_increment_selected = buttonvalue;
}
});
pnl.add(aibutton, GBC.std());
} catch (ParseException x) {
Main.error("Cannot parse auto-increment value of '" + ai + "' into an integer");
}
}
// an invisible toggle button for "release" of the button group
final JToggleButton clearbutton = new JToggleButton("X");
clearbutton.setVisible(false);
clearbutton.setFocusable(false);
bg.add(clearbutton);
// and its visible counterpart. - this mechanism allows us to
// have *no* button selected after the X is clicked, instead
// of the X remaining selected
JButton releasebutton = new JButton("X");
releasebutton.setToolTipText(tr("Cancel auto-increment for this field"));
releasebutton.setMargin(new java.awt.Insets(0,0,0,0));
releasebutton.setFocusable(false);
releasebutton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
auto_increment_selected = 0;
clearbutton.setSelected(true);
}
});
pnl.add(releasebutton, GBC.eol());
value = pnl;
}
p.add(new JLabel(locale_text+":"), GBC.std().insets(0,0,10,0));
p.add(value, GBC.eol().fill(GBC.HORIZONTAL));
return true;
}
private static String getValue(Component comp) {
if (comp instanceof JosmComboBox) {
return ((JosmComboBox<?>) comp).getEditor().getItem().toString();
} else if (comp instanceof JosmTextField) {
return ((JosmTextField) comp).getText();
} else if (comp instanceof JPanel) {
return getValue(((JPanel)comp).getComponent(0));
} else {
return null;
}
}
@Override
public void addCommands(List<Tag> changedTags) {
// return if unchanged
String v = getValue(value);
if (v == null) {
Main.error("No 'last value' support for component " + value);
return;
}
v = Tag.removeWhiteSpaces(v);
if (!"false".equals(use_last_as_default) || auto_increment != null) {
LAST_VALUES.put(key, v);
}
if (v.equals(originalValue) || (originalValue == null && v.length() == 0))
return;
changedTags.add(new Tag(key, v));
}
@Override
boolean requestFocusInWindow() {
return value.requestFocusInWindow();
}
@Override
public MatchType getDefaultMatch() {
return MatchType.NONE;
}
@Override
public Collection<String> getValues() {
if (default_ == null || default_.isEmpty())
return Collections.emptyList();
return Collections.singleton(default_);
}
}
/**
* A group of {@link Check}s.
* @since 6114
*/
public static class CheckGroup extends TaggingPresetItem {
/**
* Number of columns (positive integer)
*/
public String columns;
/**
* List of checkboxes
*/
public final List<Check> checks = new LinkedList<>();
@Override
boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
Integer cols = Integer.valueOf(columns);
int rows = (int) Math.ceil(checks.size()/cols.doubleValue());
JPanel panel = new JPanel(new GridLayout(rows, cols));
for (Check check : checks) {
check.addToPanel(panel, sel, presetInitiallyMatches);
}
p.add(panel, GBC.eol());
return false;
}
@Override
void addCommands(List<Tag> changedTags) {
for (Check check : checks) {
check.addCommands(changedTags);
}
}
@Override
public String toString() {
return "CheckGroup [columns=" + columns + "]";
}
}
/**
* Checkbox type.
*/
public static class Check extends KeyedItem {
/** The localized version of {@link #text}. */
public String locale_text;
/** the value to set when checked (default is "yes") */
public String value_on = OsmUtils.trueval;
/** the value to set when unchecked (default is "no") */
public String value_off = OsmUtils.falseval;
/** whether the off value is disabled in the dialog, i.e., only unset or yes are provided */
public boolean disable_off = false;
/** ticked on/off (default is "off") */
public boolean default_ = false; // only used for tagless objects
private QuadStateCheckBox check;
private QuadStateCheckBox.State initialState;
private boolean def;
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
// find out if our key is already used in the selection.
final Usage usage = determineBooleanUsage(sel, key);
final String oneValue = usage.values.isEmpty() ? null : usage.values.last();
def = default_;
if (locale_text == null) {
locale_text = getLocaleText(text, text_context, null);
}
if (usage.values.size() < 2 && (oneValue == null || value_on.equals(oneValue) || value_off.equals(oneValue))) {
if (def && !PROP_FILL_DEFAULT.get()) {
// default is set and filling default values feature is disabled - check if all primitives are untagged
for (OsmPrimitive s : sel)
if (s.hasKeys()) {
def = false;
}
}
// all selected objects share the same value which is either true or false or unset,
// we can display a standard check box.
initialState = value_on.equals(oneValue)
? QuadStateCheckBox.State.SELECTED
: value_off.equals(oneValue)
? QuadStateCheckBox.State.NOT_SELECTED
: def
? QuadStateCheckBox.State.SELECTED
: QuadStateCheckBox.State.UNSET;
} else {
def = false;
// the objects have different values, or one or more objects have something
// else than true/false. we display a quad-state check box
// in "partial" state.
initialState = QuadStateCheckBox.State.PARTIAL;
}
final List<QuadStateCheckBox.State> allowedStates = new ArrayList<>(4);
if (QuadStateCheckBox.State.PARTIAL.equals(initialState))
allowedStates.add(QuadStateCheckBox.State.PARTIAL);
allowedStates.add(QuadStateCheckBox.State.SELECTED);
if (!disable_off || value_off.equals(oneValue))
allowedStates.add(QuadStateCheckBox.State.NOT_SELECTED);
allowedStates.add(QuadStateCheckBox.State.UNSET);
check = new QuadStateCheckBox(locale_text, initialState,
allowedStates.toArray(new QuadStateCheckBox.State[allowedStates.size()]));
p.add(check, GBC.eol().fill(GBC.HORIZONTAL));
return true;
}
@Override
public void addCommands(List<Tag> changedTags) {
// if the user hasn't changed anything, don't create a command.
if (check.getState() == initialState && !def) return;
// otherwise change things according to the selected value.
changedTags.add(new Tag(key,
check.getState() == QuadStateCheckBox.State.SELECTED ? value_on :
check.getState() == QuadStateCheckBox.State.NOT_SELECTED ? value_off :
null));
}
@Override
boolean requestFocusInWindow() {return check.requestFocusInWindow();}
@Override
public MatchType getDefaultMatch() {
return MatchType.NONE;
}
@Override
public Collection<String> getValues() {
return disable_off ? Arrays.asList(value_on) : Arrays.asList(value_on, value_off);
}
@Override
public String toString() {
return "Check ["
+ (locale_text != null ? "locale_text=" + locale_text + ", " : "")
+ (value_on != null ? "value_on=" + value_on + ", " : "")
+ (value_off != null ? "value_off=" + value_off + ", " : "")
+ "default_=" + default_ + ", "
+ (check != null ? "check=" + check + ", " : "")
+ (initialState != null ? "initialState=" + initialState
+ ", " : "") + "def=" + def + "]";
}
}
/**
* Abstract superclass for combo box and multi-select list types.
*/
public abstract static class ComboMultiSelect extends KeyedItem {
/** The localized version of {@link #text}. */
public String locale_text;
public String values;
public String values_from;
/** The context used for translating {@link #values} */
public String values_context;
public String display_values;
/** The localized version of {@link #display_values}. */
public String locale_display_values;
public String short_descriptions;
/** The localized version of {@link #short_descriptions}. */
public String locale_short_descriptions;
public String default_;
public String delimiter = ";";
public String use_last_as_default = "false";
/** whether to use values for search via {@link TaggingPresetSelector} */
public String values_searchable = "false";
protected JComponent component;
protected final Map<String, PresetListEntry> lhm = new LinkedHashMap<>();
private boolean initialized = false;
protected Usage usage;
protected Object originalValue;
protected abstract Object getSelectedItem();
protected abstract void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches);
protected char getDelChar() {
return delimiter.isEmpty() ? ';' : delimiter.charAt(0);
}
@Override
public Collection<String> getValues() {
initListEntries();
return lhm.keySet();
}
public Collection<String> getDisplayValues() {
initListEntries();
return Utils.transform(lhm.values(), new Utils.Function<PresetListEntry, String>() {
@Override
public String apply(PresetListEntry x) {
return x.getDisplayValue(true);
}
});
}
@Override
public boolean addToPanel(JPanel p, Collection<OsmPrimitive> sel, boolean presetInitiallyMatches) {
initListEntries();
// find out if our key is already used in the selection.
usage = determineTextUsage(sel, key);
if (!usage.hasUniqueValue() && !usage.unused()) {
lhm.put(DIFFERENT, new PresetListEntry(DIFFERENT));
}
p.add(new JLabel(tr("{0}:", locale_text)), GBC.std().insets(0, 0, 10, 0));
addToPanelAnchor(p, default_, presetInitiallyMatches);
return true;
}
private void initListEntries() {
if (initialized) {
lhm.remove(DIFFERENT); // possibly added in #addToPanel
return;
} else if (lhm.isEmpty()) {
initListEntriesFromAttributes();
} else {
if (values != null) {
Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
+ "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
key, text, "values", "list_entry"));
}
if (display_values != null || locale_display_values != null) {
Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
+ "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
key, text, "display_values", "list_entry"));
}
if (short_descriptions != null || locale_short_descriptions != null) {
Main.warn(tr("Warning in tagging preset \"{0}-{1}\": "
+ "Ignoring ''{2}'' attribute as ''{3}'' elements are given.",
key, text, "short_descriptions", "list_entry"));
}
for (PresetListEntry e : lhm.values()) {
if (e.value_context == null) {
e.value_context = values_context;
}
}
}
if (locale_text == null) {
locale_text = getLocaleText(text, text_context, null);
}
initialized = true;
}
private String[] initListEntriesFromAttributes() {
char delChar = getDelChar();
String[] value_array = null;
if (values_from != null) {
String[] class_method = values_from.split("#");
if (class_method != null && class_method.length == 2) {
try {
Method method = Class.forName(class_method[0]).getMethod(class_method[1]);
// Check method is public static String[] methodName()
int mod = method.getModifiers();
if (Modifier.isPublic(mod) && Modifier.isStatic(mod)
&& method.getReturnType().equals(String[].class) && method.getParameterTypes().length == 0) {
value_array = (String[]) method.invoke(null);
} else {
Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' is not \"{2}\"", key, text,
"public static String[] methodName()"));
}
} catch (Exception e) {
Main.error(tr("Broken tagging preset \"{0}-{1}\" - Java method given in ''values_from'' threw {2} ({3})", key, text,
e.getClass().getName(), e.getMessage()));
}
}
}
if (value_array == null) {
value_array = splitEscaped(delChar, values);
}
final String displ = Utils.firstNonNull(locale_display_values, display_values);
String[] display_array = displ == null ? value_array : splitEscaped(delChar, displ);
final String descr = Utils.firstNonNull(locale_short_descriptions, short_descriptions);
String[] short_descriptions_array = descr == null ? null : splitEscaped(delChar, descr);
if (display_array.length != value_array.length) {
Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''", key, text));
display_array = value_array;
}
if (short_descriptions_array != null && short_descriptions_array.length != value_array.length) {
Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''", key, text));
short_descriptions_array = null;
}
for (int i = 0; i < value_array.length; i++) {
final PresetListEntry e = new PresetListEntry(value_array[i]);
e.locale_display_value = locale_display_values != null
? display_array[i]
: trc(values_context, fixPresetString(display_array[i]));
if (short_descriptions_array != null) {
e.locale_short_description = locale_short_descriptions != null
? short_descriptions_array[i]
: tr(fixPresetString(short_descriptions_array[i]));
}
lhm.put(value_array[i], e);
display_array[i] = e.getDisplayValue(true);
}
return display_array;
}
protected String getDisplayIfNull() {
return null;
}
@Override
public void addCommands(List<Tag> changedTags) {
Object obj = getSelectedItem();
String display = (obj == null) ? null : obj.toString();
String value = null;
if (display == null) {
display = getDisplayIfNull();
}
if (display != null) {
for (String val : lhm.keySet()) {
String k = lhm.get(val).toString();
if (k != null && k.equals(display)) {
value = val;
break;
}
}
if (value == null) {
value = display;
}
} else {
value = "";
}
value = Tag.removeWhiteSpaces(value);
// no change if same as before
if (originalValue == null) {
if (value.length() == 0)
return;
} else if (value.equals(originalValue.toString()))
return;
if (!"false".equals(use_last_as_default)) {
LAST_VALUES.put(key, value);
}
changedTags.add(new Tag(key, value));
}
public void addListEntry(PresetListEntry e) {
lhm.put(e.value, e);
}
public void addListEntries(Collection<PresetListEntry> e) {
for (PresetListEntry i : e) {
addListEntry(i);
}
}
@Override
boolean requestFocusInWindow() {
return component.requestFocusInWindow();
}
private static final ListCellRenderer<PresetListEntry> RENDERER = new ListCellRenderer<PresetListEntry>() {
JLabel lbl = new JLabel();
@Override
public Component getListCellRendererComponent(
JList<? extends PresetListEntry> list,
PresetListEntry item,
int index,
boolean isSelected,
boolean cellHasFocus) {
// Only return cached size, item is not shown
if (!list.isShowing() && item.prefferedWidth != -1 && item.prefferedHeight != -1) {
if (index == -1) {
lbl.setPreferredSize(new Dimension(item.prefferedWidth, 10));
} else {
lbl.setPreferredSize(new Dimension(item.prefferedWidth, item.prefferedHeight));
}
return lbl;
}
lbl.setPreferredSize(null);
if (isSelected) {
lbl.setBackground(list.getSelectionBackground());
lbl.setForeground(list.getSelectionForeground());
} else {
lbl.setBackground(list.getBackground());
lbl.setForeground(list.getForeground());
}
lbl.setOpaque(true);
lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN));
lbl.setText("<html>" + item.getListDisplay() + "</html>");
lbl.setIcon(item.getIcon());
lbl.setEnabled(list.isEnabled());
// Cache size
item.prefferedWidth = lbl.getPreferredSize().width;
item.prefferedHeight = lbl.getPreferredSize().height;
// We do not want the editor to have the maximum height of all
// entries. Return a dummy with bogus height.
if (index == -1) {
lbl.setPreferredSize(new Dimension(lbl.getPreferredSize().width, 10));
}
return lbl;
}
};
protected ListCellRenderer<PresetListEntry> getListCellRenderer() {
return RENDERER;
}
@Override
public MatchType getDefaultMatch() {
return MatchType.NONE;
}
}
/**
* Combobox type.
*/
public static class Combo extends ComboMultiSelect {
public boolean editable = true;
protected JosmComboBox<PresetListEntry> combo;
public String length;
/**
* Constructs a new {@code Combo}.
*/
public Combo() {
delimiter = ",";
}
@Override
protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
if (!usage.unused()) {
for (String s : usage.values) {
if (!lhm.containsKey(s)) {
lhm.put(s, new PresetListEntry(s));
}
}
}
if (def != null && !lhm.containsKey(def)) {
lhm.put(def, new PresetListEntry(def));
}
lhm.put("", new PresetListEntry(""));
combo = new JosmComboBox<>(lhm.values().toArray(new PresetListEntry[0]));
component = combo;
combo.setRenderer(getListCellRenderer());
combo.setEditable(editable);
combo.reinitialize(lhm.values());
AutoCompletingTextField tf = new AutoCompletingTextField();
initAutoCompletionField(tf, key);
if (Main.pref.getBoolean("taggingpreset.display-keys-as-hint", true)) {
tf.setHint(key);
}
if (length != null && !length.isEmpty()) {
tf.setMaxChars(Integer.valueOf(length));
}
AutoCompletionList acList = tf.getAutoCompletionList();
if (acList != null) {
acList.add(getDisplayValues(), AutoCompletionItemPriority.IS_IN_STANDARD);
}
combo.setEditor(tf);
if (usage.hasUniqueValue()) {
// all items have the same value (and there were no unset items)
originalValue = lhm.get(usage.getFirst());
combo.setSelectedItem(originalValue);
} else if (def != null && usage.unused()) {
// default is set and all items were unset
if (!usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
// selected osm primitives are untagged or filling default feature is enabled
combo.setSelectedItem(lhm.get(def).getDisplayValue(true));
} else {
// selected osm primitives are tagged and filling default feature is disabled
combo.setSelectedItem("");
}
originalValue = lhm.get(DIFFERENT);
} else if (usage.unused()) {
// all items were unset (and so is default)
originalValue = lhm.get("");
if ("force".equals(use_last_as_default) && LAST_VALUES.containsKey(key) && !presetInitiallyMatches) {
combo.setSelectedItem(lhm.get(LAST_VALUES.get(key)));
} else {
combo.setSelectedItem(originalValue);
}
} else {
originalValue = lhm.get(DIFFERENT);
combo.setSelectedItem(originalValue);
}
p.add(combo, GBC.eol().fill(GBC.HORIZONTAL));
}
@Override
protected Object getSelectedItem() {
return combo.getSelectedItem();
}
@Override
protected String getDisplayIfNull() {
if (combo.isEditable())
return combo.getEditor().getItem().toString();
else
return null;
}
}
/**
* Multi-select list type.
*/
public static class MultiSelect extends ComboMultiSelect {
public long rows = -1;
protected ConcatenatingJList list;
@Override
protected void addToPanelAnchor(JPanel p, String def, boolean presetInitiallyMatches) {
list = new ConcatenatingJList(delimiter, lhm.values().toArray(new PresetListEntry[0]));
component = list;
ListCellRenderer<PresetListEntry> renderer = getListCellRenderer();
list.setCellRenderer(renderer);
if (usage.hasUniqueValue() && !usage.unused()) {
originalValue = usage.getFirst();
list.setSelectedItem(originalValue);
} else if (def != null && !usage.hadKeys() || PROP_FILL_DEFAULT.get() || "force".equals(use_last_as_default)) {
originalValue = DIFFERENT;
list.setSelectedItem(def);
} else if (usage.unused()) {
originalValue = null;
list.setSelectedItem(originalValue);
} else {
originalValue = DIFFERENT;
list.setSelectedItem(originalValue);
}
JScrollPane sp = new JScrollPane(list);
// if a number of rows has been specified in the preset,
// modify preferred height of scroll pane to match that row count.
if (rows != -1) {
double height = renderer.getListCellRendererComponent(list,
new PresetListEntry("x"), 0, false, false).getPreferredSize().getHeight() * rows;
sp.setPreferredSize(new Dimension((int) sp.getPreferredSize().getWidth(), (int) height));
}
p.add(sp, GBC.eol().fill(GBC.HORIZONTAL));
}
@Override
protected Object getSelectedItem() {
return list.getSelectedItem();
}
@Override
public void addCommands(List<Tag> changedTags) {
// Do not create any commands if list has been disabled because of an unknown value (fix #8605)
if (list.isEnabled()) {
super.addCommands(changedTags);
}
}
}
/**
* Class that allows list values to be assigned and retrieved as a comma-delimited
* string (extracted from TaggingPreset)
*/
private static class ConcatenatingJList extends JList<PresetListEntry> {
private String delimiter;
public ConcatenatingJList(String del, PresetListEntry[] o) {
super(o);
delimiter = del;
}
public void setSelectedItem(Object o) {
if (o == null) {
clearSelection();
} else {
String s = o.toString();
TreeSet<String> parts = new TreeSet<>(Arrays.asList(s.split(delimiter)));
ListModel<PresetListEntry> lm = getModel();
int[] intParts = new int[lm.getSize()];
int j = 0;
for (int i = 0; i < lm.getSize(); i++) {
if (parts.contains((lm.getElementAt(i).value))) {
intParts[j++]=i;
}
}
setSelectedIndices(Arrays.copyOf(intParts, j));
// check if we have actually managed to represent the full
// value with our presets. if not, cop out; we will not offer
// a selection list that threatens to ruin the value.
setEnabled(Utils.join(delimiter, parts).equals(getSelectedItem()));
}
}
public String getSelectedItem() {
ListModel<PresetListEntry> lm = getModel();
int[] si = getSelectedIndices();
StringBuilder builder = new StringBuilder();
for (int i=0; i<si.length; i++) {
if (i>0) {
builder.append(delimiter);
}
builder.append(lm.getElementAt(si[i]).value);
}
return builder.toString();
}
}
public static EnumSet<TaggingPresetType> getType(String types) throws SAXException {
if (TYPE_CACHE.containsKey(types))
return TYPE_CACHE.get(types);
EnumSet<TaggingPresetType> result = EnumSet.noneOf(TaggingPresetType.class);
for (String type : Arrays.asList(types.split(","))) {
try {
TaggingPresetType presetType = TaggingPresetType.fromString(type);
result.add(presetType);
} catch (IllegalArgumentException e) {
throw new SAXException(tr("Unknown type: {0}", type), e);
}
}
TYPE_CACHE.put(types, result);
return result;
}
static String fixPresetString(String s) {
return s == null ? s : s.replaceAll("'","''");
}
private static String getLocaleText(String text, String text_context, String defaultText) {
if (text == null) {
return defaultText;
} else if (text_context != null) {
return trc(text_context, fixPresetString(text));
} else {
return tr(fixPresetString(text));
}
}
/**
* allow escaped comma in comma separated list:
* "A\, B\, C,one\, two" --> ["A, B, C", "one, two"]
* @param delimiter the delimiter, e.g. a comma. separates the entries and
* must be escaped within one entry
* @param s the string
*/
private static String[] splitEscaped(char delimiter, String s) {
if (s == null)
return new String[0];
List<String> result = new ArrayList<>();
boolean backslash = false;
StringBuilder item = new StringBuilder();
for (int i=0; i<s.length(); i++) {
char ch = s.charAt(i);
if (backslash) {
item.append(ch);
backslash = false;
} else if (ch == '\\') {
backslash = true;
} else if (ch == delimiter) {
result.add(item.toString());
item.setLength(0);
} else {
item.append(ch);
}
}
if (item.length() > 0) {
result.add(item.toString());
}
return result.toArray(new String[result.size()]);
}
static Usage determineTextUsage(Collection<OsmPrimitive> sel, String key) {
Usage returnValue = new Usage();
returnValue.values = new TreeSet<>();
for (OsmPrimitive s : sel) {
String v = s.get(key);
if (v != null) {
returnValue.values.add(v);
} else {
returnValue.hadEmpty = true;
}
if(s.hasKeys()) {
returnValue.hadKeys = true;
}
}
return returnValue;
}
static Usage determineBooleanUsage(Collection<OsmPrimitive> sel, String key) {
Usage returnValue = new Usage();
returnValue.values = new TreeSet<>();
for (OsmPrimitive s : sel) {
String booleanValue = OsmUtils.getNamedOsmBoolean(s.get(key));
if (booleanValue != null) {
returnValue.values.add(booleanValue);
}
}
return returnValue;
}
protected static ImageIcon loadImageIcon(String iconName, File zipIcons, Integer maxSize) {
LinkedList<String> s = new LinkedList<String>();
MapPaintStyles.addDebianDirs(s);
String realIconName = iconName;
if (iconName.startsWith("styles/standard/")) {
realIconName = iconName.replace("styles/standard/", "");
}
ImageProvider imgProv = new ImageProvider(realIconName).setDirs(s).setId("presets").setArchive(zipIcons).setOptional(true);
if (maxSize != null) {
imgProv.setMaxSize(maxSize);
}
ImageIcon icon = imgProv.get();
if (icon == null) {
System.out.println("Could not get presets icon " + realIconName);
icon = new ImageIcon(realIconName);
}
return icon;
}
protected static Integer parseInteger(String str) {
if (str == null || str.isEmpty())
return null;
try {
return Integer.parseInt(str);
} catch (Exception e) {
if (Main.isTraceEnabled()) {
Main.trace(e.getMessage());
}
}
return null;
}
}
|