- Timestamp:
- 2015-06-20T14:36:00+02:00 (9 years ago)
- Location:
- trunk/src
- Files:
-
- 181 edited
Legend:
- Unmodified
- Added
- Removed
-
trunk/src/JOSM.java
r7509 r8509 1 // License: GPL. Copyright 2007 by Immanuel Scholz and others1 // License: GPL. For details, see LICENSE file. 2 2 import org.openstreetmap.josm.gui.MainApplication; 3 3 -
trunk/src/org/openstreetmap/josm/Main.java
r8506 r8509 1040 1040 1041 1041 /** 1042 * Asks user to perform "save layer" operations (save on disk and/or upload data to server) for all {@link AbstractModifiableLayer} before JOSM exits. 1043 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. {@code false} if the user cancels. 1042 * Asks user to perform "save layer" operations (save on disk and/or upload data to server) for all 1043 * {@link AbstractModifiableLayer} before JOSM exits. 1044 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. 1045 * {@code false} if the user cancels. 1044 1046 * @since 2025 1045 1047 */ … … 1054 1056 * @param selectedLayers The layers to check. Only instances of {@link AbstractModifiableLayer} are considered. 1055 1057 * @param exit {@code true} if JOSM is exiting, {@code false} otherwise. 1056 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. {@code false} if the user cancels. 1058 * @return {@code true} if there was nothing to save, or if the user wants to proceed to save operations. 1059 * {@code false} if the user cancels. 1057 1060 * @since 5519 1058 1061 */ -
trunk/src/org/openstreetmap/josm/actions/AbstractInfoAction.java
r8475 r8509 29 29 } 30 30 31 public AbstractInfoAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean register, String toolbarId, boolean installAdapters) { 31 public AbstractInfoAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean register, 32 String toolbarId, boolean installAdapters) { 32 33 super(name, iconName, tooltip, shortcut, register, toolbarId, installAdapters); 33 34 } … … 46 47 tr("Continue"), 47 48 ImageProvider.get("ok"), 48 trn("Click to continue and to open {0} browser", "Click to continue and to open {0} browsers", numBrowsers, numBrowsers), 49 trn("Click to continue and to open {0} browser", "Click to continue and to open {0} browsers", 50 numBrowsers, numBrowsers), 49 51 null // no specific help topic 50 52 ), -
trunk/src/org/openstreetmap/josm/actions/AddImageryLayerAction.java
r8469 r8509 146 146 @Override 147 147 protected void updateEnabledState() { 148 ImageryType type = info.getImageryType(); 148 149 // never enable blacklisted entries. Do not add same imagery layer twice (fix #2519) 149 if (info.isBlacklisted() /*|| isLayerAlreadyPresent()*/) { // FIXME check disabled to allow several instances with different settings (see #7981) 150 if (info.isBlacklisted() /*|| isLayerAlreadyPresent()*/) { 151 // FIXME check disabled to allow several instances with different settings (see #7981) 150 152 setEnabled(false); 151 } else if ( info.getImageryType() == ImageryType.TMS || info.getImageryType() == ImageryType.BING || info.getImageryType()== ImageryType.SCANEX) {153 } else if (type == ImageryType.TMS || type == ImageryType.BING || type == ImageryType.SCANEX) { 152 154 setEnabled(true); 153 155 } else if (Main.isDisplayingMapView() && !Main.map.mapView.getAllLayers().isEmpty()) { -
trunk/src/org/openstreetmap/josm/actions/DiskAccessAction.java
r7578 r8509 42 42 * @since 5438 43 43 */ 44 public DiskAccessAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean register, String toolbarId, boolean installAdapters) { 44 public DiskAccessAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean register, 45 String toolbarId, boolean installAdapters) { 45 46 super(name, iconName, tooltip, shortcut, register, toolbarId, installAdapters); 46 47 } … … 84 85 * If false, only the file filters that include {@code extension} will be proposed 85 86 * @param lastDirProperty The name of the property used to setup the AbstractFileChooser initial directory. 86 * This property will then be updated to the new "last directory" chosen by the user. If null, the default property "lastDirectory" will be used. 87 * This property will then be updated to the new "last directory" chosen by the user. 88 * If null, the default property "lastDirectory" will be used. 87 89 * @return The {@code AbstractFileChooser}. 88 90 * @since 5438 89 91 */ 90 public static AbstractFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title, String extension, int selectionMode, boolean allTypes, String lastDirProperty) { 91 return new FileChooserManager(open, lastDirProperty).createFileChooser(multiple, title, extension, allTypes, selectionMode).openFileChooser(); 92 public static AbstractFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title, String extension, 93 int selectionMode, boolean allTypes, String lastDirProperty) { 94 return new FileChooserManager(open, lastDirProperty) 95 .createFileChooser(multiple, title, extension, allTypes, selectionMode).openFileChooser(); 92 96 } 93 97 … … 102 106 * <li>just select directories ({@code JFileChooser.DIRECTORIES_ONLY})</li> 103 107 * <li>select both files and directories ({@code JFileChooser.FILES_AND_DIRECTORIES})</li></ul> 104 * @param lastDirProperty The name of the property used to setup the AbstractFileChooser initial directory. This property will then be updated to the new "last directory" chosen by the user 108 * @param lastDirProperty The name of the property used to setup the AbstractFileChooser initial directory. 109 * This property will then be updated to the new "last directory" chosen by the user 105 110 * @return The {@code AbstractFileChooser}. 106 111 * @since 5438 107 112 */ 108 public static AbstractFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title, FileFilter filter, int selectionMode, String lastDirProperty) { 113 public static AbstractFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title, FileFilter filter, 114 int selectionMode, String lastDirProperty) { 109 115 return new FileChooserManager(open, lastDirProperty).createFileChooser(multiple, title, filter, selectionMode).openFileChooser(); 110 116 } … … 121 127 * <li>just select directories ({@code JFileChooser.DIRECTORIES_ONLY})</li> 122 128 * <li>select both files and directories ({@code JFileChooser.FILES_AND_DIRECTORIES})</li></ul> 123 * @param lastDirProperty The name of the property used to setup the JFileChooser initial directory. This property will then be updated to the new "last directory" chosen by the user 129 * @param lastDirProperty The name of the property used to setup the JFileChooser initial directory. 130 * This property will then be updated to the new "last directory" chosen by the user 124 131 * @return The {@code AbstractFileChooser}. 125 132 * @since 5438 … … 127 134 public static AbstractFileChooser createAndOpenFileChooser(boolean open, boolean multiple, String title, 128 135 Collection<? extends FileFilter> filters, FileFilter defaultFilter, int selectionMode, String lastDirProperty) { 129 return new FileChooserManager(open, lastDirProperty).createFileChooser(multiple, title, filters, defaultFilter, selectionMode).openFileChooser(); 136 return new FileChooserManager(open, lastDirProperty).createFileChooser(multiple, title, filters, defaultFilter, selectionMode) 137 .openFileChooser(); 130 138 } 131 139 } -
trunk/src/org/openstreetmap/josm/actions/DownloadAlongAction.java
r7937 r8509 44 44 super(name, iconName, tooltip, shortcut, registerInToolbar); 45 45 } 46 46 47 47 protected static void addToDownload(Area a, Rectangle2D r, Collection<Rectangle2D> results, double maxArea) { 48 48 Area tmp = new Area(r); … … 74 74 } 75 75 } 76 76 77 77 /** 78 78 * Area "a" contains the hull that we would like to download data for. however we … … 92 92 * the areas if applicable. 93 93 */ 94 protected static void confirmAndDownloadAreas(Area a, double maxArea, boolean osmDownload, boolean gpxDownload, String title, ProgressMonitor progressMonitor) { 94 protected static void confirmAndDownloadAreas(Area a, double maxArea, boolean osmDownload, boolean gpxDownload, String title, 95 ProgressMonitor progressMonitor) { 95 96 List<Rectangle2D> toDownload = new ArrayList<>(); 96 97 addToDownload(a, a.getBounds(), toDownload, maxArea); … … 99 100 } 100 101 JPanel msg = new JPanel(new GridBagLayout()); 101 msg.add(new JLabel(tr("<html>This action will require {0} individual<br>" + "download requests. Do you wish<br>to continue?</html>", toDownload.size())), GBC.eol()); 102 if (JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(Main.parent, msg, title, JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) { 102 msg.add(new JLabel( 103 tr("<html>This action will require {0} individual<br>" + "download requests. Do you wish<br>to continue?</html>", 104 toDownload.size())), GBC.eol()); 105 if (JOptionPane.OK_OPTION != JOptionPane.showConfirmDialog(Main.parent, msg, title, 106 JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE)) { 103 107 return; 104 108 } -
trunk/src/org/openstreetmap/josm/actions/DownloadPrimitiveAction.java
r8378 r8509 28 28 public DownloadPrimitiveAction() { 29 29 super(tr("Download object..."), "downloadprimitive", tr("Download OSM object by ID."), 30 Shortcut.registerShortcut("system:download_primitive", tr("File: {0}", tr("Download object...")), KeyEvent.VK_O, Shortcut.CTRL_SHIFT), true); 30 Shortcut.registerShortcut("system:download_primitive", tr("File: {0}", tr("Download object...")), 31 KeyEvent.VK_O, Shortcut.CTRL_SHIFT), true); 31 32 putValue("help", ht("/Action/DownloadObject")); 32 33 } … … 44 45 * @param newLayer if the data should be downloaded into a new layer 45 46 * @param ids List of primitive id to download 46 * @param downloadReferrers if the referrers of the object should be downloaded as well, i.e., parent relations, and for nodes, additionally, parent ways 47 * @param downloadReferrers if the referrers of the object should be downloaded as well, i.e., parent relations, and for nodes, 48 * additionally, parent ways 47 49 * @param full if the members of a relation should be downloaded as well 48 50 */ -
trunk/src/org/openstreetmap/josm/actions/GpxExportAction.java
r8443 r8509 80 80 CheckParameterUtil.ensureParameterNotNull(layer, "layer"); 81 81 if (!(layer instanceof OsmDataLayer) && !(layer instanceof GpxLayer)) 82 throw new IllegalArgumentException(MessageFormat.format("Expected instance of OsmDataLayer or GpxLayer. Got ''{0}''.", layer.getClass().getName())); 82 throw new IllegalArgumentException(MessageFormat.format("Expected instance of OsmDataLayer or GpxLayer. Got ''{0}''.", 83 layer.getClass().getName())); 83 84 84 85 File file = createAndOpenSaveFileChooser(tr("Export GPX file"), GpxImporter.FILE_FILTER); -
trunk/src/org/openstreetmap/josm/actions/JosmAction.java
r8324 r8509 73 73 * TODO: do not pass Icon, pass ImageProvider instead 74 74 */ 75 public JosmAction(String name, ImageProvider icon, String tooltip, Shortcut shortcut, boolean registerInToolbar, String toolbarId, boolean installAdapters) { 75 public JosmAction(String name, ImageProvider icon, String tooltip, Shortcut shortcut, boolean registerInToolbar, 76 String toolbarId, boolean installAdapters) { 76 77 super(name); 77 78 if(icon != null) … … 111 112 * @param installAdapters false, if you don't want to install layer changed and selection changed adapters 112 113 */ 113 public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar, String toolbarId, boolean installAdapters) { 114 public JosmAction(String name, String iconName, String tooltip, Shortcut shortcut, boolean registerInToolbar, 115 String toolbarId, boolean installAdapters) { 114 116 this(name, iconName == null ? null : new ImageProvider(iconName), tooltip, shortcut, registerInToolbar, 115 117 toolbarId == null ? iconName : toolbarId, installAdapters); -
trunk/src/org/openstreetmap/josm/actions/JumpToAction.java
r8443 r8509 128 128 ll = new LatLon(Double.parseDouble(lat.getText()), Double.parseDouble(lon.getText())); 129 129 } catch (NumberFormatException ex) { 130 JOptionPane.showMessageDialog(Main.parent, tr("Could not parse Latitude, Longitude or Zoom. Please check."), tr("Unable to parse Lon/Lat"), JOptionPane.ERROR_MESSAGE); 130 JOptionPane.showMessageDialog(Main.parent, 131 tr("Could not parse Latitude, Longitude or Zoom. Please check."), 132 tr("Unable to parse Lon/Lat"), JOptionPane.ERROR_MESSAGE); 131 133 } 132 134 } -
trunk/src/org/openstreetmap/josm/actions/SessionSaveAsAction.java
r8426 r8509 89 89 fc = createAndOpenFileChooser(false, false, tr("Save session"), joz, JFileChooser.FILES_ONLY, "lastDirectory"); 90 90 } else { 91 fc = createAndOpenFileChooser(false, false, tr("Save session"), Arrays.asList(new FileFilter[]{jos, joz}), jos, JFileChooser.FILES_ONLY, "lastDirectory"); 91 fc = createAndOpenFileChooser(false, false, tr("Save session"), Arrays.asList(new FileFilter[]{jos, joz}), jos, 92 JFileChooser.FILES_ONLY, "lastDirectory"); 92 93 } 93 94 -
trunk/src/org/openstreetmap/josm/actions/SimplifyWayAction.java
r8459 r8509 44 44 */ 45 45 public SimplifyWayAction() { 46 super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."), Shortcut.registerShortcut("tools:simplify", tr("Tool: {0}", tr("Simplify Way")),47 KeyEvent.VK_Y, Shortcut.SHIFT), true);46 super(tr("Simplify Way"), "simplify", tr("Delete unnecessary nodes from a way."), 47 Shortcut.registerShortcut("tools:simplify", tr("Tool: {0}", tr("Simplify Way")), KeyEvent.VK_Y, Shortcut.SHIFT), true); 48 48 putValue("help", ht("/Action/SimplifyWay")); 49 49 } -
trunk/src/org/openstreetmap/josm/actions/ToggleAction.java
r8390 r8509 40 40 * @param installAdapters false, if you don't want to install layer changed and selection changed adapters 41 41 */ 42 public ToggleAction(String name, ImageProvider icon, String tooltip, Shortcut shortcut, boolean registerInToolbar, String toolbarId, boolean installAdapters) { 42 public ToggleAction(String name, ImageProvider icon, String tooltip, Shortcut shortcut, boolean registerInToolbar, 43 String toolbarId, boolean installAdapters) { 43 44 super(name, icon, tooltip, shortcut, registerInToolbar, toolbarId, installAdapters); 44 45 // It is required to set the SELECTED_KEY to a non-null value in order to let Swing components update it … … 115 116 /** 116 117 * Toggles the selcted action state, if needed according to the ActionEvent that trigerred the action. 117 * This method will do nothing if the action event comes from a Swing component supporting the SELECTED_KEY property because the component already set the selected state. 118 * This method will do nothing if the action event comes from a Swing component supporting the SELECTED_KEY property because 119 * the component already set the selected state. 118 120 * This method needs to be called especially if the action is associated with a keyboard shortcut to ensure correct selected state. 119 121 * @see <a href="https://weblogs.java.net/blog/zixle/archive/2005/11/changes_to_acti.html">Changes to Actions in 1.6</a> -
trunk/src/org/openstreetmap/josm/actions/UnGlueAction.java
r8338 r8509 464 464 465 465 Main.main.undoRedo.add(new SequenceCommand( 466 trn("Dupe {0} node into {1} nodes", "Dupe {0} nodes into {1} nodes", selectedNodes.size(), selectedNodes.size(), selectedNodes.size()+allNewNodes.size()), cmds)); 466 trn("Dupe {0} node into {1} nodes", "Dupe {0} nodes into {1} nodes", 467 selectedNodes.size(), selectedNodes.size(), selectedNodes.size()+allNewNodes.size()), cmds)); 467 468 getCurrentDataSet().setSelected(allNewNodes); 468 469 } -
trunk/src/org/openstreetmap/josm/actions/UpdateSelectionAction.java
r8443 r8509 35 35 * 36 36 * @param id the primitive id 37 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 37 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, 38 * {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 38 39 */ 39 40 public static void handlePrimitiveGoneException(long id, OsmPrimitiveType type) { -
trunk/src/org/openstreetmap/josm/actions/ValidateAction.java
r8378 r8509 124 124 * @param formerValidatedPrimitives the last collection of primitives being validates. May be null. 125 125 */ 126 public ValidationTask(Collection<Test> tests, Collection<OsmPrimitive> validatedPrimitives, Collection<OsmPrimitive> formerValidatedPrimitives) { 126 public ValidationTask(Collection<Test> tests, Collection<OsmPrimitive> validatedPrimitives, 127 Collection<OsmPrimitive> formerValidatedPrimitives) { 127 128 super(tr("Validating"), false /*don't ignore exceptions */); 128 129 this.validatedPrimitives = validatedPrimitives; -
trunk/src/org/openstreetmap/josm/actions/mapmode/DrawAction.java
r8465 r8509 626 626 } 627 627 628 private void insertNodeIntoAllNearbySegments(List<WaySegment> wss, Node n, Collection<OsmPrimitive> newSelection, Collection<Command> cmds, List<Way> replacedWays, List<Way> reuseWays) { 628 private void insertNodeIntoAllNearbySegments(List<WaySegment> wss, Node n, Collection<OsmPrimitive> newSelection, 629 Collection<Command> cmds, List<Way> replacedWays, List<Way> reuseWays) { 629 630 Map<Way, List<Integer>> insertPoints = new HashMap<>(); 630 631 for (WaySegment ws : wss) { … … 1293 1294 1294 1295 private class SnapHelper { 1295 private boolean snapOn; // snapping is turned on 1296 1297 private boolean active; // snapping is active for current mouse position 1298 private boolean fixed; // snap angle is fixed 1299 private boolean absoluteFix; // snap angle is absolute 1300 1301 private boolean drawConstructionGeometry; 1302 private boolean showProjectedPoint; 1303 private boolean showAngle; 1304 1305 private boolean snapToProjections; 1306 1307 private EastNorth dir2; 1308 private EastNorth projected; 1309 private String labelText; 1310 private double lastAngle; 1311 1312 private double customBaseHeading=-1; // angle of base line, if not last segment) 1313 private EastNorth segmentPoint1; // remembered first point of base segment 1314 private EastNorth segmentPoint2; // remembered second point of base segment 1315 private EastNorth projectionSource; // point that we are projecting to the line 1316 1317 private double[] snapAngles; 1318 private double snapAngleTolerance; 1319 1320 private double pe,pn; // (pe,pn) - direction of snapping line 1321 private double e0,n0; // (e0,n0) - origin of snapping line 1322 1323 private final String fixFmt="%d "+tr("FIX"); 1324 private Color snapHelperColor; 1325 private Color highlightColor; 1326 1327 private Stroke normalStroke; 1328 private Stroke helperStroke; 1329 private Stroke highlightStroke; 1330 1331 private JCheckBoxMenuItem checkBox; 1332 1333 public void init() { 1334 snapOn=false; 1335 checkBox.setState(snapOn); 1336 fixed=false; absoluteFix=false; 1337 1338 Collection<String> angles = Main.pref.getCollection("draw.anglesnap.angles", 1339 Arrays.asList("0","30","45","60","90","120","135","150","180")); 1340 1341 snapAngles = new double[2*angles.size()]; 1342 int i=0; 1343 for (String s: angles) { 1344 try { 1345 snapAngles[i] = Double.parseDouble(s); i++; 1346 snapAngles[i] = 360-Double.parseDouble(s); i++; 1347 } catch (NumberFormatException e) { 1348 Main.warn("Incorrect number in draw.anglesnap.angles preferences: "+s); 1349 snapAngles[i]=0;i++; 1350 snapAngles[i]=0;i++; 1351 } 1352 } 1353 snapAngleTolerance = Main.pref.getDouble("draw.anglesnap.tolerance", 5.0); 1354 drawConstructionGeometry = Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry", true); 1355 showProjectedPoint = Main.pref.getBoolean("draw.anglesnap.drawProjectedPoint", true); 1356 snapToProjections = Main.pref.getBoolean("draw.anglesnap.projectionsnap", true); 1357 1358 showAngle = Main.pref.getBoolean("draw.anglesnap.showAngle", true); 1359 useRepeatedShortcut = Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA", true); 1360 1361 normalStroke = rubberLineStroke; 1362 snapHelperColor = Main.pref.getColor(marktr("draw angle snap"), Color.ORANGE); 1363 1364 highlightColor = Main.pref.getColor(marktr("draw angle snap highlight"), ORANGE_TRANSPARENT); 1365 highlightStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.highlight","10")); 1366 helperStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.helper","1 4")); 1367 } 1368 1369 public void saveAngles(String ... angles) { 1370 Main.pref.putCollection("draw.anglesnap.angles", Arrays.asList(angles)); 1371 } 1372 1373 public void setMenuCheckBox(JCheckBoxMenuItem checkBox) { 1374 this.checkBox = checkBox; 1375 } 1376 1377 public void drawIfNeeded(Graphics2D g2, MapView mv) { 1378 if (!snapOn || !active) 1379 return; 1380 Point p1=mv.getPoint(getCurrentBaseNode()); 1381 Point p2=mv.getPoint(dir2); 1382 Point p3=mv.getPoint(projected); 1383 GeneralPath b; 1384 if (drawConstructionGeometry) { 1385 g2.setColor(snapHelperColor); 1386 g2.setStroke(helperStroke); 1387 1388 b = new GeneralPath(); 1389 if (absoluteFix) { 1390 b.moveTo(p2.x,p2.y); 1391 b.lineTo(2*p1.x-p2.x,2*p1.y-p2.y); // bi-directional line 1392 } else { 1393 b.moveTo(p2.x,p2.y); 1394 b.lineTo(p3.x,p3.y); 1395 } 1396 g2.draw(b); 1397 } 1398 if (projectionSource != null) { 1399 g2.setColor(snapHelperColor); 1400 g2.setStroke(helperStroke); 1401 b = new GeneralPath(); 1402 b.moveTo(p3.x,p3.y); 1403 Point pp=mv.getPoint(projectionSource); 1404 b.lineTo(pp.x,pp.y); 1405 g2.draw(b); 1406 } 1407 1408 if (customBaseHeading >= 0) { 1409 g2.setColor(highlightColor); 1410 g2.setStroke(highlightStroke); 1411 b = new GeneralPath(); 1412 Point pp1=mv.getPoint(segmentPoint1); 1413 Point pp2=mv.getPoint(segmentPoint2); 1414 b.moveTo(pp1.x,pp1.y); 1415 b.lineTo(pp2.x,pp2.y); 1416 g2.draw(b); 1417 } 1418 1419 g2.setColor(rubberLineColor); 1420 g2.setStroke(normalStroke); 1421 b = new GeneralPath(); 1422 b.moveTo(p1.x,p1.y); 1423 b.lineTo(p3.x,p3.y); 1424 g2.draw(b); 1425 1426 g2.drawString(labelText, p3.x-5, p3.y+20); 1427 if (showProjectedPoint) { 1428 g2.setStroke(normalStroke); 1429 g2.drawOval(p3.x-5, p3.y-5, 10, 10); // projected point 1430 } 1431 1432 g2.setColor(snapHelperColor); 1433 g2.setStroke(helperStroke); 1434 } 1435 1436 /* If mouse position is close to line at 15-30-45-... angle, remembers this direction 1437 */ 1438 public void checkAngleSnapping(EastNorth currentEN, double baseHeading, double curHeading) { 1439 EastNorth p0 = getCurrentBaseNode().getEastNorth(); 1440 EastNorth snapPoint = currentEN; 1441 double angle = -1; 1442 1443 double activeBaseHeading = (customBaseHeading>=0)? customBaseHeading : baseHeading; 1444 1445 if (snapOn && (activeBaseHeading>=0)) { 1446 angle = curHeading - activeBaseHeading; 1447 if (angle < 0) { 1448 angle+=360; 1449 } 1450 if (angle > 360) { 1451 angle=0; 1452 } 1453 1454 double nearestAngle; 1455 if (fixed) { 1456 nearestAngle = lastAngle; // if direction is fixed use previous angle 1457 active = true; 1458 } else { 1459 nearestAngle = getNearestAngle(angle); 1460 if (getAngleDelta(nearestAngle, angle) < snapAngleTolerance) { 1461 active = (customBaseHeading>=0)? true : Math.abs(nearestAngle - 180) > 1e-3; 1462 // if angle is to previous segment, exclude 180 degrees 1463 lastAngle = nearestAngle; 1464 } else { 1465 active=false; 1466 } 1467 } 1468 1469 if (active) { 1470 double phi; 1471 e0 = p0.east(); 1472 n0 = p0.north(); 1473 buildLabelText((nearestAngle<=180) ? nearestAngle : nearestAngle-360); 1474 1475 phi = (nearestAngle + activeBaseHeading) * Math.PI / 180; 1476 // (pe,pn) - direction of snapping line 1477 pe = Math.sin(phi); 1478 pn = Math.cos(phi); 1479 double scale = 20 * Main.map.mapView.getDist100Pixel(); 1480 dir2 = new EastNorth(e0 + scale * pe, n0 + scale * pn); 1481 snapPoint = getSnapPoint(currentEN); 1482 } else { 1483 noSnapNow(); 1484 } 1485 } 1486 1487 // find out the distance, in metres, between the base point and projected point 1488 LatLon mouseLatLon = Main.map.mapView.getProjection().eastNorth2latlon(snapPoint); 1489 double distance = getCurrentBaseNode().getCoor().greatCircleDistance(mouseLatLon); 1490 double hdg = Math.toDegrees(p0.heading(snapPoint)); 1491 // heading of segment from current to calculated point, not to mouse position 1492 1493 if (baseHeading >= 0) { // there is previous line segment with some heading 1494 angle = hdg - baseHeading; 1495 if (angle < 0) { 1496 angle+=360; 1497 } 1498 if (angle > 360) { 1499 angle=0; 1500 } 1501 } 1502 showStatusInfo(angle, hdg, distance, isSnapOn()); 1503 } 1504 1505 private void buildLabelText(double nearestAngle) { 1506 if (showAngle) { 1507 if (fixed) { 1508 if (absoluteFix) { 1509 labelText = "="; 1510 } else { 1511 labelText = String.format(fixFmt, (int) nearestAngle); 1512 } 1513 } else { 1514 labelText = String.format("%d", (int) nearestAngle); 1515 } 1516 } else { 1517 if (fixed) { 1518 if (absoluteFix) { 1519 labelText = "="; 1520 } else { 1521 labelText = String.format(tr("FIX"), 0); 1522 } 1523 } else { 1524 labelText = ""; 1525 } 1526 } 1527 } 1528 1529 public EastNorth getSnapPoint(EastNorth p) { 1530 if (!active) 1531 return p; 1532 double de=p.east()-e0; 1533 double dn=p.north()-n0; 1534 double l = de*pe+dn*pn; 1535 double delta = Main.map.mapView.getDist100Pixel()/20; 1536 if (!absoluteFix && l<delta) { 1537 active=false; 1538 return p; 1539 } // do not go backward! 1540 1541 projectionSource=null; 1542 if (snapToProjections) { 1543 DataSet ds = getCurrentDataSet(); 1544 Collection<Way> selectedWays = ds.getSelectedWays(); 1545 if (selectedWays.size()==1) { 1546 Way w = selectedWays.iterator().next(); 1547 Collection<EastNorth> pointsToProject = new ArrayList<>(); 1548 if (w.getNodesCount()<1000) { 1549 for (Node n: w.getNodes()) { 1550 pointsToProject.add(n.getEastNorth()); 1551 } 1552 } 1553 if (customBaseHeading >= 0) { 1554 pointsToProject.add(segmentPoint1); 1555 pointsToProject.add(segmentPoint2); 1556 } 1557 EastNorth enOpt=null; 1558 double dOpt=1e5; 1559 for (EastNorth en: pointsToProject) { // searching for besht projection 1560 double l1 = (en.east()-e0)*pe+(en.north()-n0)*pn; 1561 double d1 = Math.abs(l1-l); 1562 if (d1 < delta && d1 < dOpt) { 1563 l=l1; 1564 enOpt = en; 1565 dOpt = d1; 1566 } 1567 } 1568 if (enOpt!=null) { 1569 projectionSource = enOpt; 1570 } 1571 } 1572 } 1573 return projected = new EastNorth(e0+l*pe, n0+l*pn); 1574 } 1575 1576 1577 public void noSnapNow() { 1578 active=false; 1579 dir2=null; projected=null; 1580 labelText=null; 1581 } 1582 1583 public void setBaseSegment(WaySegment seg) { 1584 if (seg==null) return; 1585 segmentPoint1=seg.getFirstNode().getEastNorth(); 1586 segmentPoint2=seg.getSecondNode().getEastNorth(); 1587 1588 double hdg = segmentPoint1.heading(segmentPoint2); 1589 hdg=Math.toDegrees(hdg); 1590 if (hdg<0) { 1591 hdg+=360; 1592 } 1593 if (hdg>360) { 1594 hdg-=360; 1595 } 1596 customBaseHeading=hdg; 1597 } 1598 1599 private void nextSnapMode() { 1600 if (snapOn) { 1601 // turn off snapping if we are in fixed mode or no actile snapping line exist 1602 if (fixed || !active) { 1603 snapOn = false; 1604 unsetFixedMode(); 1605 } else { 1606 setFixedMode(); 1607 } 1608 } else { 1609 snapOn=true; 1610 unsetFixedMode(); 1611 } 1612 checkBox.setState(snapOn); 1613 customBaseHeading=-1; 1614 } 1615 1616 private void enableSnapping() { 1617 snapOn = true; 1618 checkBox.setState(snapOn); 1619 customBaseHeading=-1; 1620 unsetFixedMode(); 1621 } 1622 1623 private void toggleSnapping() { 1624 snapOn = !snapOn; 1625 checkBox.setState(snapOn); 1626 customBaseHeading=-1; 1627 unsetFixedMode(); 1628 } 1629 1630 public void setFixedMode() { 1631 if (active) { 1632 fixed=true; 1633 } 1634 } 1635 1636 1637 public void unsetFixedMode() { 1638 fixed=false; 1639 absoluteFix=false; 1640 lastAngle=0; 1641 active=false; 1642 } 1643 1644 public boolean isActive() { 1645 return active; 1646 } 1647 1648 public boolean isSnapOn() { 1649 return snapOn; 1650 } 1651 1652 private double getNearestAngle(double angle) { 1653 double delta,minDelta=1e5, bestAngle=0.0; 1654 for (double snapAngle : snapAngles) { 1655 delta = getAngleDelta(angle, snapAngle); 1656 if (delta < minDelta) { 1657 minDelta = delta; 1658 bestAngle = snapAngle; 1659 } 1660 } 1661 if (Math.abs(bestAngle-360) < 1e-3) { 1662 bestAngle=0; 1663 } 1664 return bestAngle; 1665 } 1666 1667 private double getAngleDelta(double a, double b) { 1668 double delta = Math.abs(a-b); 1669 if (delta>180) 1670 return 360-delta; 1671 else 1672 return delta; 1673 } 1674 1675 private void unFixOrTurnOff() { 1676 if (absoluteFix) { 1677 unsetFixedMode(); 1678 } else { 1679 toggleSnapping(); 1680 } 1681 } 1682 1683 private MouseListener anglePopupListener = new PopupMenuLauncher(new JPopupMenu() { 1684 private JCheckBoxMenuItem repeatedCb = new JCheckBoxMenuItem( 1296 private final class AnglePopupMenu extends JPopupMenu { 1297 1298 private final JCheckBoxMenuItem repeatedCb = new JCheckBoxMenuItem( 1685 1299 new AbstractAction(tr("Toggle snapping by {0}", getShortcut().getKeyText())) { 1686 @Override public void actionPerformed(ActionEvent e) { 1300 @Override 1301 public void actionPerformed(ActionEvent e) { 1687 1302 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState(); 1688 1303 Main.pref.put("draw.anglesnap.toggleOnRepeatedA", sel); … … 1690 1305 } 1691 1306 }); 1692 private JCheckBoxMenuItem helperCb = new JCheckBoxMenuItem( 1307 1308 private final JCheckBoxMenuItem helperCb = new JCheckBoxMenuItem( 1693 1309 new AbstractAction(tr("Show helper geometry")) { 1694 @Override public void actionPerformed(ActionEvent e) { 1310 @Override 1311 public void actionPerformed(ActionEvent e) { 1695 1312 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState(); 1696 1313 Main.pref.put("draw.anglesnap.drawConstructionGeometry", sel); … … 1701 1318 } 1702 1319 }); 1703 private JCheckBoxMenuItem projectionCb = new JCheckBoxMenuItem( 1320 1321 private final JCheckBoxMenuItem projectionCb = new JCheckBoxMenuItem( 1704 1322 new AbstractAction(tr("Snap to node projections")) { 1705 @Override public void actionPerformed(ActionEvent e) { 1323 @Override 1324 public void actionPerformed(ActionEvent e) { 1706 1325 boolean sel=((JCheckBoxMenuItem) e.getSource()).getState(); 1707 1326 Main.pref.put("draw.anglesnap.projectionsnap", sel); … … 1710 1329 } 1711 1330 }); 1712 { 1331 1332 private AnglePopupMenu() { 1713 1333 helperCb.setState(Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry",true)); 1714 1334 projectionCb.setState(Main.pref.getBoolean("draw.anglesnap.projectionsnapgvff",true)); … … 1746 1366 }); 1747 1367 } 1748 }) { 1368 } 1369 1370 private boolean snapOn; // snapping is turned on 1371 1372 private boolean active; // snapping is active for current mouse position 1373 private boolean fixed; // snap angle is fixed 1374 private boolean absoluteFix; // snap angle is absolute 1375 1376 private boolean drawConstructionGeometry; 1377 private boolean showProjectedPoint; 1378 private boolean showAngle; 1379 1380 private boolean snapToProjections; 1381 1382 private EastNorth dir2; 1383 private EastNorth projected; 1384 private String labelText; 1385 private double lastAngle; 1386 1387 private double customBaseHeading=-1; // angle of base line, if not last segment) 1388 private EastNorth segmentPoint1; // remembered first point of base segment 1389 private EastNorth segmentPoint2; // remembered second point of base segment 1390 private EastNorth projectionSource; // point that we are projecting to the line 1391 1392 private double[] snapAngles; 1393 private double snapAngleTolerance; 1394 1395 private double pe,pn; // (pe,pn) - direction of snapping line 1396 private double e0,n0; // (e0,n0) - origin of snapping line 1397 1398 private final String fixFmt="%d "+tr("FIX"); 1399 private Color snapHelperColor; 1400 private Color highlightColor; 1401 1402 private Stroke normalStroke; 1403 private Stroke helperStroke; 1404 private Stroke highlightStroke; 1405 1406 private JCheckBoxMenuItem checkBox; 1407 1408 private MouseListener anglePopupListener = new PopupMenuLauncher(new AnglePopupMenu()) { 1749 1409 @Override 1750 1410 public void mouseClicked(MouseEvent e) { … … 1756 1416 } 1757 1417 }; 1418 1419 public void init() { 1420 snapOn=false; 1421 checkBox.setState(snapOn); 1422 fixed=false; absoluteFix=false; 1423 1424 Collection<String> angles = Main.pref.getCollection("draw.anglesnap.angles", 1425 Arrays.asList("0","30","45","60","90","120","135","150","180")); 1426 1427 snapAngles = new double[2*angles.size()]; 1428 int i=0; 1429 for (String s: angles) { 1430 try { 1431 snapAngles[i] = Double.parseDouble(s); i++; 1432 snapAngles[i] = 360-Double.parseDouble(s); i++; 1433 } catch (NumberFormatException e) { 1434 Main.warn("Incorrect number in draw.anglesnap.angles preferences: "+s); 1435 snapAngles[i]=0;i++; 1436 snapAngles[i]=0;i++; 1437 } 1438 } 1439 snapAngleTolerance = Main.pref.getDouble("draw.anglesnap.tolerance", 5.0); 1440 drawConstructionGeometry = Main.pref.getBoolean("draw.anglesnap.drawConstructionGeometry", true); 1441 showProjectedPoint = Main.pref.getBoolean("draw.anglesnap.drawProjectedPoint", true); 1442 snapToProjections = Main.pref.getBoolean("draw.anglesnap.projectionsnap", true); 1443 1444 showAngle = Main.pref.getBoolean("draw.anglesnap.showAngle", true); 1445 useRepeatedShortcut = Main.pref.getBoolean("draw.anglesnap.toggleOnRepeatedA", true); 1446 1447 normalStroke = rubberLineStroke; 1448 snapHelperColor = Main.pref.getColor(marktr("draw angle snap"), Color.ORANGE); 1449 1450 highlightColor = Main.pref.getColor(marktr("draw angle snap highlight"), ORANGE_TRANSPARENT); 1451 highlightStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.highlight","10")); 1452 helperStroke = GuiHelper.getCustomizedStroke(Main.pref.get("draw.anglesnap.stroke.helper","1 4")); 1453 } 1454 1455 public void saveAngles(String ... angles) { 1456 Main.pref.putCollection("draw.anglesnap.angles", Arrays.asList(angles)); 1457 } 1458 1459 public void setMenuCheckBox(JCheckBoxMenuItem checkBox) { 1460 this.checkBox = checkBox; 1461 } 1462 1463 public void drawIfNeeded(Graphics2D g2, MapView mv) { 1464 if (!snapOn || !active) 1465 return; 1466 Point p1=mv.getPoint(getCurrentBaseNode()); 1467 Point p2=mv.getPoint(dir2); 1468 Point p3=mv.getPoint(projected); 1469 GeneralPath b; 1470 if (drawConstructionGeometry) { 1471 g2.setColor(snapHelperColor); 1472 g2.setStroke(helperStroke); 1473 1474 b = new GeneralPath(); 1475 if (absoluteFix) { 1476 b.moveTo(p2.x,p2.y); 1477 b.lineTo(2*p1.x-p2.x,2*p1.y-p2.y); // bi-directional line 1478 } else { 1479 b.moveTo(p2.x,p2.y); 1480 b.lineTo(p3.x,p3.y); 1481 } 1482 g2.draw(b); 1483 } 1484 if (projectionSource != null) { 1485 g2.setColor(snapHelperColor); 1486 g2.setStroke(helperStroke); 1487 b = new GeneralPath(); 1488 b.moveTo(p3.x,p3.y); 1489 Point pp=mv.getPoint(projectionSource); 1490 b.lineTo(pp.x,pp.y); 1491 g2.draw(b); 1492 } 1493 1494 if (customBaseHeading >= 0) { 1495 g2.setColor(highlightColor); 1496 g2.setStroke(highlightStroke); 1497 b = new GeneralPath(); 1498 Point pp1=mv.getPoint(segmentPoint1); 1499 Point pp2=mv.getPoint(segmentPoint2); 1500 b.moveTo(pp1.x,pp1.y); 1501 b.lineTo(pp2.x,pp2.y); 1502 g2.draw(b); 1503 } 1504 1505 g2.setColor(rubberLineColor); 1506 g2.setStroke(normalStroke); 1507 b = new GeneralPath(); 1508 b.moveTo(p1.x,p1.y); 1509 b.lineTo(p3.x,p3.y); 1510 g2.draw(b); 1511 1512 g2.drawString(labelText, p3.x-5, p3.y+20); 1513 if (showProjectedPoint) { 1514 g2.setStroke(normalStroke); 1515 g2.drawOval(p3.x-5, p3.y-5, 10, 10); // projected point 1516 } 1517 1518 g2.setColor(snapHelperColor); 1519 g2.setStroke(helperStroke); 1520 } 1521 1522 /* If mouse position is close to line at 15-30-45-... angle, remembers this direction 1523 */ 1524 public void checkAngleSnapping(EastNorth currentEN, double baseHeading, double curHeading) { 1525 EastNorth p0 = getCurrentBaseNode().getEastNorth(); 1526 EastNorth snapPoint = currentEN; 1527 double angle = -1; 1528 1529 double activeBaseHeading = (customBaseHeading>=0)? customBaseHeading : baseHeading; 1530 1531 if (snapOn && (activeBaseHeading>=0)) { 1532 angle = curHeading - activeBaseHeading; 1533 if (angle < 0) { 1534 angle+=360; 1535 } 1536 if (angle > 360) { 1537 angle=0; 1538 } 1539 1540 double nearestAngle; 1541 if (fixed) { 1542 nearestAngle = lastAngle; // if direction is fixed use previous angle 1543 active = true; 1544 } else { 1545 nearestAngle = getNearestAngle(angle); 1546 if (getAngleDelta(nearestAngle, angle) < snapAngleTolerance) { 1547 active = (customBaseHeading>=0)? true : Math.abs(nearestAngle - 180) > 1e-3; 1548 // if angle is to previous segment, exclude 180 degrees 1549 lastAngle = nearestAngle; 1550 } else { 1551 active=false; 1552 } 1553 } 1554 1555 if (active) { 1556 double phi; 1557 e0 = p0.east(); 1558 n0 = p0.north(); 1559 buildLabelText((nearestAngle<=180) ? nearestAngle : nearestAngle-360); 1560 1561 phi = (nearestAngle + activeBaseHeading) * Math.PI / 180; 1562 // (pe,pn) - direction of snapping line 1563 pe = Math.sin(phi); 1564 pn = Math.cos(phi); 1565 double scale = 20 * Main.map.mapView.getDist100Pixel(); 1566 dir2 = new EastNorth(e0 + scale * pe, n0 + scale * pn); 1567 snapPoint = getSnapPoint(currentEN); 1568 } else { 1569 noSnapNow(); 1570 } 1571 } 1572 1573 // find out the distance, in metres, between the base point and projected point 1574 LatLon mouseLatLon = Main.map.mapView.getProjection().eastNorth2latlon(snapPoint); 1575 double distance = getCurrentBaseNode().getCoor().greatCircleDistance(mouseLatLon); 1576 double hdg = Math.toDegrees(p0.heading(snapPoint)); 1577 // heading of segment from current to calculated point, not to mouse position 1578 1579 if (baseHeading >= 0) { // there is previous line segment with some heading 1580 angle = hdg - baseHeading; 1581 if (angle < 0) { 1582 angle+=360; 1583 } 1584 if (angle > 360) { 1585 angle=0; 1586 } 1587 } 1588 showStatusInfo(angle, hdg, distance, isSnapOn()); 1589 } 1590 1591 private void buildLabelText(double nearestAngle) { 1592 if (showAngle) { 1593 if (fixed) { 1594 if (absoluteFix) { 1595 labelText = "="; 1596 } else { 1597 labelText = String.format(fixFmt, (int) nearestAngle); 1598 } 1599 } else { 1600 labelText = String.format("%d", (int) nearestAngle); 1601 } 1602 } else { 1603 if (fixed) { 1604 if (absoluteFix) { 1605 labelText = "="; 1606 } else { 1607 labelText = String.format(tr("FIX"), 0); 1608 } 1609 } else { 1610 labelText = ""; 1611 } 1612 } 1613 } 1614 1615 public EastNorth getSnapPoint(EastNorth p) { 1616 if (!active) 1617 return p; 1618 double de=p.east()-e0; 1619 double dn=p.north()-n0; 1620 double l = de*pe+dn*pn; 1621 double delta = Main.map.mapView.getDist100Pixel()/20; 1622 if (!absoluteFix && l<delta) { 1623 active=false; 1624 return p; 1625 } // do not go backward! 1626 1627 projectionSource=null; 1628 if (snapToProjections) { 1629 DataSet ds = getCurrentDataSet(); 1630 Collection<Way> selectedWays = ds.getSelectedWays(); 1631 if (selectedWays.size()==1) { 1632 Way w = selectedWays.iterator().next(); 1633 Collection<EastNorth> pointsToProject = new ArrayList<>(); 1634 if (w.getNodesCount()<1000) { 1635 for (Node n: w.getNodes()) { 1636 pointsToProject.add(n.getEastNorth()); 1637 } 1638 } 1639 if (customBaseHeading >= 0) { 1640 pointsToProject.add(segmentPoint1); 1641 pointsToProject.add(segmentPoint2); 1642 } 1643 EastNorth enOpt=null; 1644 double dOpt=1e5; 1645 for (EastNorth en: pointsToProject) { // searching for besht projection 1646 double l1 = (en.east()-e0)*pe+(en.north()-n0)*pn; 1647 double d1 = Math.abs(l1-l); 1648 if (d1 < delta && d1 < dOpt) { 1649 l=l1; 1650 enOpt = en; 1651 dOpt = d1; 1652 } 1653 } 1654 if (enOpt!=null) { 1655 projectionSource = enOpt; 1656 } 1657 } 1658 } 1659 return projected = new EastNorth(e0+l*pe, n0+l*pn); 1660 } 1661 1662 public void noSnapNow() { 1663 active=false; 1664 dir2=null; projected=null; 1665 labelText=null; 1666 } 1667 1668 public void setBaseSegment(WaySegment seg) { 1669 if (seg==null) return; 1670 segmentPoint1=seg.getFirstNode().getEastNorth(); 1671 segmentPoint2=seg.getSecondNode().getEastNorth(); 1672 1673 double hdg = segmentPoint1.heading(segmentPoint2); 1674 hdg=Math.toDegrees(hdg); 1675 if (hdg<0) { 1676 hdg+=360; 1677 } 1678 if (hdg>360) { 1679 hdg-=360; 1680 } 1681 customBaseHeading=hdg; 1682 } 1683 1684 private void nextSnapMode() { 1685 if (snapOn) { 1686 // turn off snapping if we are in fixed mode or no actile snapping line exist 1687 if (fixed || !active) { 1688 snapOn = false; 1689 unsetFixedMode(); 1690 } else { 1691 setFixedMode(); 1692 } 1693 } else { 1694 snapOn=true; 1695 unsetFixedMode(); 1696 } 1697 checkBox.setState(snapOn); 1698 customBaseHeading=-1; 1699 } 1700 1701 private void enableSnapping() { 1702 snapOn = true; 1703 checkBox.setState(snapOn); 1704 customBaseHeading=-1; 1705 unsetFixedMode(); 1706 } 1707 1708 private void toggleSnapping() { 1709 snapOn = !snapOn; 1710 checkBox.setState(snapOn); 1711 customBaseHeading=-1; 1712 unsetFixedMode(); 1713 } 1714 1715 public void setFixedMode() { 1716 if (active) { 1717 fixed=true; 1718 } 1719 } 1720 1721 public void unsetFixedMode() { 1722 fixed=false; 1723 absoluteFix=false; 1724 lastAngle=0; 1725 active=false; 1726 } 1727 1728 public boolean isActive() { 1729 return active; 1730 } 1731 1732 public boolean isSnapOn() { 1733 return snapOn; 1734 } 1735 1736 private double getNearestAngle(double angle) { 1737 double delta,minDelta=1e5, bestAngle=0.0; 1738 for (double snapAngle : snapAngles) { 1739 delta = getAngleDelta(angle, snapAngle); 1740 if (delta < minDelta) { 1741 minDelta = delta; 1742 bestAngle = snapAngle; 1743 } 1744 } 1745 if (Math.abs(bestAngle-360) < 1e-3) { 1746 bestAngle=0; 1747 } 1748 return bestAngle; 1749 } 1750 1751 private double getAngleDelta(double a, double b) { 1752 double delta = Math.abs(a-b); 1753 if (delta>180) 1754 return 360-delta; 1755 else 1756 return delta; 1757 } 1758 1759 private void unFixOrTurnOff() { 1760 if (absoluteFix) { 1761 unsetFixedMode(); 1762 } else { 1763 toggleSnapping(); 1764 } 1765 } 1758 1766 } 1759 1767 1760 1768 private class SnapChangeAction extends JosmAction { 1769 /** 1770 * Constructs a new {@code SnapChangeAction}. 1771 */ 1761 1772 public SnapChangeAction() { 1762 1773 super(tr("Angle snapping"), /* ICON() */ "anglesnap", -
trunk/src/org/openstreetmap/josm/actions/mapmode/ExtrudeAction.java
r8470 r8509 174 174 /** {@code true}, if dual alignment mode is enabled. User wants following extrude to be dual aligned. */ 175 175 private boolean dualAlignEnabled; 176 /** {@code true}, if dual alignment is active. User is dragging the mouse, required conditions are met. Treat {@link #mode} (extrude/translate/create_new) as dual aligned. */ 176 /** {@code true}, if dual alignment is active. User is dragging the mouse, required conditions are met. 177 * Treat {@link #mode} (extrude/translate/create_new) as dual aligned. */ 177 178 private boolean dualAlignActive; 178 179 /** Dual alignment reference segments */ … … 622 623 Node prevNode = getPreviousNode(selectedSegment.lowerIndex); 623 624 boolean nodeOverlapsSegment = prevNode != null && Geometry.segmentsParallel(initialN1en, prevNode.getEastNorth(), initialN1en, newN1en); 624 // segmentAngleZero marks subset of nodeOverlapsSegment. nodeOverlapsSegment is true if angle between segments is 0 or PI, segmentAngleZero only if angle is 0 625 // segmentAngleZero marks subset of nodeOverlapsSegment. 626 // nodeOverlapsSegment is true if angle between segments is 0 or PI, segmentAngleZero only if angle is 0 625 627 boolean segmentAngleZero = prevNode != null && Math.abs(Geometry.getCornerAngle(prevNode.getEastNorth(), initialN1en, newN1en)) < 1e-5; 626 628 boolean hasOtherWays = hasNodeOtherWays(selectedSegment.getFirstNode(), selectedSegment.way); … … 927 929 if (newN1en == null || newN2en == null) return bestMovement; 928 930 if (keepSegmentDirection && isOppositeDirection(newN1en, newN2en, initialN1en, initialN2en)) { 929 EastNorth collapsedSegmentPosition = Geometry.getLineLineIntersection(dualAlignSegment1.p1, dualAlignSegment1.p2, dualAlignSegment2.p1, dualAlignSegment2.p2); 931 EastNorth collapsedSegmentPosition = Geometry.getLineLineIntersection(dualAlignSegment1.p1, dualAlignSegment1.p2, 932 dualAlignSegment2.p1, dualAlignSegment2.p2); 930 933 newN1en = collapsedSegmentPosition; 931 934 newN2en = collapsedSegmentPosition; … … 1172 1175 // Graphics2D calls 'user space'. Essentially a manhattan distance of manhattan distances. 1173 1176 // This can be used as a safe length of line to generate which will always go off-viewport. 1174 double linelength = Math.abs(widthpoint.getX()) + Math.abs(widthpoint.getY()) + Math.abs(heightpoint.getX()) + Math.abs(heightpoint.getY()); 1175 1176 return new Line2D.Double(start, new Point2D.Double(start.getX() + (unitvector.getX() * linelength) , start.getY() + (unitvector.getY() * linelength))); 1177 double linelength = Math.abs(widthpoint.getX()) + Math.abs(widthpoint.getY()) 1178 + Math.abs(heightpoint.getX()) + Math.abs(heightpoint.getY()); 1179 1180 return new Line2D.Double(start, new Point2D.Double(start.getX() + (unitvector.getX() * linelength) , start.getY() 1181 + (unitvector.getY() * linelength))); 1177 1182 } catch (NoninvertibleTransformException e) { 1178 return new Line2D.Double(start, new Point2D.Double(start.getX() + (unitvector.getX() * 10) , start.getY() + (unitvector.getY() * 10))); 1183 return new Line2D.Double(start, new Point2D.Double(start.getX() + (unitvector.getX() * 10) , start.getY() 1184 + (unitvector.getY() * 10))); 1179 1185 } 1180 1186 } -
trunk/src/org/openstreetmap/josm/actions/mapmode/ParallelWays.java
r8459 r8509 89 89 } 90 90 91 // Ugly method of ensuring that the offset isn't inverted. I'm sure there is a better and more elegant way , but I'm starting to get sleepy, so I do this for now.91 // Ugly method of ensuring that the offset isn't inverted. I'm sure there is a better and more elegant way 92 92 Way refWay = ways.get(refWayIndex); 93 93 boolean refWayReversed = true; -
trunk/src/org/openstreetmap/josm/actions/relation/SelectMembersAction.java
r8338 r8509 23 23 /** 24 24 * Constructs a new <code>SelectMembersAction</code>. 25 * @param add if <code>true</code>, the members will be added to current selection. If <code>false</code>, the members will replace the current selection. 25 * @param add if <code>true</code>, the members will be added to current selection. 26 * If <code>false</code>, the members will replace the current selection. 26 27 */ 27 28 public SelectMembersAction(boolean add) { -
trunk/src/org/openstreetmap/josm/actions/relation/SelectRelationAction.java
r7937 r8509 20 20 /** 21 21 * Constructs a new <code>SelectRelationAction</code>. 22 * @param add if <code>true</code>, the relation will be added to current selection. If <code>false</code>, the relation will replace the current selection. 22 * @param add if <code>true</code>, the relation will be added to current selection. 23 * If <code>false</code>, the relation will replace the current selection. 23 24 */ 24 25 public SelectRelationAction(boolean add) { 25 putValue(SHORT_DESCRIPTION, add ? tr("Add the selected relations to the current selection") : tr("Set the current selection to the list of selected relations")); 26 putValue(SHORT_DESCRIPTION, add ? tr("Add the selected relations to the current selection") : 27 tr("Set the current selection to the list of selected relations")); 26 28 putValue(SMALL_ICON, ImageProvider.get("dialogs", "select")); 27 29 putValue(NAME, add ? tr("Select relation (add)") : tr("Select relation")); -
trunk/src/org/openstreetmap/josm/actions/search/SearchAction.java
r8470 r8509 322 322 new ToolbarPreferences.ActionDefinition(Main.main.menu.search); 323 323 aDef.getParameters().put(SEARCH_EXPRESSION, initialValues); 324 aDef.setName(Utils.shortenString(initialValues.text, MAX_LENGTH_SEARCH_EXPRESSION_DISPLAY)); // Display search expression as tooltip instead of generic one 324 // Display search expression as tooltip instead of generic one 325 aDef.setName(Utils.shortenString(initialValues.text, MAX_LENGTH_SEARCH_EXPRESSION_DISPLAY)); 325 326 // parametrized action definition is now composed 326 327 ActionParser actionParser = new ToolbarPreferences.ActionParser(null); … … 348 349 .addKeyword("<i>key</i>=", null, tr("matches if ''key'' exists")) 349 350 .addKeyword("<i>key</i>><i>value</i>", null, tr("matches if ''key'' is greater than ''value'' (analogously, less than)")) 350 .addKeyword("\"key\"=\"value\"", "\"\"=\"\"", tr("to quote operators.<br>Within quoted strings the <b>\"</b> and <b>\\</b> characters need to be escaped by a preceding <b>\\</b> (e.g. <b>\\\"</b> and <b>\\\\</b>)."), "\"addr:street\"") 351 .addKeyword("\"key\"=\"value\"", "\"\"=\"\"", 352 tr("to quote operators.<br>Within quoted strings the <b>\"</b> and <b>\\</b> characters need to be escaped by a preceding <b>\\</b> (e.g. <b>\\\"</b> and <b>\\\\</b>)."), 353 "\"addr:street\"") 351 354 , GBC.eol()); 352 355 right.add(new SearchKeywordRow(hcbSearchString) … … 373 376 .addKeyword("id:", "id:", tr("objects with given ID"), "id:0 (new objects)") 374 377 .addKeyword("version:", "version:", tr("objects with given version"), "version:0 (objects without an assigned version)") 375 .addKeyword("changeset:", "changeset:", tr("objects with given changeset ID"), "changeset:0 (objects without an assigned changeset)") 376 .addKeyword("timestamp:", "timestamp:", tr("objects with last modification timestamp within range"), "timestamp:2012/", "timestamp:2008/2011-02-04T12") 378 .addKeyword("changeset:", "changeset:", tr("objects with given changeset ID"), 379 "changeset:0 (objects without an assigned changeset)") 380 .addKeyword("timestamp:", "timestamp:", tr("objects with last modification timestamp within range"), "timestamp:2012/", 381 "timestamp:2008/2011-02-04T12") 377 382 , GBC.eol()); 378 383 right.add(new SearchKeywordRow(hcbSearchString) … … 404 409 .addKeyword("allinview", "allinview ", tr("objects (and all its way nodes / relation members) in current view")) 405 410 .addKeyword("indownloadedarea", "indownloadedarea ", tr("objects in downloaded area")) 406 .addKeyword("allindownloadedarea", "allindownloadedarea ", tr("objects (and all its way nodes / relation members) in downloaded area")) 411 .addKeyword("allindownloadedarea", "allindownloadedarea ", 412 tr("objects (and all its way nodes / relation members) in downloaded area")) 407 413 , GBC.eol()); 408 414 } -
trunk/src/org/openstreetmap/josm/command/ChangePropertyCommand.java
r8456 r8509 166 166 } else { 167 167 /* I18n: plural form for objects, but value < 2 not possible! */ 168 text = trn("Set {0}={1} for {2} object", "Set {0}={1} for {2} objects", objects.size(), entry.getKey(), entry.getValue(), objects.size()); 168 text = trn("Set {0}={1} for {2} object", "Set {0}={1} for {2} objects", 169 objects.size(), entry.getKey(), entry.getValue(), objects.size()); 169 170 } 170 171 } else { -
trunk/src/org/openstreetmap/josm/command/PurgeCommand.java
r8456 r8509 124 124 if (data != null) { 125 125 if (ds.getPrimitiveById(osm) != osm) 126 throw new AssertionError(String.format("Primitive %s has been made incomplete when purging, but it cannot be found on undo.", osm)); 126 throw new AssertionError( 127 String.format("Primitive %s has been made incomplete when purging, but it cannot be found on undo.", osm)); 127 128 osm.load(data); 128 129 } else { -
trunk/src/org/openstreetmap/josm/command/conflict/TagConflictResolveCommand.java
r8456 r8509 58 58 case NODE: 59 59 /* for correct i18n of plural forms - see #9110 */ 60 return trn("Resolve {0} tag conflict in node {1}", "Resolve {0} tag conflicts in node {1}", getNumDecidedConflicts(), getNumDecidedConflicts(), conflict.getMy().getId()); 60 return trn("Resolve {0} tag conflict in node {1}", "Resolve {0} tag conflicts in node {1}", 61 getNumDecidedConflicts(), getNumDecidedConflicts(), conflict.getMy().getId()); 61 62 case WAY: 62 63 /* for correct i18n of plural forms - see #9110 */ 63 return trn("Resolve {0} tag conflict in way {1}", "Resolve {0} tag conflicts in way {1}", getNumDecidedConflicts(), getNumDecidedConflicts(), conflict.getMy().getId()); 64 return trn("Resolve {0} tag conflict in way {1}", "Resolve {0} tag conflicts in way {1}", 65 getNumDecidedConflicts(), getNumDecidedConflicts(), conflict.getMy().getId()); 64 66 case RELATION: 65 67 /* for correct i18n of plural forms - see #9110 */ 66 return trn("Resolve {0} tag conflict in relation {1}", "Resolve {0} tag conflicts in relation {1}", getNumDecidedConflicts(), getNumDecidedConflicts(), conflict.getMy().getId()); 68 return trn("Resolve {0} tag conflict in relation {1}", "Resolve {0} tag conflicts in relation {1}", 69 getNumDecidedConflicts(), getNumDecidedConflicts(), conflict.getMy().getId()); 67 70 } 68 71 return ""; -
trunk/src/org/openstreetmap/josm/corrector/TagCorrector.java
r8426 r8509 180 180 RoleCorrection roleCorrection = roleCorrections.get(i); 181 181 if (roleTableMap.get(primitive).getCorrectionTableModel().getApply(i)) { 182 commands.add(new ChangeRelationMemberRoleCommand(roleCorrection.relation, roleCorrection.position, roleCorrection.newRole)); 182 commands.add(new ChangeRelationMemberRoleCommand( 183 roleCorrection.relation, roleCorrection.position, roleCorrection.newRole)); 183 184 } 184 185 } -
trunk/src/org/openstreetmap/josm/data/Bounds.java
r8443 r8509 176 176 String[] components = asString.split(separator); 177 177 if (components.length != 4) 178 throw new IllegalArgumentException(MessageFormat.format("Exactly four doubles expected in string, got {0}: {1}", components.length, asString)); 178 throw new IllegalArgumentException( 179 MessageFormat.format("Exactly four doubles expected in string, got {0}: {1}", components.length, asString)); 179 180 double[] values = new double[4]; 180 181 for (int i=0; i<4; i++) { -
trunk/src/org/openstreetmap/josm/data/CustomConfigurator.java
r8470 r8509 180 180 if (!opts.isEmpty()) { 181 181 String[] options = opts.split(";"); 182 answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0); 182 answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", 183 JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, 0); 183 184 } else { 184 answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, 2); 185 answer = JOptionPane.showOptionDialog(Main.parent, text, "Question", 186 JOptionPane.YES_NO_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, 2); 185 187 } 186 188 if (answer==null) return -1; else return answer; … … 229 231 * Export specified preferences keys to configuration file 230 232 * @param filename - name of file 231 * @param append - will the preferences be appended to existing ones when file is imported later. Elsewhere preferences from file will replace existing keys. 233 * @param append - will the preferences be appended to existing ones when file is imported later. 234 * Elsewhere preferences from file will replace existing keys. 232 235 * @param keys - collection of preferences key names to save 233 236 */ … … 1042 1045 * @throws ScriptException if the evaluation fails 1043 1046 */ 1044 public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults) throws ScriptException { 1047 public static void loadPrefsToJS(ScriptEngine engine, Preferences tmpPref, String whereToPutInJS, boolean includeDefaults) 1048 throws ScriptException { 1045 1049 Map<String, String> stringMap = new TreeMap<>(); 1046 1050 Map<String, List<String>> listMap = new TreeMap<>(); -
trunk/src/org/openstreetmap/josm/data/Preferences.java
r8471 r8509 871 871 if (prefDir.exists()) { 872 872 if(!prefDir.isDirectory()) { 873 Main.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.", prefDir.getAbsoluteFile())); 873 Main.warn(tr("Failed to initialize preferences. Preference directory ''{0}'' is not a directory.", 874 prefDir.getAbsoluteFile())); 874 875 JOptionPane.showMessageDialog( 875 876 Main.parent, 876 tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>", prefDir.getAbsoluteFile()), 877 tr("<html>Failed to initialize preferences.<br>Preference directory ''{0}'' is not a directory.</html>", 878 prefDir.getAbsoluteFile()), 877 879 tr("Error"), 878 880 JOptionPane.ERROR_MESSAGE … … 882 884 } else { 883 885 if (!prefDir.mkdirs()) { 884 Main.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}", prefDir.getAbsoluteFile())); 886 Main.warn(tr("Failed to initialize preferences. Failed to create missing preference directory: {0}", 887 prefDir.getAbsoluteFile())); 885 888 JOptionPane.showMessageDialog( 886 889 Main.parent, 887 tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>",prefDir.getAbsoluteFile()), 890 tr("<html>Failed to initialize preferences.<br>Failed to create missing preference directory: {0}</html>", 891 prefDir.getAbsoluteFile()), 888 892 tr("Error"), 889 893 JOptionPane.ERROR_MESSAGE … … 908 912 JOptionPane.showMessageDialog( 909 913 Main.parent, 910 tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>",getPreferenceFile().getAbsoluteFile()), 914 tr("<html>Failed to initialize preferences.<br>Failed to reset preference file to default: {0}</html>", 915 getPreferenceFile().getAbsoluteFile()), 911 916 tr("Error"), 912 917 JOptionPane.ERROR_MESSAGE … … 921 926 JOptionPane.showMessageDialog( 922 927 Main.parent, 923 tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> and creating a new default preference file.</html>", backupFile.getAbsoluteFile()), 928 tr("<html>Preferences file had errors.<br> Making backup of old one to <br>{0}<br> and creating a new default preference file.</html>", 929 backupFile.getAbsoluteFile()), 924 930 tr("Error"), 925 931 JOptionPane.ERROR_MESSAGE … … 1646 1652 1647 1653 protected void throwException(String msg) { 1648 throw new RuntimeException(msg + tr(" (at line {0}, column {1})", parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber())); 1654 throw new RuntimeException(msg + tr(" (at line {0}, column {1})", 1655 parser.getLocation().getLineNumber(), parser.getLocation().getColumnNumber())); 1649 1656 } 1650 1657 … … 1711 1718 b.append(" <map>\n"); 1712 1719 for (Entry<String, String> e : struct.entrySet()) { 1713 b.append(" <tag key='").append(XmlWriter.encode(e.getKey())).append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n"); 1720 b.append(" <tag key='").append(XmlWriter.encode(e.getKey())) 1721 .append("' value='").append(XmlWriter.encode(e.getValue())).append("'/>\n"); 1714 1722 } 1715 1723 b.append(" </map>\n"); -
trunk/src/org/openstreetmap/josm/data/cache/JCSCacheManager.java
r8487 r8509 73 73 jcsLog.setLevel(Level.INFO); 74 74 jcsLog.setUseParentHandlers(false); 75 //Logger.getLogger("org.apache.common").setUseParentHandlers(false); 76 // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level 75 // we need a separate handler from Main's, as we downgrade LEVEL.INFO to DEBUG level 77 76 jcsLog.addHandler(new Handler() { 78 77 @Override … … 100 99 }); 101 100 102 103 CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance();104 101 // this could be moved to external file 105 102 Properties props = new Properties(); 106 103 // these are default common to all cache regions 107 104 // use of auxiliary cache and sizing of the caches is done with giving proper geCache(...) params 108 props.setProperty("jcs.default.cacheattributes", org.apache.commons.jcs.engine.CompositeCacheAttributes.class.getCanonicalName()); 109 props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString()); 110 props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true"); 111 props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put 112 props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName()); 113 props.setProperty("jcs.default.elementattributes.IsEternal", "false"); 114 props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL)); 115 props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL)); 116 props.setProperty("jcs.default.elementattributes.IsSpool", "true"); 105 props.setProperty("jcs.default.cacheattributes", CompositeCacheAttributes.class.getCanonicalName()); 106 props.setProperty("jcs.default.cacheattributes.MaxObjects", DEFAULT_MAX_OBJECTS_IN_MEMORY.get().toString()); 107 props.setProperty("jcs.default.cacheattributes.UseMemoryShrinker", "true"); 108 props.setProperty("jcs.default.cacheattributes.DiskUsagePatternName", "UPDATE"); // store elements on disk on put 109 props.setProperty("jcs.default.elementattributes", CacheEntryAttributes.class.getCanonicalName()); 110 props.setProperty("jcs.default.elementattributes.IsEternal", "false"); 111 props.setProperty("jcs.default.elementattributes.MaxLife", Long.toString(maxObjectTTL)); 112 props.setProperty("jcs.default.elementattributes.IdleTime", Long.toString(maxObjectTTL)); 113 props.setProperty("jcs.default.elementattributes.IsSpool", "true"); 114 CompositeCacheManager cm = CompositeCacheManager.getUnconfiguredInstance(); 117 115 cm.configure(props); 118 116 cacheManager = cm; 119 120 117 } 121 118 -
trunk/src/org/openstreetmap/josm/data/cache/JCSCachedTileLoaderJob.java
r8485 r8509 288 288 expires = Math.min(expires, attributes.getCreateTime() + EXPIRE_TIME_SERVER_LIMIT); 289 289 if (now > expires) { 290 log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}", new Object[]{getUrl(), Long.toString(expires), Long.toString(now)}); 290 log.log(Level.FINE, "JCS - Object {0} has expired -> valid to {1}, now is: {2}", 291 new Object[]{getUrl(), Long.toString(expires), Long.toString(now)}); 291 292 return false; 292 293 } -
trunk/src/org/openstreetmap/josm/data/imagery/Shape.java
r8415 r8509 27 27 String[] components = asString.split(separator); 28 28 if (components.length % 2 != 0) 29 throw new IllegalArgumentException(MessageFormat.format("Even number of doubles expected in string, got {0}: {1}", components.length, asString)); 29 throw new IllegalArgumentException(MessageFormat.format("Even number of doubles expected in string, got {0}: {1}", 30 components.length, asString)); 30 31 for (int i=0; i<components.length; i+=2) { 31 32 addPoint(components[i], components[i+1]); -
trunk/src/org/openstreetmap/josm/data/imagery/TMSCachedTileLoader.java
r8459 r8509 80 80 * @throws IOException when cache initialization fails 81 81 */ 82 public TMSCachedTileLoader(TileLoaderListener listener, String name, int connectTimeout, int readTimeout, Map<String, String> headers, String cacheDir) throws IOException { 82 public TMSCachedTileLoader(TileLoaderListener listener, String name, int connectTimeout, int readTimeout, 83 Map<String, String> headers, String cacheDir) throws IOException { 83 84 this.cache = JCSCacheManager.getCache(name, 84 85 200, // use fairly small memory cache, as cached objects are quite big, as they contain BufferedImages -
trunk/src/org/openstreetmap/josm/data/imagery/WmsCache.java
r8470 r8509 98 98 private int totalFileSize; 99 99 private boolean totalFileSizeDirty; // Some file was missing - size needs to be recalculated 100 // No need for hashCode/equals on CacheEntry, object identity is enough. Comparing by values can lead to error - CacheEntry for wrong projection could be found 100 // No need for hashCode/equals on CacheEntry, object identity is enough. 101 // Comparing by values can lead to error - CacheEntry for wrong projection could be found 101 102 private Map<CacheEntry, SoftReference<BufferedImage>> memoryCache = new HashMap<>(); 102 103 private Set<ProjectionBounds> areaToCache; … … 458 459 } 459 460 460 private String generateFileName(ProjectionEntries projectionEntries, double pixelPerDegree, Projection projection, double east, double north, String mimeType) { 461 private String generateFileName(ProjectionEntries projectionEntries, double pixelPerDegree, Projection projection, 462 double east, double north, String mimeType) { 461 463 LatLon ll1 = projection.eastNorth2latlon(new EastNorth(east, north)); 462 464 LatLon ll2 = projection.eastNorth2latlon(new EastNorth(east + 100 / pixelPerDegree, north)); … … 490 492 FILENAME_LOOP: 491 493 while (true) { 492 String result = String.format("%s_%." + precisionLat + "f_%." + precisionLon +"f%s.%s", zoom, ll1.lat(), ll1.lon(), counter==0?"":"_" + counter, extension); 494 String result = String.format("%s_%." + precisionLat + "f_%." + precisionLon +"f%s.%s", 495 zoom, ll1.lat(), ll1.lon(), counter==0?"":"_" + counter, extension); 493 496 for (CacheEntry entry: projectionEntries.entries) { 494 497 if (entry.filename.equals(result)) { … … 511 514 * @throws IOException if any I/O error occurs 512 515 */ 513 public synchronized void saveToCache(BufferedImage img, InputStream imageData, Projection projection, double pixelPerDegree, double east, double north)514 throws IOException {516 public synchronized void saveToCache(BufferedImage img, InputStream imageData, Projection projection, double pixelPerDegree, 517 double east, double north) throws IOException { 515 518 ProjectionEntries projectionEntries = getProjectionEntries(projection); 516 519 CacheEntry entry = findEntry(projectionEntries, pixelPerDegree, east, north); -
trunk/src/org/openstreetmap/josm/data/osm/DataSetMerger.java
r8444 r8509 268 268 OsmPrimitive targetMember = getMergeTarget(sourceMember.getMember()); 269 269 if (targetMember == null) 270 throw new IllegalStateException(tr("Missing merge target of type {0} with id {1}", sourceMember.getType(), sourceMember.getUniqueId())); 270 throw new IllegalStateException(tr("Missing merge target of type {0} with id {1}", 271 sourceMember.getType(), sourceMember.getUniqueId())); 271 272 RelationMember newMember = new RelationMember(sourceMember.getRole(), targetMember); 272 273 newMembers.add(newMember); … … 312 313 // take. We take target. 313 314 // 314 } else if (!target.isModified() && !source.isModified() && target.isVisible() != source.isVisible() && target.getVersion() == source.getVersion()) 315 } else if (!target.isModified() && !source.isModified() && target.isVisible() != source.isVisible() 316 && target.getVersion() == source.getVersion()) 315 317 // Same version, but different "visible" attribute and neither of them are modified. 316 318 // It indicates a serious problem in datasets. -
trunk/src/org/openstreetmap/josm/data/osm/MultipolygonBuilder.java
r8449 r8509 369 369 } 370 370 371 private static List<PolygonLevel> processOuterWay(int level, List<JoinedPolygon> boundaryWays, final List<PolygonLevel> result, JoinedPolygon outerWay) { 371 private static List<PolygonLevel> processOuterWay(int level, List<JoinedPolygon> boundaryWays, 372 final List<PolygonLevel> result, JoinedPolygon outerWay) { 372 373 Pair<Boolean, List<JoinedPolygon>> p = findInnerWaysCandidates(outerWay, boundaryWays); 373 374 if (p == null) { -
trunk/src/org/openstreetmap/josm/data/osm/Node.java
r8444 r8509 164 164 * Constructs an identical clone of the argument. 165 165 * @param clone The node to clone 166 * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. If {@code false}, does nothing 166 * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. 167 * If {@code false}, does nothing 167 168 */ 168 169 public Node(Node clone, boolean clearMetadata) { -
trunk/src/org/openstreetmap/josm/data/osm/OsmPrimitive.java
r8470 r8509 345 345 protected void writeUnlock(boolean locked) { 346 346 if (locked) { 347 // It shouldn't be possible for dataset to become null because method calling setDataset would need write lock which is owned by this thread 347 // It shouldn't be possible for dataset to become null because 348 // method calling setDataset would need write lock which is owned by this thread 348 349 dataSet.endUpdate(); 349 350 } … … 1141 1142 CheckParameterUtil.ensureParameterNotNull(other, "other"); 1142 1143 if (other.isNew() ^ isNew()) 1143 throw new DataIntegrityProblemException(tr("Cannot merge because either of the participating primitives is new and the other is not")); 1144 throw new DataIntegrityProblemException( 1145 tr("Cannot merge because either of the participating primitives is new and the other is not")); 1144 1146 if (!other.isNew() && other.getId() != id) 1145 throw new DataIntegrityProblemException(tr("Cannot merge primitives with different ids. This id is {0}, the other is {1}", id, other.getId())); 1147 throw new DataIntegrityProblemException( 1148 tr("Cannot merge primitives with different ids. This id is {0}, the other is {1}", id, other.getId())); 1146 1149 1147 1150 setKeys(other.getKeys()); -
trunk/src/org/openstreetmap/josm/data/osm/Relation.java
r8470 r8509 187 187 * Constructs an identical clone of the argument. 188 188 * @param clone The relation to clone 189 * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. If {@code false}, does nothing 189 * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. 190 * If {@code false}, does nothing 190 191 */ 191 192 public Relation(Relation clone, boolean clearMetadata) { … … 490 491 for (RelationMember rm: members) { 491 492 if (rm.getMember().getDataSet() != dataSet) 492 throw new DataIntegrityProblemException(String.format("Relation member must be part of the same dataset as relation(%s, %s)", getPrimitiveId(), rm.getMember().getPrimitiveId())); 493 throw new DataIntegrityProblemException( 494 String.format("Relation member must be part of the same dataset as relation(%s, %s)", 495 getPrimitiveId(), rm.getMember().getPrimitiveId())); 493 496 } 494 497 if (Main.pref.getBoolean("debug.checkDeleteReferenced", true)) { -
trunk/src/org/openstreetmap/josm/data/osm/Way.java
r8460 r8509 187 187 * Replies the ordered {@link List} of chunks of this way. Each chunk is replied as a {@link Pair} of {@link Node nodes}. 188 188 * @param sort If true, the nodes of each pair are sorted as defined by {@link Pair#sort}. 189 * If false, Pair.a and Pair.b are in the way order (i.e for a given Pair(n), Pair(n-1).b == Pair(n).a, Pair(n).b == Pair(n+1).a, etc.) 189 * If false, Pair.a and Pair.b are in the way order 190 * (i.e for a given Pair(n), Pair(n-1).b == Pair(n).a, Pair(n).b == Pair(n+1).a, etc.) 190 191 * @return The ordered list of chunks of this way. 191 192 * @since 3348 … … 234 235 * Contructs a new {@code Way} from an existing {@code Way}. 235 236 * @param original The original {@code Way} to be identically cloned. Must not be null 236 * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. If {@code false}, does nothing 237 * @param clearMetadata If {@code true}, clears the OSM id and other metadata as defined by {@link #clearOsmMetadata}. 238 * If {@code false}, does nothing 237 239 * @since 2410 238 240 */ … … 597 599 if (n.isDeleted()) 598 600 throw new DataIntegrityProblemException("Deleted node referenced: " + toString(), 599 "<html>" + tr("Deleted node referenced by {0}", DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(this)) + "</html>"); 601 "<html>" + tr("Deleted node referenced by {0}", 602 DefaultNameFormatter.getInstance().formatAsHtmlUnorderedList(this)) + "</html>"); 600 603 } 601 604 if (Main.pref.getBoolean("debug.checkNullCoor", true)) { -
trunk/src/org/openstreetmap/josm/data/osm/event/DatasetEventManager.java
r8285 r8509 29 29 private static final DatasetEventManager instance = new DatasetEventManager(); 30 30 31 public enum FireMode { 32 /** 33 * Fire in calling thread immediately. 34 */ 35 IMMEDIATELY, 36 /** 37 * Fire in event dispatch thread. 38 */ 39 IN_EDT, 40 /** 41 * Fire in event dispatch thread. If more than one event arrived when event queue is checked, merged them to 42 * one event 43 */ 44 IN_EDT_CONSOLIDATED} 45 46 private static class ListenerInfo { 47 private final DataSetListener listener; 48 private final boolean consolidate; 49 50 public ListenerInfo(DataSetListener listener, boolean consolidate) { 51 this.listener = listener; 52 this.consolidate = consolidate; 53 } 54 55 @Override 56 public int hashCode() { 57 return listener.hashCode(); 58 } 59 60 @Override 61 public boolean equals(Object o) { 62 return o instanceof ListenerInfo && ((ListenerInfo)o).listener == listener; 63 } 64 } 65 66 public static DatasetEventManager getInstance() { 67 return instance; 68 } 69 70 private final Queue<AbstractDatasetChangedEvent> eventsInEDT = new LinkedBlockingQueue<>(); 71 private final CopyOnWriteArrayList<ListenerInfo> inEDTListeners = new CopyOnWriteArrayList<>(); 72 private final CopyOnWriteArrayList<ListenerInfo> normalListeners = new CopyOnWriteArrayList<>(); 73 private final DataSetListener myListener = new DataSetListenerAdapter(this); 74 75 /** 76 * Constructs a new {@code DatasetEventManager}. 77 */ 78 public DatasetEventManager() { 79 MapView.addEditLayerChangeListener(this); 80 } 81 82 /** 83 * Register listener, that will receive events from currently active dataset 84 * @param listener the listener to be registered 85 * @param fireMode If {@link FireMode#IN_EDT} or {@link FireMode#IN_EDT_CONSOLIDATED}, 86 * listener will be notified in event dispatch thread instead of thread that caused 87 * the dataset change 88 */ 89 public void addDatasetListener(DataSetListener listener, FireMode fireMode) { 90 if (fireMode == FireMode.IN_EDT || fireMode == FireMode.IN_EDT_CONSOLIDATED) { 91 inEDTListeners.addIfAbsent(new ListenerInfo(listener, fireMode == FireMode.IN_EDT_CONSOLIDATED)); 92 } else { 93 normalListeners.addIfAbsent(new ListenerInfo(listener, false)); 94 } 95 } 96 97 public void removeDatasetListener(DataSetListener listener) { 98 ListenerInfo searchListener = new ListenerInfo(listener, false); 99 inEDTListeners.remove(searchListener); 100 normalListeners.remove(searchListener); 101 } 102 103 @Override 104 public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) { 105 if (oldLayer != null) { 106 oldLayer.data.removeDataSetListener(myListener); 107 } 108 109 if (newLayer != null) { 110 newLayer.data.addDataSetListener(myListener); 111 processDatasetEvent(new DataChangedEvent(newLayer.data)); 112 } else { 113 processDatasetEvent(new DataChangedEvent(null)); 114 } 115 } 116 117 private void fireEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) { 118 for (ListenerInfo listener: listeners) { 119 if (!listener.consolidate) { 120 event.fire(listener.listener); 121 } 122 } 123 } 124 125 private void fireConsolidatedEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) { 126 for (ListenerInfo listener: listeners) { 127 if (listener.consolidate) { 128 event.fire(listener.listener); 129 } 130 } 131 } 132 133 @Override 134 public void processDatasetEvent(AbstractDatasetChangedEvent event) { 135 fireEvents(normalListeners, event); 136 eventsInEDT.add(event); 137 SwingUtilities.invokeLater(edtRunnable); 138 } 139 140 private final Runnable edtRunnable = new Runnable() { 31 private final class EdtRunnable implements Runnable { 141 32 @Override 142 33 public void run() { 143 34 while (!eventsInEDT.isEmpty()) { 144 List<AbstractDatasetChangedEvent> events = new ArrayList<>(); 145 events.addAll(eventsInEDT); 35 List<AbstractDatasetChangedEvent> events = new ArrayList<>(eventsInEDT); 146 36 147 37 DataSet dataSet = null; … … 192 82 consolidatedEvent = new DataChangedEvent(dataSet, new ArrayList<>(Arrays.asList(consolidatedEvent))); 193 83 } 194 195 84 } 196 85 } … … 200 89 } 201 90 } 202 }; 91 } 92 93 public enum FireMode { 94 /** 95 * Fire in calling thread immediately. 96 */ 97 IMMEDIATELY, 98 /** 99 * Fire in event dispatch thread. 100 */ 101 IN_EDT, 102 /** 103 * Fire in event dispatch thread. If more than one event arrived when event queue is checked, merged them to 104 * one event 105 */ 106 IN_EDT_CONSOLIDATED} 107 108 private static class ListenerInfo { 109 private final DataSetListener listener; 110 private final boolean consolidate; 111 112 public ListenerInfo(DataSetListener listener, boolean consolidate) { 113 this.listener = listener; 114 this.consolidate = consolidate; 115 } 116 117 @Override 118 public int hashCode() { 119 return listener.hashCode(); 120 } 121 122 @Override 123 public boolean equals(Object o) { 124 return o instanceof ListenerInfo && ((ListenerInfo)o).listener == listener; 125 } 126 } 127 128 public static DatasetEventManager getInstance() { 129 return instance; 130 } 131 132 private final Queue<AbstractDatasetChangedEvent> eventsInEDT = new LinkedBlockingQueue<>(); 133 private final CopyOnWriteArrayList<ListenerInfo> inEDTListeners = new CopyOnWriteArrayList<>(); 134 private final CopyOnWriteArrayList<ListenerInfo> normalListeners = new CopyOnWriteArrayList<>(); 135 private final DataSetListener myListener = new DataSetListenerAdapter(this); 136 private final Runnable edtRunnable = new EdtRunnable(); 137 138 /** 139 * Constructs a new {@code DatasetEventManager}. 140 */ 141 public DatasetEventManager() { 142 MapView.addEditLayerChangeListener(this); 143 } 144 145 /** 146 * Register listener, that will receive events from currently active dataset 147 * @param listener the listener to be registered 148 * @param fireMode If {@link FireMode#IN_EDT} or {@link FireMode#IN_EDT_CONSOLIDATED}, 149 * listener will be notified in event dispatch thread instead of thread that caused 150 * the dataset change 151 */ 152 public void addDatasetListener(DataSetListener listener, FireMode fireMode) { 153 if (fireMode == FireMode.IN_EDT || fireMode == FireMode.IN_EDT_CONSOLIDATED) { 154 inEDTListeners.addIfAbsent(new ListenerInfo(listener, fireMode == FireMode.IN_EDT_CONSOLIDATED)); 155 } else { 156 normalListeners.addIfAbsent(new ListenerInfo(listener, false)); 157 } 158 } 159 160 public void removeDatasetListener(DataSetListener listener) { 161 ListenerInfo searchListener = new ListenerInfo(listener, false); 162 inEDTListeners.remove(searchListener); 163 normalListeners.remove(searchListener); 164 } 165 166 @Override 167 public void editLayerChanged(OsmDataLayer oldLayer, OsmDataLayer newLayer) { 168 if (oldLayer != null) { 169 oldLayer.data.removeDataSetListener(myListener); 170 } 171 172 if (newLayer != null) { 173 newLayer.data.addDataSetListener(myListener); 174 processDatasetEvent(new DataChangedEvent(newLayer.data)); 175 } else { 176 processDatasetEvent(new DataChangedEvent(null)); 177 } 178 } 179 180 private void fireEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) { 181 for (ListenerInfo listener: listeners) { 182 if (!listener.consolidate) { 183 event.fire(listener.listener); 184 } 185 } 186 } 187 188 private void fireConsolidatedEvents(List<ListenerInfo> listeners, AbstractDatasetChangedEvent event) { 189 for (ListenerInfo listener: listeners) { 190 if (listener.consolidate) { 191 event.fire(listener.listener); 192 } 193 } 194 } 195 196 @Override 197 public void processDatasetEvent(AbstractDatasetChangedEvent event) { 198 fireEvents(normalListeners, event); 199 eventsInEDT.add(event); 200 SwingUtilities.invokeLater(edtRunnable); 201 } 203 202 } -
trunk/src/org/openstreetmap/josm/data/osm/history/HistoryNode.java
r8291 r8509 50 50 * @since 5440 51 51 */ 52 public HistoryNode(long id, long version, boolean visible, User user, long changesetId, Date timestamp, LatLon coords, boolean checkHistoricParams) { 52 public HistoryNode(long id, long version, boolean visible, User user, long changesetId, Date timestamp, LatLon coords, 53 boolean checkHistoricParams) { 53 54 super(id, version, visible, user, changesetId, timestamp, checkHistoricParams); 54 55 setCoords(coords); -
trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/LineClip.java
r8444 r8509 38 38 return false; 39 39 } 40 return cohenSutherland(p1.x, p1.y, p2.x, p2.y, clipBounds.x , clipBounds.y, clipBounds.x + clipBounds.width, clipBounds.y + clipBounds.height); 40 return cohenSutherland(p1.x, p1.y, p2.x, p2.y, clipBounds.x , clipBounds.y, 41 clipBounds.x + clipBounds.width, clipBounds.y + clipBounds.height); 41 42 } 42 43 -
trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/MapRendererFactory.java
r8444 r8509 128 128 activateDefault(); 129 129 } else if (!AbstractMapRenderer.class.isAssignableFrom(c)) { 130 Main.error(tr("Can''t activate map renderer class ''{0}'', because it isn''t a subclass of ''{1}''.", rendererClassName, AbstractMapRenderer.class.getName())); 130 Main.error(tr("Can''t activate map renderer class ''{0}'', because it isn''t a subclass of ''{1}''.", 131 rendererClassName, AbstractMapRenderer.class.getName())); 131 132 Main.error(tr("Activating the standard map renderer instead.")); 132 133 activateDefault(); … … 260 261 * @see AbstractMapRenderer#AbstractMapRenderer(Graphics2D, NavigatableComponent, boolean) 261 262 */ 262 public AbstractMapRenderer createActiveRenderer(Graphics2D g, NavigatableComponent viewport, boolean isInactiveMode) throws MapRendererFactoryException{ 263 public AbstractMapRenderer createActiveRenderer(Graphics2D g, NavigatableComponent viewport, boolean isInactiveMode) 264 throws MapRendererFactoryException{ 263 265 try { 264 266 Constructor<?> c = activeRenderer.getConstructor(new Class<?>[]{Graphics2D.class, NavigatableComponent.class, boolean.class}); -
trunk/src/org/openstreetmap/josm/data/osm/visitor/paint/StyledMapRenderer.java
r8470 r8509 1086 1086 long dx, dy; 1087 1087 1088 // find half segments that are long enough to draw text on 1089 // (don't draw text over the cross hair in the center of each segment) 1088 // find half segments that are long enough to draw text on (don't draw text over the cross hair in the center of each segment) 1090 1089 List<Double> longHalfSegmentStart = new ArrayList<>(); // start point of half segment (as length along the way) 1091 1090 List<Double> longHalfSegmentEnd = new ArrayList<>(); // end point of half segment (as length along the way) … … 1139 1138 if (!longHalfSegmentStart.isEmpty()) { 1140 1139 if (way.getNodesCount() == 2) { 1141 // For 2 node ways, the two half segments are exactly 1142 // the same size and distance from the center. 1140 // For 2 node ways, the two half segments are exactly the same size and distance from the center. 1143 1141 // Prefer the first one for consistency. 1144 1142 longHalfsegmentQuality.set(0, longHalfsegmentQuality.get(0) + 0.5); … … 1214 1212 } 1215 1213 } 1216 // only works for text that is completely left-to-right or completely 1217 // right-to-left, not bi-directional text 1214 // only works for text that is completely left-to-right or completely right-to-left, not bi-directional text 1218 1215 GlyphVector gv = text.font.layoutGlyphVector(frc, chars, 0, chars.length, dirFlag); 1219 1216 -
trunk/src/org/openstreetmap/josm/data/projection/CustomProjection.java
r8415 r8509 125 125 /** 126 126 * Constructs a new {@code CustomProjection} with given parameters. 127 * @param pref String containing projection parameters (ex: "+proj=tmerc +lon_0=-3 +k_0=0.9996 +x_0=500000 +ellps=WGS84 +datum=WGS84 +bounds=-8,-5,2,85") 127 * @param pref String containing projection parameters 128 * (ex: "+proj=tmerc +lon_0=-3 +k_0=0.9996 +x_0=500000 +ellps=WGS84 +datum=WGS84 +bounds=-8,-5,2,85") 128 129 */ 129 130 public CustomProjection(String pref) { -
trunk/src/org/openstreetmap/josm/data/projection/datum/SevenParameterDatum.java
r8444 r8509 33 33 * @param s scale change in parts per million 34 34 */ 35 public SevenParameterDatum(String name, String proj4Id, Ellipsoid ellps, double dx, double dy, double dz, double rx, double ry, double rz, double s) { 35 public SevenParameterDatum(String name, String proj4Id, Ellipsoid ellps, double dx, double dy, double dz, 36 double rx, double ry, double rz, double s) { 36 37 super(name, proj4Id, ellps); 37 38 this.dx = dx; -
trunk/src/org/openstreetmap/josm/data/projection/proj/SwissObliqueMercator.java
r8444 r8509 23 23 * Projection for the SwissGrid CH1903 / L03, see <a href="https://en.wikipedia.org/wiki/Swiss_coordinate_system">Wikipedia article</a>.<br> 24 24 * 25 * Calculations were originally based on <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.12749.DownloadFile.tmp/ch1903wgs84en.pdf"> 25 * Calculations were originally based on 26 * <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.12749.DownloadFile.tmp/ch1903wgs84en.pdf"> 26 27 * simple formula</a>.<br> 27 28 * 28 * August 2010 update to <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.97912.DownloadFile.tmp/swissprojectionen.pdf"> 29 * August 2010 update to 30 * <a href="http://www.swisstopo.admin.ch/internet/swisstopo/en/home/topics/survey/sys/refsys/switzerland.parsysrelated1.37696.downloadList.97912.DownloadFile.tmp/swissprojectionen.pdf"> 29 31 * this formula (rigorous formulas)</a>. 30 32 */ -
trunk/src/org/openstreetmap/josm/data/validation/routines/UrlValidator.java
r8461 r8509 64 64 * </pre> 65 65 * 66 * @version $Revision: 1640269 $ $Date: 2014-11-18 02:28:56 UTC (Tue, 18 Nov 2014) $ 66 67 * @see 67 68 * <a href="http://www.ietf.org/rfc/rfc2396.txt"> … … 69 70 * </a> 70 71 * 71 * @version $Revision: 1640269 $ $Date: 2014-11-18 02:28:56 UTC (Tue, 18 Nov 2014) $72 72 * @since Validator 1.4 73 73 */ -
trunk/src/org/openstreetmap/josm/data/validation/tests/ConditionalKeys.java
r8285 r8509 102 102 // <restriction-value> @ <condition>[;<restriction-value> @ <condition>] 103 103 final List<ConditionalValue> r = new ArrayList<>(); 104 final Pattern part = Pattern.compile("([^@\\p{Space}][^@]*?)" + "\\s*@\\s*" + "(\\([^)\\p{Space}][^)]+?\\)|[^();\\p{Space}][^();]*?)\\s*"); 104 final Pattern part = Pattern.compile("([^@\\p{Space}][^@]*?)" 105 + "\\s*@\\s*" + "(\\([^)\\p{Space}][^)]+?\\)|[^();\\p{Space}][^();]*?)\\s*"); 105 106 final Matcher m = Pattern.compile("(" + part + ")(;\\s*" + part + ")*").matcher(value); 106 107 if (!m.matches()) { -
trunk/src/org/openstreetmap/josm/data/validation/tests/Highways.java
r8454 r8509 102 102 public void visit(Way w) { 103 103 if (w.isUsable()) { 104 if (w.hasKey("highway") && CLASSIFIED_HIGHWAYS.contains(w.get("highway")) && w.hasKey("junction") && "roundabout".equals(w.get("junction"))) { 104 if (w.hasKey("highway") && CLASSIFIED_HIGHWAYS.contains(w.get("highway")) 105 && w.hasKey("junction") && "roundabout".equals(w.get("junction"))) { 105 106 testWrongRoundabout(w); 106 107 } … … 248 249 String context = value.substring(index+1); 249 250 if (!KNOWN_SOURCE_MAXSPEED_CONTEXTS.contains(context)) { 250 errors.add(new TestError(this, Severity.WARNING, tr("Unknown source:maxspeed context: {0}", context), SOURCE_MAXSPEED_UNKNOWN_CONTEXT, p)); 251 errors.add(new TestError(this, Severity.WARNING, 252 tr("Unknown source:maxspeed context: {0}", context), SOURCE_MAXSPEED_UNKNOWN_CONTEXT, p)); 251 253 } 252 254 // TODO: Check coherence of context against maxspeed -
trunk/src/org/openstreetmap/josm/data/validation/tests/MapCSSTagChecker.java
r8465 r8509 148 148 abstract static class FixCommand { 149 149 /** 150 * Creates the fixing {@link Command} for the given primitive. The {@code matchingSelector} is used to 151 * evaluate placeholders(cf. {@link org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.TagCheck#insertArguments(Selector, String, OsmPrimitive)}).150 * Creates the fixing {@link Command} for the given primitive. The {@code matchingSelector} is used to evaluate placeholders 151 * (cf. {@link org.openstreetmap.josm.data.validation.tests.MapCSSTagChecker.TagCheck#insertArguments(Selector, String, OsmPrimitive)}). 152 152 */ 153 153 abstract Command createCommand(final OsmPrimitive p, final Selector matchingSelector); 154 154 155 155 private static void checkObject(final Object obj) { 156 CheckParameterUtil.ensureThat(obj instanceof Expression || obj instanceof String, "instance of Exception or String expected, but got " + obj); 156 CheckParameterUtil.ensureThat(obj instanceof Expression || obj instanceof String, 157 "instance of Exception or String expected, but got " + obj); 157 158 } 158 159 -
trunk/src/org/openstreetmap/josm/data/validation/tests/MultipolygonTest.java
r8382 r8509 198 198 addError(r, new TestError(this, Severity.WARNING, 199 199 trn("Multipolygon relation should be tagged with area tags and not the outer way", 200 "Multipolygon relation should be tagged with area tags and not the outer ways", polygon.getOuterWays().size()), 200 "Multipolygon relation should be tagged with area tags and not the outer ways", 201 polygon.getOuterWays().size()), 201 202 NO_STYLE_POLYGON, r)); 202 203 } … … 211 212 l.add(r); 212 213 l.add(wInner); 213 addError(r, new TestError(this, Severity.OTHER, tr("With the currently used mappaint style the style for inner way equals the multipolygon style"), 214 addError(r, new TestError(this, Severity.OTHER, 215 tr("With the currently used mappaint style the style for inner way equals the multipolygon style"), 214 216 INNER_STYLE_MISMATCH, l, Collections.singletonList(wInner))); 215 217 } … … 263 265 highlights.add(pdInner.getNodes()); 264 266 if (outside) { 265 addError(r, new TestError(this, Severity.WARNING, tr("Multipolygon inner way is outside"), INNER_WAY_OUTSIDE, Collections.singletonList(r), highlights)); 267 addError(r, new TestError(this, Severity.WARNING, tr("Multipolygon inner way is outside"), 268 INNER_WAY_OUTSIDE, Collections.singletonList(r), highlights)); 266 269 } else { 267 270 highlights.add(outerWay.getNodes()); 268 addError(r, new TestError(this, Severity.WARNING, tr("Intersection between multipolygon ways"), CROSSING_WAYS, Collections.singletonList(r), highlights)); 271 addError(r, new TestError(this, Severity.WARNING, tr("Intersection between multipolygon ways"), 272 CROSSING_WAYS, Collections.singletonList(r), highlights)); 269 273 } 270 274 } … … 277 281 if (rm.isWay()) { 278 282 if (!(rm.hasRole("inner", "outer") || !rm.hasRole())) { 279 addError(r, new TestError(this, Severity.WARNING, tr("No useful role for multipolygon member"), WRONG_MEMBER_ROLE, rm.getMember())); 283 addError(r, new TestError(this, Severity.WARNING, tr("No useful role for multipolygon member"), 284 WRONG_MEMBER_ROLE, rm.getMember())); 280 285 } 281 286 } else { -
trunk/src/org/openstreetmap/josm/data/validation/tests/UnconnectedWays.java
r8378 r8509 442 442 public void visit(Way w) { 443 443 if (w.getNodesCount() > 0 // do not consider empty ways 444 && !w.hasKey("addr:interpolation") // ignore addr:interpolation ways as they are not physical features and most of the time very near the associated highway, which is perfectly normal, see #9332 444 && !w.hasKey("addr:interpolation") // ignore addr:interpolation ways as they are not physical features and most of 445 // the time very near the associated highway, which is perfectly normal, see #9332 445 446 && !w.hasTag("highway", "platform") && !w.hasTag("railway", "platform") // similarly for public transport platforms 446 447 ) { -
trunk/src/org/openstreetmap/josm/data/validation/util/NameVisitor.java
r8378 r8509 19 19 * @author imi 20 20 */ 21 //TODO This class used to be in JOSM but it was removed. MultipleNameVisitor depends on it so I copied it here, but MultipleNameVisitor should be refactored instead of using this class 21 //TODO This class used to be in JOSM but it was removed. MultipleNameVisitor depends on it so I copied it here, 22 // but MultipleNameVisitor should be refactored instead of using this class 22 23 public class NameVisitor extends AbstractVisitor { 23 24 -
trunk/src/org/openstreetmap/josm/gui/ConditionalOptionPaneUtil.java
r8468 r8509 157 157 * @see JOptionPane#ERROR_MESSAGE 158 158 */ 159 public static boolean showConfirmationDialog(String preferenceKey, Component parent, Object message, String title, int optionType, int messageType, int trueOption) throws HeadlessException { 159 public static boolean showConfirmationDialog(String preferenceKey, Component parent, Object message, String title, 160 int optionType, int messageType, int trueOption) throws HeadlessException { 160 161 int ret = getDialogReturnValue(preferenceKey); 161 162 if (isYesOrNo(ret)) -
trunk/src/org/openstreetmap/josm/gui/FileDrop.java
r8465 r8509 34 34 import org.openstreetmap.josm.Main; 35 35 import org.openstreetmap.josm.actions.OpenFileAction; 36 import org.openstreetmap.josm.gui.FileDrop.TransferableObject;37 36 38 37 /** … … 128 127 if (supportsDnD()) { 129 128 // Make a drop listener 130 dropListener = new DropTargetListener() { 131 @Override 132 public void dragEnter(DropTargetDragEvent evt) { 133 Main.trace("FileDrop: dragEnter event."); 134 135 // Is this an acceptable drag event? 136 if (isDragOk(evt)) { 137 // If it's a Swing component, set its border 138 if (c instanceof JComponent) { 139 JComponent jc = (JComponent) c; 140 normalBorder = jc.getBorder(); 141 Main.trace("FileDrop: normal border saved."); 142 jc.setBorder(dragBorder); 143 Main.trace("FileDrop: drag border set."); 144 } 145 146 // Acknowledge that it's okay to enter 147 evt.acceptDrag(DnDConstants.ACTION_COPY); 148 Main.trace("FileDrop: event accepted."); 149 } else { 150 // Reject the drag event 151 evt.rejectDrag(); 152 Main.trace("FileDrop: event rejected."); 153 } 154 } 155 156 @Override 157 public void dragOver(DropTargetDragEvent evt) { 158 // This is called continually as long as the mouse is over the drag target. 159 } 160 161 @Override 162 public void drop(DropTargetDropEvent evt) { 163 Main.trace("FileDrop: drop event."); 164 try { 165 // Get whatever was dropped 166 Transferable tr = evt.getTransferable(); 167 168 // Is it a file list? 169 if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { 170 171 // Say we'll take it. 172 evt.acceptDrop(DnDConstants.ACTION_COPY); 173 Main.trace("FileDrop: file list accepted."); 174 175 // Get a useful list 176 List<?> fileList = (List<?>)tr.getTransferData(DataFlavor.javaFileListFlavor); 177 178 // Convert list to array 179 final File[] files = fileList.toArray(new File[fileList.size()]); 180 181 // Alert listener to drop. 182 if (listener != null) { 183 listener.filesDropped(files); 184 } 185 186 // Mark that drop is completed. 187 evt.getDropTargetContext().dropComplete(true); 188 Main.trace("FileDrop: drop complete."); 189 } else { 190 // this section will check for a reader flavor. 191 // Thanks, Nathan! 192 // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. 193 DataFlavor[] flavors = tr.getTransferDataFlavors(); 194 boolean handled = false; 195 for (DataFlavor flavor : flavors) { 196 if (flavor.isRepresentationClassReader()) { 197 // Say we'll take it. 198 evt.acceptDrop(DnDConstants.ACTION_COPY); 199 Main.trace("FileDrop: reader accepted."); 200 201 Reader reader = flavor.getReaderForText(tr); 202 203 BufferedReader br = new BufferedReader(reader); 204 205 if (listener != null) { 206 listener.filesDropped(createFileArray(br)); 207 } 208 209 // Mark that drop is completed. 210 evt.getDropTargetContext().dropComplete(true); 211 Main.trace("FileDrop: drop complete."); 212 handled = true; 213 break; 214 } 215 } 216 if (!handled) { 217 Main.trace("FileDrop: not a file list or reader - abort."); 218 evt.rejectDrop(); 219 } 220 // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. 221 } 222 } catch (IOException | UnsupportedFlavorException e) { 223 Main.warn("FileDrop: "+e.getClass().getSimpleName()+" - abort:"); 224 Main.error(e); 225 try { 226 evt.rejectDrop(); 227 } catch (InvalidDnDOperationException ex) { 228 // Catch InvalidDnDOperationException to fix #11259 229 Main.error(ex); 230 } 231 } finally { 232 // If it's a Swing component, reset its border 233 if (c instanceof JComponent) { 234 JComponent jc = (JComponent) c; 235 jc.setBorder(normalBorder); 236 Main.debug("FileDrop: normal border restored."); 237 } 238 } 239 } 240 241 @Override 242 public void dragExit(DropTargetEvent evt) { 243 Main.debug("FileDrop: dragExit event."); 244 // If it's a Swing component, reset its border 245 if (c instanceof JComponent) { 246 JComponent jc = (JComponent) c; 247 jc.setBorder(normalBorder); 248 Main.debug("FileDrop: normal border restored."); 249 } 250 } 251 252 @Override 253 public void dropActionChanged(DropTargetDragEvent evt) { 254 Main.debug("FileDrop: dropActionChanged event."); 255 // Is this an acceptable drag event? 256 if (isDragOk(evt)) { 257 evt.acceptDrag(DnDConstants.ACTION_COPY); 258 Main.debug("FileDrop: event accepted."); 259 } else { 260 evt.rejectDrag(); 261 Main.debug("FileDrop: event rejected."); 262 } 263 } 264 }; 129 dropListener = new DropListener(listener, dragBorder, c); 265 130 266 131 // Make the component (and possibly children) drop targets … … 428 293 429 294 /* ******** I N N E R I N T E R F A C E L I S T E N E R ******** */ 295 296 private final class DropListener implements DropTargetListener { 297 private final Listener listener; 298 private final Border dragBorder; 299 private final Component c; 300 301 private DropListener(Listener listener, Border dragBorder, Component c) { 302 this.listener = listener; 303 this.dragBorder = dragBorder; 304 this.c = c; 305 } 306 307 @Override 308 public void dragEnter(DropTargetDragEvent evt) { 309 Main.trace("FileDrop: dragEnter event."); 310 311 // Is this an acceptable drag event? 312 if (isDragOk(evt)) { 313 // If it's a Swing component, set its border 314 if (c instanceof JComponent) { 315 JComponent jc = (JComponent) c; 316 normalBorder = jc.getBorder(); 317 Main.trace("FileDrop: normal border saved."); 318 jc.setBorder(dragBorder); 319 Main.trace("FileDrop: drag border set."); 320 } 321 322 // Acknowledge that it's okay to enter 323 evt.acceptDrag(DnDConstants.ACTION_COPY); 324 Main.trace("FileDrop: event accepted."); 325 } else { 326 // Reject the drag event 327 evt.rejectDrag(); 328 Main.trace("FileDrop: event rejected."); 329 } 330 } 331 332 @Override 333 public void dragOver(DropTargetDragEvent evt) { 334 // This is called continually as long as the mouse is over the drag target. 335 } 336 337 @Override 338 public void drop(DropTargetDropEvent evt) { 339 Main.trace("FileDrop: drop event."); 340 try { 341 // Get whatever was dropped 342 Transferable tr = evt.getTransferable(); 343 344 // Is it a file list? 345 if (tr.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { 346 347 // Say we'll take it. 348 evt.acceptDrop(DnDConstants.ACTION_COPY); 349 Main.trace("FileDrop: file list accepted."); 350 351 // Get a useful list 352 List<?> fileList = (List<?>)tr.getTransferData(DataFlavor.javaFileListFlavor); 353 354 // Convert list to array 355 final File[] files = fileList.toArray(new File[fileList.size()]); 356 357 // Alert listener to drop. 358 if (listener != null) { 359 listener.filesDropped(files); 360 } 361 362 // Mark that drop is completed. 363 evt.getDropTargetContext().dropComplete(true); 364 Main.trace("FileDrop: drop complete."); 365 } else { 366 // this section will check for a reader flavor. 367 // Thanks, Nathan! 368 // BEGIN 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. 369 DataFlavor[] flavors = tr.getTransferDataFlavors(); 370 boolean handled = false; 371 for (DataFlavor flavor : flavors) { 372 if (flavor.isRepresentationClassReader()) { 373 // Say we'll take it. 374 evt.acceptDrop(DnDConstants.ACTION_COPY); 375 Main.trace("FileDrop: reader accepted."); 376 377 Reader reader = flavor.getReaderForText(tr); 378 379 BufferedReader br = new BufferedReader(reader); 380 381 if (listener != null) { 382 listener.filesDropped(createFileArray(br)); 383 } 384 385 // Mark that drop is completed. 386 evt.getDropTargetContext().dropComplete(true); 387 Main.trace("FileDrop: drop complete."); 388 handled = true; 389 break; 390 } 391 } 392 if (!handled) { 393 Main.trace("FileDrop: not a file list or reader - abort."); 394 evt.rejectDrop(); 395 } 396 // END 2007-09-12 Nathan Blomquist -- Linux (KDE/Gnome) support added. 397 } 398 } catch (IOException | UnsupportedFlavorException e) { 399 Main.warn("FileDrop: "+e.getClass().getSimpleName()+" - abort:"); 400 Main.error(e); 401 try { 402 evt.rejectDrop(); 403 } catch (InvalidDnDOperationException ex) { 404 // Catch InvalidDnDOperationException to fix #11259 405 Main.error(ex); 406 } 407 } finally { 408 // If it's a Swing component, reset its border 409 if (c instanceof JComponent) { 410 JComponent jc = (JComponent) c; 411 jc.setBorder(normalBorder); 412 Main.debug("FileDrop: normal border restored."); 413 } 414 } 415 } 416 417 @Override 418 public void dragExit(DropTargetEvent evt) { 419 Main.debug("FileDrop: dragExit event."); 420 // If it's a Swing component, reset its border 421 if (c instanceof JComponent) { 422 JComponent jc = (JComponent) c; 423 jc.setBorder(normalBorder); 424 Main.debug("FileDrop: normal border restored."); 425 } 426 } 427 428 @Override 429 public void dropActionChanged(DropTargetDragEvent evt) { 430 Main.debug("FileDrop: dropActionChanged event."); 431 // Is this an acceptable drag event? 432 if (isDragOk(evt)) { 433 evt.acceptDrag(DnDConstants.ACTION_COPY); 434 Main.debug("FileDrop: event accepted."); 435 } else { 436 evt.rejectDrag(); 437 Main.debug("FileDrop: event rejected."); 438 } 439 } 440 } 430 441 431 442 /** … … 512 523 */ 513 524 public static final DataFlavor DATA_FLAVOR = 514 new DataFlavor( FileDrop.TransferableObject.class, MIME_TYPE);525 new DataFlavor(TransferableObject.class, MIME_TYPE); 515 526 516 527 private Fetcher fetcher; -
trunk/src/org/openstreetmap/josm/gui/HelpAwareOptionPane.java
r8387 r8509 335 335 * @param helpTopic the help topic. Can be null. 336 336 */ 337 public static void showMessageDialogInEDT(final Component parentComponent, final Object msg, final String title, final int messageType, final String helpTopic) { 337 public static void showMessageDialogInEDT(final Component parentComponent, final Object msg, final String title, 338 final int messageType, final String helpTopic) { 338 339 GuiHelper.runInEDT(new Runnable() { 339 340 @Override -
trunk/src/org/openstreetmap/josm/gui/JosmUserIdentityManager.java
r8291 r8509 106 106 CheckParameterUtil.ensureParameterNotNull(userName, "userName"); 107 107 if (userName.trim().isEmpty()) 108 throw new IllegalArgumentException(MessageFormat.format("Expected non-empty value for parameter ''{0}'', got ''{1}''", "userName", userName)); 108 throw new IllegalArgumentException( 109 MessageFormat.format("Expected non-empty value for parameter ''{0}'', got ''{1}''", "userName", userName)); 109 110 this.userName = userName; 110 111 userInfo = null; -
trunk/src/org/openstreetmap/josm/gui/MainApplication.java
r8497 r8509 482 482 try { 483 483 // Check for insecure certificates to remove. 484 // This is Windows-dependant code but it can't go to preStartupHook (need i18n) neither startupHook (need to be called before remote control) 484 // This is Windows-dependant code but it can't go to preStartupHook (need i18n) 485 // neither startupHook (need to be called before remote control) 485 486 PlatformHookWindows.removeInsecureCertificates(); 486 487 } catch (NoSuchAlgorithmException | CertificateException | KeyStoreException | IOException e) { … … 498 499 499 500 if (Main.pref.getBoolean("debug.edt-checker.enable", Version.getInstance().isLocalBuild())) { 500 // Repaint manager is registered so late for a reason - there is lots of violation during startup process but they don't seem to break anything and are difficult to fix 501 // Repaint manager is registered so late for a reason - there is lots of violation during startup process 502 // but they don't seem to break anything and are difficult to fix 501 503 info("Enabled EDT checker, wrongful access to gui from non EDT thread will be printed to console"); 502 504 RepaintManager.setCurrentManager(new CheckThreadViolationRepaintManager()); -
trunk/src/org/openstreetmap/josm/gui/MapFrame.java
r8470 r8509 702 702 modeChanged = newMapMode != mapMode; 703 703 if (newMapMode != null) { 704 selectMapMode(newMapMode, newLayer); // it would be nice to select first supported mode when layer is first selected, but it don't work well with for example editgpx layer 704 // it would be nice to select first supported mode when layer is first selected, 705 // but it don't work well with for example editgpx layer 706 selectMapMode(newMapMode, newLayer); 705 707 } else if (mapMode != null) { 706 708 mapMode.exitMode(); // if new mode is null - simply exit from previous mode … … 726 728 }); 727 729 } 728 729 730 730 731 private MapMode getLastMapMode(Layer newLayer) { -
trunk/src/org/openstreetmap/josm/gui/MapMover.java
r7606 r8509 119 119 if (!Main.isPlatformOsx()) { 120 120 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( 121 Shortcut.registerShortcut("view:zoominalternate", tr("Map: {0}", tr("Zoom in")), KeyEvent.VK_COMMA, Shortcut.CTRL).getKeyStroke(), 121 Shortcut.registerShortcut("view:zoominalternate", 122 tr("Map: {0}", tr("Zoom in")), KeyEvent.VK_COMMA, Shortcut.CTRL).getKeyStroke(), 122 123 "MapMover.Zoomer.in"); 123 124 contentPane.getActionMap().put("MapMover.Zoomer.in", new ZoomerAction(",")); 124 125 125 126 contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put( 126 Shortcut.registerShortcut("view:zoomoutalternate", tr("Map: {0}", tr("Zoom out")), KeyEvent.VK_PERIOD, Shortcut.CTRL).getKeyStroke(), 127 Shortcut.registerShortcut("view:zoomoutalternate", 128 tr("Map: {0}", tr("Zoom out")), KeyEvent.VK_PERIOD, Shortcut.CTRL).getKeyStroke(), 127 129 "MapMover.Zoomer.out"); 128 130 contentPane.getActionMap().put("MapMover.Zoomer.out", new ZoomerAction(".")); -
trunk/src/org/openstreetmap/josm/gui/MapStatus.java
r8470 r8509 228 228 229 229 /** 230 * The collector class that waits for notification and then update 231 * the display objects. 230 * The collector class that waits for notification and then update the display objects. 232 231 * 233 232 * @author imi 234 233 */ 235 234 private final class Collector implements Runnable { 235 private final class CollectorWorker implements Runnable { 236 private final MouseState ms; 237 238 private CollectorWorker(MouseState ms) { 239 this.ms = ms; 240 } 241 242 @Override 243 public void run() { 244 // Freeze display when holding down CTRL 245 if ((ms.modifiers & MouseEvent.CTRL_DOWN_MASK) != 0) { 246 // update the information popup's labels though, because the selection might have changed from the outside 247 popupUpdateLabels(); 248 return; 249 } 250 251 // This try/catch is a hack to stop the flooding bug reports about this. 252 // The exception needed to handle with in the first place, means that this 253 // access to the data need to be restarted, if the main thread modifies the data. 254 DataSet ds = null; 255 // The popup != null check is required because a left-click produces several events as well, 256 // which would make this variable true. Of course we only want the popup to show 257 // if the middle mouse button has been pressed in the first place 258 boolean mouseNotMoved = oldMousePos != null 259 && oldMousePos.equals(ms.mousePos); 260 boolean isAtOldPosition = mouseNotMoved && popup != null; 261 boolean middleMouseDown = (ms.modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0; 262 try { 263 ds = mv.getCurrentDataSet(); 264 if (ds != null) { 265 // This is not perfect, if current dataset was changed during execution, the lock would be useless 266 if(isAtOldPosition && middleMouseDown) { 267 // Write lock is necessary when selecting in popupCycleSelection 268 // locks can not be upgraded -> if do read lock here and write lock later 269 // (in OsmPrimitive.updateFlags) then always occurs deadlock (#5814) 270 ds.beginUpdate(); 271 } else { 272 ds.getReadLock().lock(); 273 } 274 } 275 276 // Set the text label in the bottom status bar 277 // "if mouse moved only" was added to stop heap growing 278 if (!mouseNotMoved) { 279 statusBarElementUpdate(ms); 280 } 281 282 // Popup Information 283 // display them if the middle mouse button is pressed and keep them until the mouse is moved 284 if (middleMouseDown || isAtOldPosition) { 285 Collection<OsmPrimitive> osms = mv.getAllNearest(ms.mousePos, OsmPrimitive.isUsablePredicate); 286 287 final JPanel c = new JPanel(new GridBagLayout()); 288 final JLabel lbl = new JLabel( 289 "<html>"+tr("Middle click again to cycle through.<br>"+ 290 "Hold CTRL to select directly from this list with the mouse.<hr>")+"</html>", 291 null, 292 JLabel.HORIZONTAL 293 ); 294 lbl.setHorizontalAlignment(JLabel.LEFT); 295 c.add(lbl, GBC.eol().insets(2, 0, 2, 0)); 296 297 // Only cycle if the mouse has not been moved and the middle mouse button has been pressed at least 298 // twice (the reason for this is the popup != null check for isAtOldPosition, see above. 299 // This is a nice side effect though, because it does not change selection of the first middle click) 300 if (isAtOldPosition && middleMouseDown) { 301 // Hand down mouse modifiers so the SHIFT mod can be handled correctly (see function) 302 popupCycleSelection(osms, ms.modifiers); 303 } 304 305 // These labels may need to be updated from the outside so collect them 306 List<JLabel> lbls = new ArrayList<>(osms.size()); 307 for (final OsmPrimitive osm : osms) { 308 JLabel l = popupBuildPrimitiveLabels(osm); 309 lbls.add(l); 310 c.add(l, GBC.eol().fill(GBC.HORIZONTAL).insets(2, 0, 2, 2)); 311 } 312 313 popupShowPopup(popupCreatePopup(c, ms), lbls); 314 } else { 315 popupHidePopup(); 316 } 317 318 oldMousePos = ms.mousePos; 319 } catch (ConcurrentModificationException x) { 320 Main.warn(x); 321 } finally { 322 if (ds != null) { 323 if(isAtOldPosition && middleMouseDown) { 324 ds.endUpdate(); 325 } else { 326 ds.getReadLock().unlock(); 327 } 328 } 329 } 330 } 331 } 332 236 333 /** 237 334 * the mouse position of the previous iteration. This is used to show … … 285 382 286 383 try { 287 EventQueue.invokeAndWait(new Runnable() { 288 289 @Override 290 public void run() { 291 // Freeze display when holding down CTRL 292 if ((ms.modifiers & MouseEvent.CTRL_DOWN_MASK) != 0) { 293 // update the information popup's labels though, because 294 // the selection might have changed from the outside 295 popupUpdateLabels(); 296 return; 297 } 298 299 // This try/catch is a hack to stop the flooding bug reports about this. 300 // The exception needed to handle with in the first place, means that this 301 // access to the data need to be restarted, if the main thread modifies 302 // the data. 303 DataSet ds = null; 304 // The popup != null check is required because a left-click 305 // produces several events as well, which would make this 306 // variable true. Of course we only want the popup to show 307 // if the middle mouse button has been pressed in the first place 308 boolean mouseNotMoved = oldMousePos != null 309 && oldMousePos.equals(ms.mousePos); 310 boolean isAtOldPosition = mouseNotMoved && popup != null; 311 boolean middleMouseDown = (ms.modifiers & MouseEvent.BUTTON2_DOWN_MASK) != 0; 312 try { 313 ds = mv.getCurrentDataSet(); 314 if (ds != null) { 315 // This is not perfect, if current dataset was changed during execution, the lock would be useless 316 if(isAtOldPosition && middleMouseDown) { 317 // Write lock is necessary when selecting in popupCycleSelection 318 // locks can not be upgraded -> if do read lock here and write lock later (in OsmPrimitive.updateFlags) 319 // then always occurs deadlock (#5814) 320 ds.beginUpdate(); 321 } else { 322 ds.getReadLock().lock(); 323 } 324 } 325 326 // Set the text label in the bottom status bar 327 // "if mouse moved only" was added to stop heap growing 328 if (!mouseNotMoved) { 329 statusBarElementUpdate(ms); 330 } 331 332 // Popup Information 333 // display them if the middle mouse button is pressed and keep them until the mouse is moved 334 if (middleMouseDown || isAtOldPosition) { 335 Collection<OsmPrimitive> osms = mv.getAllNearest(ms.mousePos, OsmPrimitive.isUsablePredicate); 336 337 final JPanel c = new JPanel(new GridBagLayout()); 338 final JLabel lbl = new JLabel( 339 "<html>"+tr("Middle click again to cycle through.<br>"+ 340 "Hold CTRL to select directly from this list with the mouse.<hr>")+"</html>", 341 null, 342 JLabel.HORIZONTAL 343 ); 344 lbl.setHorizontalAlignment(JLabel.LEFT); 345 c.add(lbl, GBC.eol().insets(2, 0, 2, 0)); 346 347 // Only cycle if the mouse has not been moved and the middle mouse button has been pressed at least 348 // twice (the reason for this is the popup != null check for isAtOldPosition, see above. 349 // This is a nice side effect though, because it does not change selection of the first middle click) 350 if (isAtOldPosition && middleMouseDown) { 351 // Hand down mouse modifiers so the SHIFT mod can be handled correctly (see function) 352 popupCycleSelection(osms, ms.modifiers); 353 } 354 355 // These labels may need to be updated from the outside so collect them 356 List<JLabel> lbls = new ArrayList<>(osms.size()); 357 for (final OsmPrimitive osm : osms) { 358 JLabel l = popupBuildPrimitiveLabels(osm); 359 lbls.add(l); 360 c.add(l, GBC.eol().fill(GBC.HORIZONTAL).insets(2, 0, 2, 2)); 361 } 362 363 popupShowPopup(popupCreatePopup(c, ms), lbls); 364 } else { 365 popupHidePopup(); 366 } 367 368 oldMousePos = ms.mousePos; 369 } catch (ConcurrentModificationException x) { 370 Main.warn(x); 371 } finally { 372 if (ds != null) { 373 if(isAtOldPosition && middleMouseDown) { 374 ds.endUpdate(); 375 } else { 376 ds.getReadLock().unlock(); 377 } 378 } 379 } 380 } 381 }); 384 EventQueue.invokeAndWait(new CollectorWorker(ms)); 382 385 } catch (InterruptedException e) { 383 386 // Occurs frequently during JOSM shutdown, log set to trace only -
trunk/src/org/openstreetmap/josm/gui/MapView.java
r8454 r8509 76 76 * @author imi 77 77 */ 78 public class MapView extends NavigatableComponent implements PropertyChangeListener, PreferenceChangedListener, OsmDataLayer.LayerStateChangeListener { 78 public class MapView extends NavigatableComponent 79 implements PropertyChangeListener, PreferenceChangedListener, OsmDataLayer.LayerStateChangeListener { 79 80 80 81 /** … … 599 600 600 601 if (!canUseBuffer || nonChangedLayersBuffer == null) { 601 if (null == nonChangedLayersBuffer || nonChangedLayersBuffer.getWidth() != getWidth() || nonChangedLayersBuffer.getHeight() != getHeight()) { 602 if (null == nonChangedLayersBuffer 603 || nonChangedLayersBuffer.getWidth() != getWidth() || nonChangedLayersBuffer.getHeight() != getHeight()) { 602 604 nonChangedLayersBuffer = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_3BYTE_BGR); 603 605 } -
trunk/src/org/openstreetmap/josm/gui/OsmPrimitivRenderer.java
r7021 r8509 43 43 */ 44 44 @Override 45 public Component getListCellRendererComponent(JList<? extends OsmPrimitive> list, OsmPrimitive value, int index, boolean isSelected, boolean cellHasFocus) { 45 public Component getListCellRendererComponent(JList<? extends OsmPrimitive> list, OsmPrimitive value, int index, 46 boolean isSelected, boolean cellHasFocus) { 46 47 Component def = defaultListCellRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); 47 48 return renderer(def, value); -
trunk/src/org/openstreetmap/josm/gui/SplashScreen.java
r8500 r8509 240 240 } 241 241 242 /** 243 * @deprecated Use {@link #finishTask(String)} instead. 244 */ 242 245 @Override 243 246 @Deprecated -
trunk/src/org/openstreetmap/josm/gui/bbox/SourceButton.java
r8308 r8509 102 102 103 103 g.setColor(new Color(0, 0, 139, 179)); 104 g.fillRoundRect(0, 0, barWidth + shrinkImage.getIconWidth(), sources.length * LAYER_HEIGHT + TOP_PADDING + BOTTOM_PADDING, 10, 10); 104 g.fillRoundRect(0, 0, barWidth + shrinkImage.getIconWidth(), 105 sources.length * LAYER_HEIGHT + TOP_PADDING + BOTTOM_PADDING, 10, 10); 105 106 for (int i=0; i<sources.length; i++) { 106 107 g.setColor(Color.WHITE); 107 108 g.fillOval(LEFT_PADDING, TOP_PADDING + i * LAYER_HEIGHT + 6, radioButtonSize, radioButtonSize); 108 g.drawString(sources[i].getName(), LEFT_PADDING + radioButtonSize + LEFT_PADDING, TOP_PADDING + i * LAYER_HEIGHT + g.getFontMetrics().getHeight()); 109 g.drawString(sources[i].getName(), LEFT_PADDING + radioButtonSize + LEFT_PADDING, 110 TOP_PADDING + i * LAYER_HEIGHT + g.getFontMetrics().getHeight()); 109 111 if (currentMap == i) { 110 112 g.setColor(Color.BLACK); -
trunk/src/org/openstreetmap/josm/gui/conflict/pair/ConflictResolver.java
r8444 r8509 178 178 } else { 179 179 tabbedPane.setTitleAt(1, trn("Tags({0} conflict)", "Tags({0} conflicts)", newValue, newValue)); 180 tabbedPane.setToolTipTextAt(1, trn("{0} pending tag conflict to be resolved", "{0} pending tag conflicts to be resolved", newValue, newValue)); 180 tabbedPane.setToolTipTextAt(1, 181 trn("{0} pending tag conflict to be resolved", "{0} pending tag conflicts to be resolved", newValue, newValue)); 181 182 tabbedPane.setIconAt(1, mergeIncomplete); 182 183 } -
trunk/src/org/openstreetmap/josm/gui/conflict/pair/ListMerger.java
r8470 r8509 276 276 gc.gridy = 0; 277 277 lblMergedVersion = new JLabel(tr("Merged version")); 278 lblMergedVersion.setToolTipText(tr("List of merged elements. They will replace the list of my elements when the merge decisions are applied.")); 278 lblMergedVersion.setToolTipText( 279 tr("List of merged elements. They will replace the list of my elements when the merge decisions are applied.")); 279 280 add(lblMergedVersion, gc); 280 281 -
trunk/src/org/openstreetmap/josm/gui/conflict/pair/PairTable.java
r8308 r8509 16 16 private final transient ListMergeModel<? extends PrimitiveId> model; 17 17 18 public PairTable(String name, ListMergeModel<? extends PrimitiveId> model, OsmPrimitivesTableModel dm, TableColumnModel cm, ListSelectionModel sm) { 18 public PairTable(String name, ListMergeModel<? extends PrimitiveId> model, 19 OsmPrimitivesTableModel dm, TableColumnModel cm, ListSelectionModel sm) { 19 20 super(dm, cm, sm); 20 21 this.model = model; -
trunk/src/org/openstreetmap/josm/gui/conflict/pair/properties/PropertiesMerger.java
r8444 r8509 86 86 gc.gridy = 0; 87 87 JLabel lblMergedVersion = new JLabel(tr("Merged version")); 88 lblMergedVersion.setToolTipText(tr("Properties in the merged element. They will replace properties in my elements when merge decisions are applied.")); 88 lblMergedVersion.setToolTipText( 89 tr("Properties in the merged element. They will replace properties in my elements when merge decisions are applied.")); 89 90 add(lblMergedVersion, gc); 90 91 -
trunk/src/org/openstreetmap/josm/gui/conflict/tags/CombinePrimitiveResolverDialog.java
r8373 r8509 319 319 320 320 final Integer keepResolutions = numberOfKeepResolutions.get(r); 321 final Collection<Relation> resolvedRelations = Utils.firstNonNull(resolvedRelationsPerPrimitive.get(p), Collections.<Relation>emptyList()); 321 final Collection<Relation> resolvedRelations = Utils.firstNonNull( 322 resolvedRelationsPerPrimitive.get(p), Collections.<Relation>emptyList()); 322 323 if (keepResolutions <= Utils.filter(resolvedRelations, Predicates.equalTo(r)).size()) { 323 324 // old relation contains one primitive more often than the current resolution => keep the current member -
trunk/src/org/openstreetmap/josm/gui/conflict/tags/MultiValueCellRenderer.java
r7743 r8509 117 117 break; 118 118 case KEEP_ONE: 119 toolTipText = tr("Value ''{0}'' is going to be applied for key ''{1}''", decision.getChosenValue(), decision.getKey()); 119 toolTipText = tr("Value ''{0}'' is going to be applied for key ''{1}''", 120 decision.getChosenValue(), decision.getKey()); 120 121 break; 121 122 case SUM_ALL_NUMERIC: 122 toolTipText = tr("All numeric values sumed as ''{0}'' are going to be applied for key ''{1}''", decision.getChosenValue(), decision.getKey()); 123 toolTipText = tr("All numeric values sumed as ''{0}'' are going to be applied for key ''{1}''", 124 decision.getChosenValue(), decision.getKey()); 123 125 break; 124 126 case KEEP_NONE: … … 126 128 break; 127 129 case KEEP_ALL: 128 toolTipText = tr("All values joined as ''{0}'' are going to be applied for key ''{1}''", decision.getChosenValue(), decision.getKey()); 130 toolTipText = tr("All values joined as ''{0}'' are going to be applied for key ''{1}''", 131 decision.getChosenValue(), decision.getKey()); 129 132 break; 130 133 } -
trunk/src/org/openstreetmap/josm/gui/conflict/tags/MultiValueResolutionDecision.java
r8291 r8509 57 57 throw new IllegalArgumentException(MessageFormat.format("Parameter ''{0}'' must not be empty.", "tags")); 58 58 if (tags.getKeys().size() != 1) 59 throw new IllegalArgumentException(MessageFormat.format("Parameter ''{0}'' with tags for exactly one key expected. Got {1}.", "tags", tags.getKeys().size())); 59 throw new IllegalArgumentException(MessageFormat.format("Parameter ''{0}'' with tags for exactly one key expected. Got {1}.", 60 "tags", tags.getKeys().size())); 60 61 this.tags = tags; 61 62 autoDecide(); -
trunk/src/org/openstreetmap/josm/gui/conflict/tags/PasteTagsConflictResolverDialog.java
r8468 r8509 161 161 * @param targetStatistics histogram of paste targets, number of primitives of each type in the paste target 162 162 */ 163 public void populate(TagCollection tagsForAllPrimitives, Map<OsmPrimitiveType, Integer> sourceStatistics, Map<OsmPrimitiveType,Integer> targetStatistics) { 163 public void populate(TagCollection tagsForAllPrimitives, Map<OsmPrimitiveType, Integer> sourceStatistics, 164 Map<OsmPrimitiveType,Integer> targetStatistics) { 164 165 mode = Mode.RESOLVING_ONE_TAGCOLLECTION_ONLY; 165 166 tagsForAllPrimitives = tagsForAllPrimitives == null? new TagCollection() : tagsForAllPrimitives; … … 203 204 * @param targetStatistics histogram of paste targets, number of primitives of each type in the paste target 204 205 */ 205 public void populate(TagCollection tagsForNodes, TagCollection tagsForWays, TagCollection tagsForRelations, Map<OsmPrimitiveType,Integer> sourceStatistics, Map<OsmPrimitiveType, Integer> targetStatistics) { 206 public void populate(TagCollection tagsForNodes, TagCollection tagsForWays, TagCollection tagsForRelations, 207 Map<OsmPrimitiveType,Integer> sourceStatistics, Map<OsmPrimitiveType, Integer> targetStatistics) { 206 208 tagsForNodes = (tagsForNodes == null) ? new TagCollection() : tagsForNodes; 207 209 tagsForWays = (tagsForWays == null) ? new TagCollection() : tagsForWays; -
trunk/src/org/openstreetmap/josm/gui/conflict/tags/RelationMemberConflictDecision.java
r8444 r8509 22 22 RelationMember member = relation.getMember(pos); 23 23 if (member == null) 24 throw new IndexOutOfBoundsException(tr("Position {0} is out of range. Current number of members is {1}.", pos, relation.getMembersCount())); 24 throw new IndexOutOfBoundsException( 25 tr("Position {0} is out of range. Current number of members is {1}.", pos, relation.getMembersCount())); 25 26 this.relation = relation; 26 27 this.pos = pos; -
trunk/src/org/openstreetmap/josm/gui/conflict/tags/RelationMemberConflictDecisionRenderer.java
r7509 r8509 14 14 import org.openstreetmap.josm.gui.widgets.JosmComboBox; 15 15 16 public class RelationMemberConflictDecisionRenderer extends JLabel implements TableCellRenderer, ListCellRenderer<RelationMemberConflictDecisionType> { 16 public class RelationMemberConflictDecisionRenderer extends JLabel 17 implements TableCellRenderer, ListCellRenderer<RelationMemberConflictDecisionType> { 17 18 18 19 private JosmComboBox<RelationMemberConflictDecisionType> cbDecisionTypes; -
trunk/src/org/openstreetmap/josm/gui/conflict/tags/TagConflictResolverModel.java
r8444 r8509 264 264 values.remove(""); 265 265 if (values.size() == 1) { 266 // TODO: Do not suggest to keep the single value in order to avoid long highways to become tunnels+bridges+... (only if both primitives are tagged) 266 // TODO: Do not suggest to keep the single value in order to avoid long highways to become tunnels+bridges+... 267 // (only if both primitives are tagged) 267 268 decision.keepOne(values.get(0)); 268 269 } else { -
trunk/src/org/openstreetmap/josm/gui/dialogs/CommandStackDialog.java
r8387 r8509 138 138 private static class CommandCellRenderer extends DefaultTreeCellRenderer { 139 139 @Override 140 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { 140 public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, 141 boolean hasFocus) { 141 142 super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); 142 143 DefaultMutableTreeNode v = (DefaultMutableTreeNode)value; -
trunk/src/org/openstreetmap/josm/gui/dialogs/DeleteFromRelationConfirmationDialog.java
r8469 r8509 110 110 msg = tr("<html>Please confirm to remove <strong>1 object</strong> from <strong>1 relation</strong>.</html>"); 111 111 } else if (numObjectsToDelete == 1 && numParentRelations > 1) { 112 msg = tr("<html>Please confirm to remove <strong>1 object</strong> from <strong>{0} relations</strong>.</html>", numParentRelations); 112 msg = tr("<html>Please confirm to remove <strong>1 object</strong> from <strong>{0} relations</strong>.</html>", 113 numParentRelations); 113 114 } else if (numObjectsToDelete > 1 && numParentRelations == 1) { 114 msg = tr("<html>Please confirm to remove <strong>1 object</strong> from <strong>{0} relations</strong>.</html>", numParentRelations); 115 msg = tr("<html>Please confirm to remove <strong>1 object</strong> from <strong>{0} relations</strong>.</html>", 116 numParentRelations); 115 117 } else { 116 msg = tr("<html>Please confirm to remove <strong>{0} objects</strong> from <strong>{1} relations</strong>.</html>", numObjectsToDelete,numParentRelations); 118 msg = tr("<html>Please confirm to remove <strong>{0} objects</strong> from <strong>{1} relations</strong>.</html>", 119 numObjectsToDelete,numParentRelations); 117 120 } 118 121 htmlPanel.getEditorPane().setText(msg); -
trunk/src/org/openstreetmap/josm/gui/dialogs/LayerListDialog.java
r8444 r8509 635 635 */ 636 636 637 public final class ActivateLayerAction extends AbstractAction implements IEnabledStateUpdating, MapView.LayerChangeListener, MultikeyShortcutAction{ 637 public final class ActivateLayerAction extends AbstractAction 638 implements IEnabledStateUpdating, MapView.LayerChangeListener, MultikeyShortcutAction{ 638 639 private transient Layer layer; 639 640 private transient Shortcut multikeyShortcut; -
trunk/src/org/openstreetmap/josm/gui/dialogs/OsmIdSelectionDialog.java
r8496 r8509 162 162 */ 163 163 protected void restorePrimitivesHistory(HistoryComboBox cbHistory) { 164 java.util.List<String> cmtHistory = new LinkedList<>(Main.pref.getCollection(getClass().getName() + ".primitivesHistory", new LinkedList<String>())); 164 java.util.List<String> cmtHistory = new LinkedList<>( 165 Main.pref.getCollection(getClass().getName() + ".primitivesHistory", new LinkedList<String>())); 165 166 // we have to reverse the history, because ComboBoxHistory will reverse it again in addElement() 166 167 Collections.reverse(cmtHistory); -
trunk/src/org/openstreetmap/josm/gui/dialogs/RelationListDialog.java
r8444 r8509 271 271 model.setSelectedRelations(relations); 272 272 Integer i = model.getVisibleRelationIndex(relations.iterator().next()); 273 if (i != null) { // Not all relations have to be in the list (for example when the relation list is hidden, it's not updated with new relations) 273 if (i != null) { 274 // Not all relations have to be in the list 275 // (for example when the relation list is hidden, it's not updated with new relations) 274 276 displaylist.scrollRectToVisible(displaylist.getCellBounds(i, i)); 275 277 } -
trunk/src/org/openstreetmap/josm/gui/dialogs/SelectionListDialog.java
r8468 r8509 471 471 * 472 472 */ 473 private static class SelectionListModel extends AbstractListModel<OsmPrimitive> implements EditLayerChangeListener, SelectionChangedListener, DataSetListener{ 473 private static class SelectionListModel extends AbstractListModel<OsmPrimitive> 474 implements EditLayerChangeListener, SelectionChangedListener, DataSetListener { 474 475 475 476 private static final int SELECTION_HISTORY_SIZE = 10; -
trunk/src/org/openstreetmap/josm/gui/dialogs/ToggleDialog.java
r8468 r8509 223 223 * @param prefClass the preferences settings class, or null if not applicable 224 224 */ 225 public ToggleDialog(String name, String iconName, String tooltip, Shortcut shortcut, int preferredHeight, boolean defShow, Class<? extends PreferenceSetting> prefClass) { 225 public ToggleDialog(String name, String iconName, String tooltip, Shortcut shortcut, int preferredHeight, boolean defShow, 226 Class<? extends PreferenceSetting> prefClass) { 226 227 super(new BorderLayout()); 227 228 this.preferencePrefix = iconName; … … 867 868 868 869 @SafeVarargs 869 protected final Component createLayout(Component data, boolean scroll, Collection<SideButton> firstButtons, Collection<SideButton>... nextButtons) { 870 protected final Component createLayout(Component data, boolean scroll, Collection<SideButton> firstButtons, 871 Collection<SideButton>... nextButtons) { 870 872 if (scroll) { 871 873 data = new JScrollPane(data); -
trunk/src/org/openstreetmap/josm/gui/dialogs/changeset/ChangesetContentDownloadTask.java
r8291 r8509 69 69 super(tr("Downloading changeset content"), false /* don't ignore exceptions */); 70 70 if (changesetId <= 0) 71 throw new IllegalArgumentException(MessageFormat.format("Expected integer value > 0 for parameter ''{0}'', got ''{1}''", "changesetId", changesetId)); 71 throw new IllegalArgumentException( 72 MessageFormat.format("Expected integer value > 0 for parameter ''{0}'', got ''{1}''", "changesetId", changesetId)); 72 73 init(Collections.singleton(changesetId)); 73 74 } … … 95 96 super(parent, tr("Downloading changeset content"), false /* don't ignore exceptions */); 96 97 if (changesetId <= 0) 97 throw new IllegalArgumentException(MessageFormat.format("Expected integer value > 0 for parameter ''{0}'', got ''{1}''", "changesetId", changesetId)); 98 throw new IllegalArgumentException( 99 MessageFormat.format("Expected integer value > 0 for parameter ''{0}'', got ''{1}''", "changesetId", changesetId)); 98 100 init(Collections.singleton(changesetId)); 99 101 } -
trunk/src/org/openstreetmap/josm/gui/dialogs/changeset/ChangesetListCellRenderer.java
r8390 r8509 51 51 52 52 @Override 53 public Component getListCellRendererComponent(JList<? extends Changeset> list, Changeset cs, int index, boolean isSelected, boolean cellHasFocus) { 53 public Component getListCellRendererComponent(JList<? extends Changeset> list, Changeset cs, int index, boolean isSelected, 54 boolean cellHasFocus) { 54 55 renderColors(isSelected); 55 56 renderLabel(cs); -
trunk/src/org/openstreetmap/josm/gui/dialogs/changeset/query/BasicChangesetQueryPanel.java
r8444 r8509 104 104 gc.weightx = 1.0; 105 105 pnl.add(cbMyChangesetsOnly = new JCheckBox(tr("Download my changesets only")), gc); 106 cbMyChangesetsOnly.setToolTipText(tr("<html>Select to restrict the query to your changesets only.<br>Unselect to include all changesets in the query.</html>")); 106 cbMyChangesetsOnly.setToolTipText( 107 tr("<html>Select to restrict the query to your changesets only.<br>Unselect to include all changesets in the query.</html>")); 107 108 108 109 // grab remaining space … … 191 192 q = BasicQuery.valueOf(BasicQuery.class, value); 192 193 } catch(IllegalArgumentException e) { 193 Main.warn(tr("Unexpected value for preference ''{0}'', got ''{1}''. Resetting to default query.","changeset-query.basic.query", value)); 194 Main.warn(tr("Unexpected value for preference ''{0}'', got ''{1}''. Resetting to default query.", 195 "changeset-query.basic.query", value)); 194 196 q = BasicQuery.MOST_RECENT_CHANGESETS; 195 197 } -
trunk/src/org/openstreetmap/josm/gui/dialogs/properties/PropertiesDialog.java
r8470 r8509 117 117 * @author imi 118 118 */ 119 public class PropertiesDialog extends ToggleDialog implements SelectionChangedListener, MapView.EditLayerChangeListener, DataSetListenerAdapter.Listener { 119 public class PropertiesDialog extends ToggleDialog 120 implements SelectionChangedListener, MapView.EditLayerChangeListener, DataSetListenerAdapter.Listener { 120 121 121 122 /** -
trunk/src/org/openstreetmap/josm/gui/dialogs/properties/TagEditHelper.java
r8463 r8509 685 685 int count = 1; 686 686 // We store the maximum number (9) of recent tags to allow dynamic change of number of tags shown in the preferences. 687 // This implies to iterate in descending order, as the oldest elements will only be removed after we reach the maximum number and not the number of tags to show. 688 // However, as Set does not allow to iterate in descending order, we need to copy its elements into a List we can access in reverse order. 687 // This implies to iterate in descending order, as the oldest elements will only be removed after we reach the maximum 688 // number and not the number of tags to show. 689 // However, as Set does not allow to iterate in descending order, we need to copy its elements into a List we can access 690 // in reverse order. 689 691 List<Tag> tags = new LinkedList<>(recentTags.keySet()); 690 692 for (int i = tags.size()-1; i >= 0 && count <= tagsToShow; i--, count++) { … … 704 706 } 705 707 }; 706 Shortcut scShift = Shortcut.registerShortcut(actionShortcutShiftKey, tr("Apply recent tag {0}", count), KeyEvent.VK_0+count, Shortcut.CTRL_SHIFT); 708 Shortcut scShift = Shortcut.registerShortcut(actionShortcutShiftKey, tr("Apply recent tag {0}", count), 709 KeyEvent.VK_0+count, Shortcut.CTRL_SHIFT); 707 710 final JosmAction actionShift = new JosmAction(actionShortcutShiftKey, null, tr("Use this tag again"), scShift, false) { 708 711 @Override -
trunk/src/org/openstreetmap/josm/gui/dialogs/relation/DownloadRelationTask.java
r8291 r8509 77 77 for (Relation relation: relations) { 78 78 i++; 79 getProgressMonitor().setCustomText(tr("({0}/{1}): Downloading relation ''{2}''...", i,relations.size(),relation.getDisplayName(DefaultNameFormatter.getInstance()))); 79 getProgressMonitor().setCustomText(tr("({0}/{1}): Downloading relation ''{2}''...", i, relations.size(), 80 relation.getDisplayName(DefaultNameFormatter.getInstance()))); 80 81 synchronized (this) { 81 82 if (canceled) return; -
trunk/src/org/openstreetmap/josm/gui/dialogs/relation/GenericRelationEditor.java
r8505 r8509 997 997 998 998 if (enabled) { 999 putValue(SHORT_DESCRIPTION, tr("Select relation members which refer to {0} objects in the current selection",memberTableModel.getChildPrimitives(getLayer().data.getSelected()).size())); 999 putValue(SHORT_DESCRIPTION, tr("Select relation members which refer to {0} objects in the current selection", 1000 memberTableModel.getChildPrimitives(getLayer().data.getSelected()).size())); 1000 1001 } else { 1001 1002 putValue(SHORT_DESCRIPTION, tr("Select relation members which refer to objects in the current selection")); … … 1012 1013 public void tableChanged(TableModelEvent e) { 1013 1014 updateEnabledState(); 1014 1015 1015 } 1016 1016 } … … 1762 1762 1763 1763 if (hasNewInOtherLayer) { 1764 JOptionPane.showMessageDialog(Main.parent, tr("Members from paste buffer cannot be added because they are not included in current layer")); 1764 JOptionPane.showMessageDialog(Main.parent, 1765 tr("Members from paste buffer cannot be added because they are not included in current layer")); 1765 1766 return; 1766 1767 } -
trunk/src/org/openstreetmap/josm/gui/dialogs/relation/MemberTableModel.java
r8505 r8509 44 44 import org.openstreetmap.josm.gui.widgets.OsmPrimitivesTableModel; 45 45 46 public class MemberTableModel extends AbstractTableModel implements TableModelListener, SelectionChangedListener, DataSetListener, OsmPrimitivesTableModel { 46 public class MemberTableModel extends AbstractTableModel 47 implements TableModelListener, SelectionChangedListener, DataSetListener, OsmPrimitivesTableModel { 47 48 48 49 /** … … 409 410 410 411 private void addMembersAtIndex(List<? extends OsmPrimitive> primitives, int index) { 411 final Collection<TaggingPreset> presets = TaggingPreset.getMatchingPresets(EnumSet.of(TaggingPresetType.RELATION), presetHandler.getSelection().iterator().next().getKeys(), false); 412 final Collection<TaggingPreset> presets = TaggingPreset.getMatchingPresets(EnumSet.of(TaggingPresetType.RELATION), 413 presetHandler.getSelection().iterator().next().getKeys(), false); 412 414 if (primitives == null) 413 415 return; -
trunk/src/org/openstreetmap/josm/gui/dialogs/relation/RelationTreeCellRenderer.java
r6889 r8509 66 66 boolean leaf, int row, boolean hasFocus) { 67 67 68 // Hackish fix for #7056 - if name template for duplicated relation contains tags from parent, template will fail because getReffers doesn't work on primitives not yet in dataset 68 // Hackish fix for #7056 - if name template for duplicated relation contains tags from parent, 69 // template will fail because getReffers doesn't work on primitives not yet in dataset 69 70 if (!tree.isRootVisible() && tree.getModel().getRoot() == value) 70 71 return this; … … 75 76 return this; 76 77 } 77 78 78 } -
trunk/src/org/openstreetmap/josm/gui/download/BookmarkList.java
r8506 r8509 225 225 226 226 @Override 227 public Component getListCellRendererComponent(JList<? extends Bookmark> list, Bookmark value, int index, boolean isSelected, boolean cellHasFocus) { 227 public Component getListCellRendererComponent(JList<? extends Bookmark> list, Bookmark value, int index, boolean isSelected, 228 boolean cellHasFocus) { 228 229 renderColor(isSelected); 229 230 setText(value.getName()); -
trunk/src/org/openstreetmap/josm/gui/download/DownloadDialog.java
r8470 r8509 155 155 156 156 cbStartup = new JCheckBox(tr("Open this dialog on startup")); 157 cbStartup.setToolTipText(tr("<html>Autostart ''Download from OSM'' dialog every time JOSM is started.<br>You can open it manually from File menu or toolbar.</html>")); 157 cbStartup.setToolTipText( 158 tr("<html>Autostart ''Download from OSM'' dialog every time JOSM is started.<br>You can open it manually from File menu or toolbar.</html>")); 158 159 cbStartup.addActionListener(new ActionListener() { 159 160 @Override … … 168 169 169 170 if (!ExpertToggleAction.isExpert()) { 170 JLabel infoLabel = new JLabel(tr("Use left click&drag to select area, arrows or right mouse button to scroll map, wheel or +/- to zoom.")); 171 JLabel infoLabel = new JLabel( 172 tr("Use left click&drag to select area, arrows or right mouse button to scroll map, wheel or +/- to zoom.")); 171 173 pnl.add(infoLabel,GBC.eol().anchor(GBC.SOUTH).insets(0,0,0,0)); 172 174 } -
trunk/src/org/openstreetmap/josm/gui/history/HistoryBrowserModel.java
r8399 r8509 300 300 throw new IllegalStateException(tr("History not initialized yet. Failed to set reference primitive.")); 301 301 if (reference.getId() != history.getId()) 302 throw new IllegalArgumentException(tr("Failed to set reference. Reference ID {0} does not match history ID {1}.", reference.getId(), history.getId())); 302 throw new IllegalArgumentException( 303 tr("Failed to set reference. Reference ID {0} does not match history ID {1}.", reference.getId(), history.getId())); 303 304 HistoryOsmPrimitive primitive = history.getByVersion(reference.getVersion()); 304 305 if (primitive == null) 305 throw new IllegalArgumentException(tr("Failed to set reference. Reference version {0} not available in history.", reference.getVersion())); 306 throw new IllegalArgumentException( 307 tr("Failed to set reference. Reference version {0} not available in history.", reference.getVersion())); 306 308 307 309 this.reference = reference; … … 330 332 throw new IllegalStateException(tr("History not initialized yet. Failed to set current primitive.")); 331 333 if (current.getId() != history.getId()) 332 throw new IllegalArgumentException(tr("Failed to set reference. Reference ID {0} does not match history ID {1}.", current.getId(), history.getId())); 334 throw new IllegalArgumentException( 335 tr("Failed to set reference. Reference ID {0} does not match history ID {1}.", current.getId(), history.getId())); 333 336 HistoryOsmPrimitive primitive = history.getByVersion(current.getVersion()); 334 337 if (primitive == null) 335 throw new IllegalArgumentException(tr("Failed to set current primitive. Current version {0} not available in history.", current.getVersion())); 338 throw new IllegalArgumentException( 339 tr("Failed to set current primitive. Current version {0} not available in history.", current.getVersion())); 336 340 this.current = current; 337 341 initTagTableModels(); -
trunk/src/org/openstreetmap/josm/gui/io/AbstractUploadTask.java
r8342 r8509 64 64 OsmPrimitive p = layer.data.getPrimitiveById(id, type); 65 65 if (p == null) 66 throw new IllegalStateException(tr("Failed to update primitive with id {0} because current edit layer does not include such a primitive", id)); 66 throw new IllegalStateException( 67 tr("Failed to update primitive with id {0} because current edit layer does not include such a primitive", id)); 67 68 Main.worker.execute(new UpdatePrimitivesTask(layer, Collections.singleton(p))); 68 69 } -
trunk/src/org/openstreetmap/josm/gui/io/ChangesetCellRenderer.java
r8390 r8509 47 47 48 48 @Override 49 public Component getListCellRendererComponent(JList<? extends Changeset> list, Changeset cs, int index, boolean isSelected, boolean cellHasFocus) { 49 public Component getListCellRendererComponent(JList<? extends Changeset> list, Changeset cs, int index, boolean isSelected, 50 boolean cellHasFocus) { 50 51 if (isSelected) { 51 52 setForeground(UIManager.getColor("List.selectionForeground")); -
trunk/src/org/openstreetmap/josm/gui/io/ChangesetManagementPanel.java
r8308 r8509 75 75 gc.weighty = 0.0; 76 76 gc.insets = new Insets(0, 0, 5, 0); 77 add(new JMultilineLabel(tr("Please decide what changeset the data is uploaded to and whether to close the changeset after the next upload.")), gc); 77 add(new JMultilineLabel( 78 tr("Please decide what changeset the data is uploaded to and whether to close the changeset after the next upload.")), gc); 78 79 79 80 gc.gridwidth = 4; -
trunk/src/org/openstreetmap/josm/gui/io/CredentialDialog.java
r8419 r8509 44 44 public class CredentialDialog extends JDialog { 45 45 46 public static CredentialDialog getOsmApiCredentialDialog(String username, String password, String host, String saveUsernameAndPasswordCheckboxText) { 46 public static CredentialDialog getOsmApiCredentialDialog(String username, String password, String host, 47 String saveUsernameAndPasswordCheckboxText) { 47 48 CredentialDialog dialog = new CredentialDialog(saveUsernameAndPasswordCheckboxText); 48 49 if (Objects.equals(OsmApi.getOsmApi().getHost(), host)) { … … 55 56 } 56 57 57 public static CredentialDialog getHttpProxyCredentialDialog(String username, String password, String host, String saveUsernameAndPasswordCheckboxText) { 58 public static CredentialDialog getHttpProxyCredentialDialog(String username, String password, String host, 59 String saveUsernameAndPasswordCheckboxText) { 58 60 CredentialDialog dialog = new CredentialDialog(saveUsernameAndPasswordCheckboxText); 59 61 dialog.prepareForProxyCredentials(username, password); … … 311 313 lblHeading.setText( 312 314 "<html>" + tr("Authenticating at the HTTP proxy ''{0}'' failed. Please enter a valid username and a valid password.", 313 Main.pref.get(ProxyPreferencesPanel.PROXY_HTTP_HOST) + ":" + Main.pref.get(ProxyPreferencesPanel.PROXY_HTTP_PORT)) + "</html>"); 314 lblWarning.setText("<html>" + tr("Warning: depending on the authentication method the proxy server uses the password may be transferred unencrypted.") + "</html>"); 315 Main.pref.get(ProxyPreferencesPanel.PROXY_HTTP_HOST) + ":" + 316 Main.pref.get(ProxyPreferencesPanel.PROXY_HTTP_PORT)) + "</html>"); 317 lblWarning.setText("<html>" + 318 tr("Warning: depending on the authentication method the proxy server uses the password may be transferred unencrypted.") 319 + "</html>"); 315 320 } 316 321 -
trunk/src/org/openstreetmap/josm/gui/io/DownloadFileTask.java
r8470 r8509 139 139 } 140 140 } catch(MalformedURLException e) { 141 String msg = tr("Cannot download file ''{0}''. Its download link ''{1}'' is not a valid URL. Skipping download.", file.getName(), address); 141 String msg = tr("Cannot download file ''{0}''. Its download link ''{1}'' is not a valid URL. Skipping download.", 142 file.getName(), address); 142 143 Main.warn(msg); 143 144 throw new DownloadException(msg, e); -
trunk/src/org/openstreetmap/josm/gui/io/UploadLayerTask.java
r8376 r8509 94 94 if (p.isDeleted()) { 95 95 // we tried to delete an already deleted primitive. 96 //97 Main.warn(tr("Object ''{0}'' is already deleted on the server. Skipping this object and retrying to upload.",p.getDisplayName(DefaultNameFormatter.getInstance())));96 Main.warn(tr("Object ''{0}'' is already deleted on the server. Skipping this object and retrying to upload.", 97 p.getDisplayName(DefaultNameFormatter.getInstance()))); 98 98 processedPrimitives.addAll(writer.getProcessedPrimitives()); 99 99 processedPrimitives.add(p); … … 101 101 return; 102 102 } 103 // exception was thrown because we tried to *update* an already deleted 104 // primitive. We can't resolve this automatically. Re-throw exception, 105 // a conflict is going to be created later. 103 // exception was thrown because we tried to *update* an already deleted primitive. We can't resolve this automatically. 104 // Re-throw exception, a conflict is going to be created later. 106 105 throw e; 107 106 } -
trunk/src/org/openstreetmap/josm/gui/io/UploadParameterSummaryPanel.java
r8426 r8509 89 89 ); 90 90 } else if (numRequests > 1){ 91 msg = tr("Uploading <strong>{0} objects</strong> to <strong>1 changeset</strong> using <strong>{1} requests</strong>", numObjects, numRequests); 91 msg = tr("Uploading <strong>{0} objects</strong> to <strong>1 changeset</strong> using <strong>{1} requests</strong>", 92 numObjects, numRequests); 92 93 } 93 94 msg = msg + " (<a href=\"urn:advanced-configuration\">" + tr("advanced configuration") + "</a>)"; … … 98 99 numObjects, maxChunkSize, OsmApi.getOsmApi().getBaseUrl()); 99 100 } else if (numRequests > 1){ 100 msg = tr("Uploading <strong>{0} objects</strong> to <strong>multiple changesets</strong> using <strong>{1} requests</strong>", numObjects, numRequests); 101 msg = tr("Uploading <strong>{0} objects</strong> to <strong>multiple changesets</strong> using <strong>{1} requests</strong>", 102 numObjects, numRequests); 101 103 msg = msg + " (<a href=\"urn:advanced-configuration\">" + tr("advanced configuration") + "</a>)"; 102 104 } -
trunk/src/org/openstreetmap/josm/gui/io/UploadStrategySelectionPanel.java
r8444 r8509 189 189 gc.anchor = GridBagConstraints.FIRST_LINE_START; 190 190 gc.weightx = 1.0; 191 pnlMultiChangesetPolicyPanel.add(lblMultiChangesetPoliciesHeader = new JMultilineLabel(tr("<html>There are <strong>multiple changesets</strong> necessary in order to upload {0} objects. Which strategy do you want to use?</html>", numUploadedObjects)), gc); 191 pnlMultiChangesetPolicyPanel.add(lblMultiChangesetPoliciesHeader = new JMultilineLabel( 192 tr("<html>There are <strong>multiple changesets</strong> necessary in order to upload {0} objects. Which strategy do you want to use?</html>", 193 numUploadedObjects)), gc); 192 194 gc.gridy = 1; 193 pnlMultiChangesetPolicyPanel.add(rbFillOneChangeset = new JRadioButton(tr("Fill up one changeset and return to the Upload Dialog")),gc); 194 gc.gridy = 2; 195 pnlMultiChangesetPolicyPanel.add(rbUseMultipleChangesets = new JRadioButton(tr("Open and use as many new changesets as necessary")),gc); 195 pnlMultiChangesetPolicyPanel.add(rbFillOneChangeset = new JRadioButton( 196 tr("Fill up one changeset and return to the Upload Dialog")), gc); 197 gc.gridy = 2; 198 pnlMultiChangesetPolicyPanel.add(rbUseMultipleChangesets = new JRadioButton( 199 tr("Open and use as many new changesets as necessary")), gc); 196 200 197 201 ButtonGroup bgMultiChangesetPolicies = new ButtonGroup(); … … 329 333 lblNumRequests.get(UploadStrategy.SINGLE_REQUEST_STRATEGY).setVisible(false); 330 334 331 lblMultiChangesetPoliciesHeader.setText(tr("<html>There are <strong>multiple changesets</strong> necessary in order to upload {0} objects. Which strategy do you want to use?</html>", numUploadedObjects)); 335 lblMultiChangesetPoliciesHeader.setText( 336 tr("<html>There are <strong>multiple changesets</strong> necessary in order to upload {0} objects. Which strategy do you want to use?</html>", 337 numUploadedObjects)); 332 338 if (!rbFillOneChangeset.isSelected() && !rbUseMultipleChangesets.isSelected()) { 333 339 rbUseMultipleChangesets.setSelected(true); … … 410 416 setErrorFeedback(tfChunkSize, tr("Illegal chunk size <= 0. Please enter an integer > 1")); 411 417 } else if (maxChunkSize > 0 && chunkSize > maxChunkSize) { 412 setErrorFeedback(tfChunkSize, tr("Chunk size {0} exceeds max. changeset size {1} for server ''{2}''", chunkSize, maxChunkSize, OsmApi.getOsmApi().getBaseUrl())); 418 setErrorFeedback(tfChunkSize, tr("Chunk size {0} exceeds max. changeset size {1} for server ''{2}''", 419 chunkSize, maxChunkSize, OsmApi.getOsmApi().getBaseUrl())); 413 420 } else { 414 421 clearErrorFeedback(tfChunkSize, tr("Please enter an integer > 1")); … … 416 423 417 424 if (maxChunkSize > 0 && chunkSize > maxChunkSize) { 418 setErrorFeedback(tfChunkSize, tr("Chunk size {0} exceeds max. changeset size {1} for server ''{2}''", chunkSize, maxChunkSize, OsmApi.getOsmApi().getBaseUrl())); 425 setErrorFeedback(tfChunkSize, tr("Chunk size {0} exceeds max. changeset size {1} for server ''{2}''", 426 chunkSize, maxChunkSize, OsmApi.getOsmApi().getBaseUrl())); 419 427 } 420 428 } catch(NumberFormatException e) { 421 setErrorFeedback(tfChunkSize, tr("Value ''{0}'' is not a number. Please enter an integer > 1", tfChunkSize.getText().trim())); 429 setErrorFeedback(tfChunkSize, tr("Value ''{0}'' is not a number. Please enter an integer > 1", 430 tfChunkSize.getText().trim())); 422 431 } finally { 423 432 updateNumRequestsLabels(); -
trunk/src/org/openstreetmap/josm/gui/layer/NoteLayer.java
r8503 r8509 146 146 147 147 g.setColor(ColorHelper.html2color(Main.pref.get("color.selected"))); 148 g.drawRect(p.x - (NotesDialog.ICON_SMALL_SIZE / 2), p.y - NotesDialog.ICON_SMALL_SIZE, NotesDialog.ICON_SMALL_SIZE - 1, NotesDialog.ICON_SMALL_SIZE - 1); 148 g.drawRect(p.x - (NotesDialog.ICON_SMALL_SIZE / 2), p.y - NotesDialog.ICON_SMALL_SIZE, 149 NotesDialog.ICON_SMALL_SIZE - 1, NotesDialog.ICON_SMALL_SIZE - 1); 149 150 150 151 int tx = p.x + (NotesDialog.ICON_SMALL_SIZE / 2) + 5; -
trunk/src/org/openstreetmap/josm/gui/layer/OsmDataLayer.java
r8394 r8509 908 908 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")} 909 909 ); 910 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?")); 910 dialog.setContent( 911 tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?")); 911 912 dialog.setButtonIcons(new String[] {"save", "cancel"}); 912 913 return dialog.showDialog().getValue(); -
trunk/src/org/openstreetmap/josm/gui/layer/TMSLayer.java
r8470 r8509 129 129 } 130 130 131 private final class ShowTileInfoAction extends AbstractAction { 132 private ShowTileInfoAction() { 133 super(tr("Show Tile Info")); 134 } 135 136 private String getSizeString(int size) { 137 return new StringBuilder().append(size).append("x").append(size).toString(); 138 } 139 140 private JTextField createTextField(String text) { 141 JTextField ret = new JTextField(text); 142 ret.setEditable(false); 143 ret.setBorder(BorderFactory.createEmptyBorder()); 144 return ret; 145 } 146 147 @Override 148 public void actionPerformed(ActionEvent ae) { 149 if (clickedTile != null) { 150 ExtendedDialog ed = new ExtendedDialog(Main.parent, tr("Tile Info"), new String[]{tr("OK")}); 151 JPanel panel = new JPanel(new GridBagLayout()); 152 Rectangle displaySize = tileToRect(clickedTile); 153 String url = ""; 154 try { 155 url = clickedTile.getUrl(); 156 } catch (IOException e) { 157 // silence exceptions 158 } 159 160 String[][] content = { 161 {"Tile name", clickedTile.getKey()}, 162 {"Tile url", url}, 163 {"Tile size", getSizeString(clickedTile.getTileSource().getTileSize()) }, 164 {"Tile display size", new StringBuilder().append(displaySize.width).append("x").append(displaySize.height).toString()}, 165 }; 166 167 for (String[] entry: content) { 168 panel.add(new JLabel(tr(entry[0]) + ":"), GBC.std()); 169 panel.add(GBC.glue(5,0), GBC.std()); 170 panel.add(createTextField(entry[1]), GBC.eol().fill(GBC.HORIZONTAL)); 171 } 172 173 for (Entry<String, String> e: clickedTile.getMetadata().entrySet()) { 174 panel.add(new JLabel(tr("Metadata ") + tr(e.getKey()) + ":"), GBC.std()); 175 panel.add(GBC.glue(5,0), GBC.std()); 176 String value = e.getValue(); 177 if ("lastModification".equals(e.getKey()) || "expirationTime".equals(e.getKey())) { 178 value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(value))); 179 } 180 panel.add(createTextField(value), GBC.eol().fill(GBC.HORIZONTAL)); 181 } 182 ed.setIcon(JOptionPane.INFORMATION_MESSAGE); 183 ed.setContent(panel); 184 ed.showDialog(); 185 } 186 } 187 } 188 131 189 /** 132 190 * Interface for creating TileLoaders, ie. classes responsible for loading tiles on map … … 537 595 })); 538 596 539 tileOptionMenu.add(new JMenuItem(new AbstractAction( 540 tr("Show Tile Info")) { 541 private String getSizeString(int size) { 542 StringBuilder ret = new StringBuilder(); 543 return ret.append(size).append("x").append(size).toString(); 544 } 545 546 private JTextField createTextField(String text) { 547 JTextField ret = new JTextField(text); 548 ret.setEditable(false); 549 ret.setBorder(BorderFactory.createEmptyBorder()); 550 return ret; 551 } 552 @Override 553 public void actionPerformed(ActionEvent ae) { 554 if (clickedTile != null) { 555 ExtendedDialog ed = new ExtendedDialog(Main.parent, tr("Tile Info"), new String[]{tr("OK")}); 556 JPanel panel = new JPanel(new GridBagLayout()); 557 Rectangle displaySize = tileToRect(clickedTile); 558 String url = ""; 559 try { 560 url = clickedTile.getUrl(); 561 } catch (IOException e) { 562 // silence exceptions 563 } 564 565 String[][] content = { 566 {"Tile name", clickedTile.getKey()}, 567 {"Tile url", url}, 568 {"Tile size", getSizeString(clickedTile.getTileSource().getTileSize()) }, 569 {"Tile display size", new StringBuilder().append(displaySize.width).append("x").append(displaySize.height).toString()}, 570 }; 571 572 for (String[] entry: content) { 573 panel.add(new JLabel(tr(entry[0]) + ":"), GBC.std()); 574 panel.add(GBC.glue(5,0), GBC.std()); 575 panel.add(createTextField(entry[1]), GBC.eol().fill(GBC.HORIZONTAL)); 576 } 577 578 for (Entry<String, String> e: clickedTile.getMetadata().entrySet()) { 579 panel.add(new JLabel(tr("Metadata ") + tr(e.getKey()) + ":"), GBC.std()); 580 panel.add(GBC.glue(5,0), GBC.std()); 581 String value = e.getValue(); 582 if ("lastModification".equals(e.getKey()) || "expirationTime".equals(e.getKey())) { 583 value = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(Long.parseLong(value))); 584 } 585 panel.add(createTextField(value), GBC.eol().fill(GBC.HORIZONTAL)); 586 587 } 588 ed.setIcon(JOptionPane.INFORMATION_MESSAGE); 589 ed.setContent(panel); 590 ed.showDialog(); 591 } 592 } 593 })); 597 tileOptionMenu.add(new JMenuItem(new ShowTileInfoAction())); 594 598 595 599 tileOptionMenu.add(new JMenuItem(new AbstractAction( -
trunk/src/org/openstreetmap/josm/gui/layer/geoimage/CorrelateGpxWithImages.java
r8506 r8509 105 105 } 106 106 107 private final class SyncDialogWindowListener extends WindowAdapter { 108 private static final int CANCEL = -1; 109 private static final int DONE = 0; 110 private static final int AGAIN = 1; 111 private static final int NOTHING = 2; 112 113 private int checkAndSave() { 114 if (syncDialog.isVisible()) 115 // nothing happened: JOSM was minimized or similar 116 return NOTHING; 117 int answer = syncDialog.getValue(); 118 if(answer != 1) 119 return CANCEL; 120 121 // Parse values again, to display an error if the format is not recognized 122 try { 123 timezone = parseTimezone(tfTimezone.getText().trim()); 124 } catch (ParseException e) { 125 JOptionPane.showMessageDialog(Main.parent, e.getMessage(), 126 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE); 127 return AGAIN; 128 } 129 130 try { 131 delta = parseOffset(tfOffset.getText().trim()); 132 } catch (ParseException e) { 133 JOptionPane.showMessageDialog(Main.parent, e.getMessage(), 134 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE); 135 return AGAIN; 136 } 137 138 if (lastNumMatched == 0 && new ExtendedDialog( 139 Main.parent, 140 tr("Correlate images with GPX track"), 141 new String[] {tr("OK"), tr("Try Again")}). 142 setContent(tr("No images could be matched!")). 143 setButtonIcons(new String[] {"ok", "dialogs/refresh"}). 144 showDialog().getValue() == 2) 145 return AGAIN; 146 return DONE; 147 } 148 149 @Override 150 public void windowDeactivated(WindowEvent e) { 151 int result = checkAndSave(); 152 switch (result) { 153 case NOTHING: 154 break; 155 case CANCEL: 156 if (yLayer != null) { 157 for (ImageEntry ie : yLayer.data) { 158 ie.tmp = null; 159 } 160 yLayer.updateBufferAndRepaint(); 161 } 162 break; 163 case AGAIN: 164 actionPerformed(null); 165 break; 166 case DONE: 167 Main.pref.put("geoimage.timezone", formatTimezone(timezone)); 168 Main.pref.put("geoimage.delta", Long.toString(delta * 1000)); 169 Main.pref.put("geoimage.showThumbs", yLayer.useThumbs); 170 171 yLayer.useThumbs = cbShowThumbs.isSelected(); 172 yLayer.startLoadThumbs(); 173 174 // Search whether an other layer has yet defined some bounding box. 175 // If none, we'll zoom to the bounding box of the layer with the photos. 176 boolean boundingBoxedLayerFound = false; 177 for (Layer l: Main.map.mapView.getAllLayers()) { 178 if (l != yLayer) { 179 BoundingXYVisitor bbox = new BoundingXYVisitor(); 180 l.visitBoundingBox(bbox); 181 if (bbox.getBounds() != null) { 182 boundingBoxedLayerFound = true; 183 break; 184 } 185 } 186 } 187 if (!boundingBoxedLayerFound) { 188 BoundingXYVisitor bbox = new BoundingXYVisitor(); 189 yLayer.visitBoundingBox(bbox); 190 Main.map.mapView.zoomTo(bbox); 191 } 192 193 for (ImageEntry ie : yLayer.data) { 194 ie.applyTmp(); 195 } 196 197 yLayer.updateBufferAndRepaint(); 198 199 break; 200 default: 201 throw new IllegalStateException(); 202 } 203 } 204 } 205 107 206 private static class GpxDataWrapper { 108 207 private String name; … … 663 762 syncDialog.setContentPane(outerPanel); 664 763 syncDialog.pack(); 665 syncDialog.addWindowListener(new WindowAdapter() { 666 private static final int CANCEL = -1; 667 private static final int DONE = 0; 668 private static final int AGAIN = 1; 669 private static final int NOTHING = 2; 670 private int checkAndSave() { 671 if (syncDialog.isVisible()) 672 // nothing happened: JOSM was minimized or similar 673 return NOTHING; 674 int answer = syncDialog.getValue(); 675 if(answer != 1) 676 return CANCEL; 677 678 // Parse values again, to display an error if the format is not recognized 679 try { 680 timezone = parseTimezone(tfTimezone.getText().trim()); 681 } catch (ParseException e) { 682 JOptionPane.showMessageDialog(Main.parent, e.getMessage(), 683 tr("Invalid timezone"), JOptionPane.ERROR_MESSAGE); 684 return AGAIN; 685 } 686 687 try { 688 delta = parseOffset(tfOffset.getText().trim()); 689 } catch (ParseException e) { 690 JOptionPane.showMessageDialog(Main.parent, e.getMessage(), 691 tr("Invalid offset"), JOptionPane.ERROR_MESSAGE); 692 return AGAIN; 693 } 694 695 if (lastNumMatched == 0 && new ExtendedDialog( 696 Main.parent, 697 tr("Correlate images with GPX track"), 698 new String[] {tr("OK"), tr("Try Again")}). 699 setContent(tr("No images could be matched!")). 700 setButtonIcons(new String[] {"ok", "dialogs/refresh"}). 701 showDialog().getValue() == 2) 702 return AGAIN; 703 return DONE; 704 } 705 706 @Override 707 public void windowDeactivated(WindowEvent e) { 708 int result = checkAndSave(); 709 switch (result) { 710 case NOTHING: 711 break; 712 case CANCEL: 713 if (yLayer != null) { 714 for (ImageEntry ie : yLayer.data) { 715 ie.tmp = null; 716 } 717 yLayer.updateBufferAndRepaint(); 718 } 719 break; 720 case AGAIN: 721 actionPerformed(null); 722 break; 723 case DONE: 724 Main.pref.put("geoimage.timezone", formatTimezone(timezone)); 725 Main.pref.put("geoimage.delta", Long.toString(delta * 1000)); 726 Main.pref.put("geoimage.showThumbs", yLayer.useThumbs); 727 728 yLayer.useThumbs = cbShowThumbs.isSelected(); 729 yLayer.startLoadThumbs(); 730 731 // Search whether an other layer has yet defined some bounding box. 732 // If none, we'll zoom to the bounding box of the layer with the photos. 733 boolean boundingBoxedLayerFound = false; 734 for (Layer l: Main.map.mapView.getAllLayers()) { 735 if (l != yLayer) { 736 BoundingXYVisitor bbox = new BoundingXYVisitor(); 737 l.visitBoundingBox(bbox); 738 if (bbox.getBounds() != null) { 739 boundingBoxedLayerFound = true; 740 break; 741 } 742 } 743 } 744 if (!boundingBoxedLayerFound) { 745 BoundingXYVisitor bbox = new BoundingXYVisitor(); 746 yLayer.visitBoundingBox(bbox); 747 Main.map.mapView.zoomTo(bbox); 748 } 749 750 for (ImageEntry ie : yLayer.data) { 751 ie.applyTmp(); 752 } 753 754 yLayer.updateBufferAndRepaint(); 755 756 break; 757 default: 758 throw new IllegalStateException(); 759 } 760 } 761 }); 764 syncDialog.addWindowListener(new SyncDialogWindowListener()); 762 765 syncDialog.showDialog(); 763 766 } -
trunk/src/org/openstreetmap/josm/gui/layer/geoimage/ImageViewerDialog.java
r8444 r8509 107 107 btnDelete.getActionMap().put(DELETE_TEXT, delAction); 108 108 109 ImageAction delFromDiskAction = new ImageAction(COMMAND_REMOVE_FROM_DISK, ImageProvider.get("dialogs", "geoimage/deletefromdisk"), tr("Delete image file from disk")); 109 ImageAction delFromDiskAction = new ImageAction(COMMAND_REMOVE_FROM_DISK, 110 ImageProvider.get("dialogs", "geoimage/deletefromdisk"), tr("Delete image file from disk")); 110 111 JButton btnDeleteFromDisk = new JButton(delFromDiskAction); 111 112 btnDeleteFromDisk.setPreferredSize(buttonDim); … … 149 150 ); 150 151 151 JToggleButton tbCentre = new JToggleButton(new ImageAction(COMMAND_CENTERVIEW, ImageProvider.get("dialogs", "centreview"), tr("Center view"))); 152 JToggleButton tbCentre = new JToggleButton(new ImageAction(COMMAND_CENTERVIEW, 153 ImageProvider.get("dialogs", "centreview"), tr("Center view"))); 152 154 tbCentre.setPreferredSize(buttonDim); 153 155 154 JButton btnZoomBestFit = new JButton(new ImageAction(COMMAND_ZOOM, ImageProvider.get("dialogs", "zoom-best-fit"), tr("Zoom best fit and 1:1"))); 156 JButton btnZoomBestFit = new JButton(new ImageAction(COMMAND_ZOOM, 157 ImageProvider.get("dialogs", "zoom-best-fit"), tr("Zoom best fit and 1:1"))); 155 158 btnZoomBestFit.setPreferredSize(buttonDim); 156 159 157 btnCollapse = new JButton(new ImageAction(COMMAND_COLLAPSE, ImageProvider.get("dialogs", "collapse"), tr("Move dialog to the side pane"))); 160 btnCollapse = new JButton(new ImageAction(COMMAND_COLLAPSE, 161 ImageProvider.get("dialogs", "collapse"), tr("Move dialog to the side pane"))); 158 162 btnCollapse.setPreferredSize(new Dimension(20,20)); 159 163 btnCollapse.setAlignmentY(Component.TOP_ALIGNMENT); -
trunk/src/org/openstreetmap/josm/gui/layer/gpx/ChooseTrackVisibilityAction.java
r8308 r8509 253 253 msg.add(dateFilter, GBC.eol().insets(0,0,10,0).fill(GBC.HORIZONTAL)); 254 254 255 msg.add(new JLabel(tr("<html>Select all tracks that you want to be displayed. You can drag select a " + "range of tracks or use CTRL+Click to select specific ones. The map is updated live in the " + "background. Open the URLs by double clicking them.</html>")), GBC.eop().fill(GBC.HORIZONTAL)); 255 msg.add(new JLabel(tr("<html>Select all tracks that you want to be displayed. You can drag select a range of tracks or use CTRL+Click to select specific ones. The map is updated live in the background. Open the URLs by double clicking them.</html>")), 256 GBC.eop().fill(GBC.HORIZONTAL)); 256 257 // build table 257 258 final boolean[] trackVisibilityBackup = layer.trackVisibility.clone(); -
trunk/src/org/openstreetmap/josm/gui/layer/gpx/ConvertToDataLayerAction.java
r8308 r8509 43 43 public void actionPerformed(ActionEvent e) { 44 44 JPanel msg = new JPanel(new GridBagLayout()); 45 msg.add(new JLabel(tr("<html>Upload of unprocessed GPS data as map data is considered harmful.<br>If you want to upload traces, look here:</html>")), GBC.eol()); 45 msg.add(new JLabel( 46 tr("<html>Upload of unprocessed GPS data as map data is considered harmful.<br>If you want to upload traces, look here:</html>")), 47 GBC.eol()); 46 48 msg.add(new UrlLabel(Main.getOSMWebsite() + "/traces", 2), GBC.eop()); 47 if (!ConditionalOptionPaneUtil.showConfirmationDialog("convert_to_data", Main.parent, msg, tr("Warning"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, JOptionPane.OK_OPTION)) { 49 if (!ConditionalOptionPaneUtil.showConfirmationDialog("convert_to_data", Main.parent, msg, tr("Warning"), 50 JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, JOptionPane.OK_OPTION)) { 48 51 return; 49 52 } -
trunk/src/org/openstreetmap/josm/gui/layer/gpx/CustomizeDrawingAction.java
r8308 r8509 88 88 scrollpane.setPreferredSize(new Dimension(panel.getPreferredSize().width, Math.min(panel.getPreferredSize().height, 450))); 89 89 } 90 int answer = JOptionPane.showConfirmDialog(Main.parent, scrollpane, tr("Customize track drawing"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); 90 int answer = JOptionPane.showConfirmDialog(Main.parent, scrollpane, tr("Customize track drawing"), 91 JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE); 91 92 if (answer == JOptionPane.CANCEL_OPTION || answer == JOptionPane.CLOSED_OPTION) { 92 93 return; -
trunk/src/org/openstreetmap/josm/gui/layer/gpx/ImportAudioAction.java
r8404 r8509 58 58 59 59 private void warnCantImportIntoServerLayer(GpxLayer layer) { 60 String msg = tr("<html>The data in the GPX layer ''{0}'' has been downloaded from the server.<br>" + "Because its way points do not include a timestamp we cannot correlate them with audio data.</html>", layer.getName()); 61 HelpAwareOptionPane.showOptionDialog(Main.parent, msg, tr("Import not possible"), JOptionPane.WARNING_MESSAGE, ht("/Action/ImportAudio#CantImportIntoGpxLayerFromServer")); 60 String msg = tr("<html>The data in the GPX layer ''{0}'' has been downloaded from the server.<br>Because its way points do not include a timestamp we cannot correlate them with audio data.</html>", 61 layer.getName()); 62 HelpAwareOptionPane.showOptionDialog(Main.parent, msg, tr("Import not possible"), 63 JOptionPane.WARNING_MESSAGE, ht("/Action/ImportAudio#CantImportIntoGpxLayerFromServer")); 62 64 } 63 65 … … 79 81 } 80 82 }; 81 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true, true, null, filter, JFileChooser.FILES_ONLY, "markers.lastaudiodirectory"); 83 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(true, true, null, filter, 84 JFileChooser.FILES_ONLY, "markers.lastaudiodirectory"); 82 85 if (fc != null) { 83 86 File[] sel = fc.getSelectedFiles(); -
trunk/src/org/openstreetmap/josm/gui/layer/gpx/ImportImagesAction.java
r8404 r8509 34 34 35 35 private void warnCantImportIntoServerLayer(GpxLayer layer) { 36 String msg = tr("<html>The data in the GPX layer ''{0}'' has been downloaded from the server.<br>" + "Because its way points do not include a timestamp we cannot correlate them with images.</html>", layer.getName()); 37 HelpAwareOptionPane.showOptionDialog(Main.parent, msg, tr("Import not possible"), JOptionPane.WARNING_MESSAGE, ht("/Action/ImportImages#CantImportIntoGpxLayerFromServer")); 36 String msg = tr("<html>The data in the GPX layer ''{0}'' has been downloaded from the server.<br>Because its way points do not include a timestamp we cannot correlate them with images.</html>", 37 layer.getName()); 38 HelpAwareOptionPane.showOptionDialog(Main.parent, msg, tr("Import not possible"), 39 JOptionPane.WARNING_MESSAGE, ht("/Action/ImportImages#CantImportIntoGpxLayerFromServer")); 38 40 } 39 41 -
trunk/src/org/openstreetmap/josm/gui/layer/markerlayer/Marker.java
r8444 r8509 184 184 public Marker createMarker(WayPoint wpt, File relativePath, MarkerLayer parentLayer, double time, double offset) { 185 185 String uri = null; 186 // cheapest way to check whether "link" object exists and is a non-empty 187 // collection of GpxLink objects... 186 // cheapest way to check whether "link" object exists and is a non-empty collection of GpxLink objects... 188 187 Collection<GpxLink> links = wpt.<GpxLink>getCollection(GpxConstants.META_LINKS); 189 188 if (links != null) { … … 206 205 } 207 206 207 String urlString = url == null ? "" : url.toString(); 208 208 if (url == null) { 209 209 String symbolName = wpt.getString("symbol"); … … 212 212 } 213 213 return new Marker(wpt.getCoor(), wpt, symbolName, parentLayer, time, offset); 214 } else if (url .toString().endsWith(".wav")) {214 } else if (urlString.endsWith(".wav")) { 215 215 AudioMarker audioMarker = new AudioMarker(wpt.getCoor(), wpt, url, parentLayer, time, offset); 216 216 Extensions exts = (Extensions) wpt.get(GpxConstants.META_EXTENSIONS); 217 217 if (exts != null && exts.containsKey("offset")) { 218 218 try { 219 double syncOffset = Double.parseDouble(exts.get("sync-offset")); 220 audioMarker.syncOffset = syncOffset; 219 audioMarker.syncOffset = Double.parseDouble(exts.get("sync-offset")); 221 220 } catch (NumberFormatException nfe) { 222 221 Main.warn(nfe); … … 224 223 } 225 224 return audioMarker; 226 } else if (url .toString().endsWith(".png") || url.toString().endsWith(".jpg") || url.toString().endsWith(".jpeg") || url.toString().endsWith(".gif")) {225 } else if (urlString.endsWith(".png") || urlString.endsWith(".jpg") || urlString.endsWith(".jpeg") || urlString.endsWith(".gif")) { 227 226 return new ImageMarker(wpt.getCoor(), url, parentLayer, time, offset); 228 227 } else { … … 280 279 private boolean erroneous = false; 281 280 282 public Marker(LatLon ll, TemplateEngineDataProvider dataProvider, String iconName, MarkerLayer parentLayer, double time, double offset) { 281 public Marker(LatLon ll, TemplateEngineDataProvider dataProvider, String iconName, MarkerLayer parentLayer, 282 double time, double offset) { 283 283 this(ll, dataProvider, null, iconName, parentLayer, time, offset); 284 284 } … … 288 288 } 289 289 290 private Marker(LatLon ll, TemplateEngineDataProvider dataProvider, String text, String iconName, MarkerLayer parentLayer, double time, double offset) { 290 private Marker(LatLon ll, TemplateEngineDataProvider dataProvider, String text, String iconName, MarkerLayer parentLayer, 291 double time, double offset) { 291 292 timeFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); 292 293 setCoor(ll); -
trunk/src/org/openstreetmap/josm/gui/mappaint/BoxTextElemStyle.java
r8261 r8509 87 87 public VerticalTextAlignment vAlign; 88 88 89 public BoxTextElemStyle(Cascade c, TextElement text, BoxProvider boxProvider, Rectangle box, HorizontalTextAlignment hAlign, VerticalTextAlignment vAlign) { 89 public BoxTextElemStyle(Cascade c, TextElement text, BoxProvider boxProvider, Rectangle box, 90 HorizontalTextAlignment hAlign, VerticalTextAlignment vAlign) { 90 91 super(c, 5f); 91 92 CheckParameterUtil.ensureParameterNotNull(text); -
trunk/src/org/openstreetmap/josm/gui/mappaint/LineElemStyle.java
r8393 r8509 55 55 } 56 56 57 protected LineElemStyle(Cascade c, float default_major_z_index, BasicStroke line, Color color, BasicStroke dashesLine, Color dashesBackground, float offset, float realWidth) { 57 protected LineElemStyle(Cascade c, float default_major_z_index, BasicStroke line, Color color, BasicStroke dashesLine, 58 Color dashesBackground, float offset, float realWidth) { 58 59 super(c, default_major_z_index); 59 60 this.line = line; -
trunk/src/org/openstreetmap/josm/gui/mappaint/NodeElemStyle.java
r8365 r8509 92 92 93 93 public static final StyleList DEFAULT_NODE_STYLELIST = new StyleList(NodeElemStyle.SIMPLE_NODE_ELEMSTYLE); 94 public static final StyleList DEFAULT_NODE_STYLELIST_TEXT = new StyleList(NodeElemStyle.SIMPLE_NODE_ELEMSTYLE, BoxTextElemStyle.SIMPLE_NODE_TEXT_ELEMSTYLE); 94 public static final StyleList DEFAULT_NODE_STYLELIST_TEXT = new StyleList(NodeElemStyle.SIMPLE_NODE_ELEMSTYLE, 95 BoxTextElemStyle.SIMPLE_NODE_TEXT_ELEMSTYLE); 95 96 96 97 protected NodeElemStyle(Cascade c, MapImage mapImage, Symbol symbol, float default_major_z_index, RotationAngle rotationAngle) { -
trunk/src/org/openstreetmap/josm/gui/mappaint/StyleCache.java
r8416 r8509 25 25 private final List<StyleList> data; 26 26 27 private static final Storage<StyleCache> internPool = new Storage<>(); // TODO: clean up the intern pool from time to time (after purge or layer removal) 27 // TODO: clean up the intern pool from time to time (after purge or layer removal) 28 private static final Storage<StyleCache> internPool = new Storage<>(); 28 29 29 30 public static final StyleCache EMPTY_STYLECACHE = (new StyleCache()).intern(); -
trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/MapCSSStyleSource.java
r8432 r8509 69 69 * @since 6867 70 70 */ 71 public static final String MAPCSS_STYLE_MIME_TYPES = "text/x-mapcss, text/mapcss, text/css; q=0.9, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5"; 71 public static final String MAPCSS_STYLE_MIME_TYPES = 72 "text/x-mapcss, text/mapcss, text/css; q=0.9, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5"; 72 73 73 74 // all rules … … 521 522 backgroundColorOverride = c.get("background-color", null, Color.class); 522 523 if (backgroundColorOverride != null) { 523 Main.warn(tr("Detected deprecated ''{0}'' in ''{1}'' which will be removed shortly. Use ''{2}'' instead.", "canvas{background-color}", url, "fill-color")); 524 Main.warn(tr("Detected deprecated ''{0}'' in ''{1}'' which will be removed shortly. Use ''{2}'' instead.", 525 "canvas{background-color}", url, "fill-color")); 524 526 } 525 527 } -
trunk/src/org/openstreetmap/josm/gui/mappaint/mapcss/Selector.java
r8494 r8509 257 257 public void visit(Way w) { 258 258 if (e.child == null && left.matches(new Environment(w))) { 259 if (e.osm instanceof Way && Geometry.PolygonIntersection.CROSSING.equals(Geometry.polygonIntersection(w.getNodes(), ((Way) e.osm).getNodes()))) { 259 if (e.osm instanceof Way && Geometry.PolygonIntersection.CROSSING.equals( 260 Geometry.polygonIntersection(w.getNodes(), ((Way) e.osm).getNodes()))) { 260 261 e.child = w; 261 262 } … … 274 275 if (e.child == null && left.matches(new Environment(n))) { 275 276 if (e.osm instanceof Way && Geometry.nodeInsidePolygon(n, ((Way) e.osm).getNodes()) 276 || e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() && Geometry.isNodeInsideMultiPolygon(n, (Relation) e.osm, null)) { 277 || e.osm instanceof Relation && ( 278 (Relation) e.osm).isMultipolygon() && Geometry.isNodeInsideMultiPolygon(n, (Relation) e.osm, null)) { 277 279 e.child = n; 278 280 } … … 283 285 public void visit(Way w) { 284 286 if (e.child == null && left.matches(new Environment(w))) { 285 if (e.osm instanceof Way && Geometry.PolygonIntersection.FIRST_INSIDE_SECOND.equals(Geometry.polygonIntersection(w.getNodes(), ((Way) e.osm).getNodes())) 286 || e.osm instanceof Relation && ((Relation) e.osm).isMultipolygon() && Geometry.isPolygonInsideMultiPolygon(w.getNodes(), (Relation) e.osm, null)) { 287 if (e.osm instanceof Way && Geometry.PolygonIntersection.FIRST_INSIDE_SECOND.equals( 288 Geometry.polygonIntersection(w.getNodes(), ((Way) e.osm).getNodes())) 289 || e.osm instanceof Relation && ( 290 (Relation) e.osm).isMultipolygon() 291 && Geometry.isPolygonInsideMultiPolygon(w.getNodes(), (Relation) e.osm, null)) { 287 292 e.child = w; 288 293 } -
trunk/src/org/openstreetmap/josm/gui/mappaint/xml/XmlStyleSource.java
r8395 r8509 40 40 * @since 6867 41 41 */ 42 public static final String XML_STYLE_MIME_TYPES = "application/xml, text/xml, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5"; 42 public static final String XML_STYLE_MIME_TYPES = 43 "application/xml, text/xml, text/plain; q=0.8, application/zip, application/octet-stream; q=0.5"; 43 44 44 45 protected final Map<String, IconPrototype> icons = new HashMap<>(); … … 91 92 logError(e); 92 93 } catch (SAXParseException e) { 93 Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: [{1}:{2}] {3}", url, e.getLineNumber(), e.getColumnNumber(), e.getMessage())); 94 Main.warn(tr("Failed to parse Mappaint styles from ''{0}''. Error was: [{1}:{2}] {3}", 95 url, e.getLineNumber(), e.getColumnNumber(), e.getMessage())); 94 96 Main.error(e); 95 97 logError(e); -
trunk/src/org/openstreetmap/josm/gui/oauth/FullyAutomaticAuthorizationUI.java
r8461 r8509 94 94 HtmlPanel pnlMessage = new HtmlPanel(); 95 95 HTMLEditorKit kit = (HTMLEditorKit)pnlMessage.getEditorPane().getEditorKit(); 96 kit.getStyleSheet().addRule(".warning-body {background-color:rgb(253,255,221);padding: 10pt; border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}"); 96 kit.getStyleSheet().addRule( 97 ".warning-body {background-color:rgb(253,255,221);padding: 10pt; border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}"); 97 98 kit.getStyleSheet().addRule("ol {margin-left: 1cm}"); 98 99 pnlMessage.setText("<html><body><p class=\"warning-body\">" … … 143 144 pnlMessage = new HtmlPanel(); 144 145 kit = (HTMLEditorKit)pnlMessage.getEditorPane().getEditorKit(); 145 kit.getStyleSheet().addRule(".warning-body {background-color:rgb(253,255,221);padding: 10pt; border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}"); 146 kit.getStyleSheet().addRule( 147 ".warning-body {background-color:rgb(253,255,221);padding: 10pt; border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}"); 146 148 kit.getStyleSheet().addRule("ol {margin-left: 1cm}"); 147 149 pnlMessage.setText("<html><body>" -
trunk/src/org/openstreetmap/josm/gui/oauth/OsmOAuthAuthorizationClient.java
r8444 r8509 427 427 } 428 428 429 protected void sendAuthorisationRequest(SessionId sessionId, OAuthToken requestToken, OsmPrivileges privileges) throws OsmOAuthAuthorizationException { 429 protected void sendAuthorisationRequest(SessionId sessionId, OAuthToken requestToken, OsmPrivileges privileges) 430 throws OsmOAuthAuthorizationException { 430 431 Map<String, String> parameters = new HashMap<>(); 431 432 fetchOAuthToken(sessionId, requestToken); … … 492 493 * 493 494 * @param requestToken the request token. Must not be null. 494 * @param osmUserName the OSM user name. Must not be null.495 * @param osmPassword the OSM password. Must not be null.495 * @param userName the OSM user name. Must not be null. 496 * @param password the OSM password. Must not be null. 496 497 * @param privileges the set of privileges. Must not be null. 497 498 * @param monitor a progress monitor. Defaults to {@link NullProgressMonitor#INSTANCE} if null … … 503 504 * @throws OsmTransferCanceledException if the task is canceled by the user 504 505 */ 505 public void authorise(OAuthToken requestToken, String osmUserName, String osmPassword, OsmPrivileges privileges, ProgressMonitor monitor) throws OsmOAuthAuthorizationException, OsmTransferCanceledException{ 506 public void authorise(OAuthToken requestToken, String userName, String password, OsmPrivileges privileges, ProgressMonitor monitor) 507 throws OsmOAuthAuthorizationException, OsmTransferCanceledException { 506 508 CheckParameterUtil.ensureParameterNotNull(requestToken, "requestToken"); 507 CheckParameterUtil.ensureParameterNotNull( osmUserName, "osmUserName");508 CheckParameterUtil.ensureParameterNotNull( osmPassword, "osmPassword");509 CheckParameterUtil.ensureParameterNotNull(userName, "userName"); 510 CheckParameterUtil.ensureParameterNotNull(password, "password"); 509 511 CheckParameterUtil.ensureParameterNotNull(privileges, "privileges"); 510 512 … … 517 519 monitor.indeterminateSubTask(tr("Initializing a session at the OSM website...")); 518 520 SessionId sessionId = fetchOsmWebsiteSessionId(); 519 sessionId.userName = osmUserName;521 sessionId.userName = userName; 520 522 if (canceled) 521 523 throw new OsmTransferCanceledException("Authorization canceled"); 522 524 monitor.worked(1); 523 525 524 monitor.indeterminateSubTask(tr("Authenticating the session for user ''{0}''...", osmUserName));525 authenticateOsmSession(sessionId, osmUserName, osmPassword);526 monitor.indeterminateSubTask(tr("Authenticating the session for user ''{0}''...", userName)); 527 authenticateOsmSession(sessionId, userName, password); 526 528 if (canceled) 527 529 throw new OsmTransferCanceledException("Authorization canceled"); -
trunk/src/org/openstreetmap/josm/gui/oauth/TestAccessTokenTask.java
r7004 r8509 113 113 114 114 if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) 115 throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED, tr("Retrieving user details with Access Token Key ''{0}'' was rejected.", token.getKey()), null); 115 throw new OsmApiException(HttpURLConnection.HTTP_UNAUTHORIZED, 116 tr("Retrieving user details with Access Token Key ''{0}'' was rejected.", token.getKey()), null); 116 117 117 118 if (connection.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN) 118 throw new OsmApiException(HttpURLConnection.HTTP_FORBIDDEN, tr("Retrieving user details with Access Token Key ''{0}'' was forbidden.", token.getKey()), null); 119 throw new OsmApiException(HttpURLConnection.HTTP_FORBIDDEN, 120 tr("Retrieving user details with Access Token Key ''{0}'' was forbidden.", token.getKey()), null); 119 121 120 122 if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) -
trunk/src/org/openstreetmap/josm/gui/preferences/PreferenceTabbedPane.java
r8470 r8509 73 73 public final class PreferenceTabbedPane extends JTabbedPane implements MouseWheelListener, ExpertModeChangeListener, ChangeListener { 74 74 75 private final class PluginDownloadAfterTask implements Runnable { 76 private final PluginPreference preference; 77 private final PluginDownloadTask task; 78 private final List<PluginInformation> toDownload; 79 80 private PluginDownloadAfterTask(PluginPreference preference, PluginDownloadTask task, 81 List<PluginInformation> toDownload) { 82 this.preference = preference; 83 this.task = task; 84 this.toDownload = toDownload; 85 } 86 87 @Override 88 public void run() { 89 boolean requiresRestart = false; 90 91 for (PreferenceSetting setting : settingsInitialized) { 92 if (setting.ok()) { 93 requiresRestart = true; 94 } 95 } 96 97 // build the messages. We only display one message, including the status information from the plugin download task 98 // and - if necessary - a hint to restart JOSM 99 // 100 StringBuilder sb = new StringBuilder(); 101 sb.append("<html>"); 102 if (task != null && !task.isCanceled()) { 103 PluginHandler.refreshLocalUpdatedPluginInfo(task.getDownloadedPlugins()); 104 sb.append(PluginPreference.buildDownloadSummary(task)); 105 } 106 if (requiresRestart) { 107 sb.append(tr("You have to restart JOSM for some settings to take effect.")); 108 sb.append("<br/><br/>"); 109 sb.append(tr("Would you like to restart now?")); 110 } 111 sb.append("</html>"); 112 113 // display the message, if necessary 114 // 115 if (requiresRestart) { 116 final ButtonSpec[] options = RestartAction.getButtonSpecs(); 117 if (0 == HelpAwareOptionPane.showOptionDialog( 118 Main.parent, 119 sb.toString(), 120 tr("Restart"), 121 JOptionPane.INFORMATION_MESSAGE, 122 null, /* no special icon */ 123 options, 124 options[0], 125 null /* no special help */ 126 )) { 127 Main.main.menu.restart.actionPerformed(null); 128 } 129 } else if (task != null && !task.isCanceled()) { 130 JOptionPane.showMessageDialog( 131 Main.parent, 132 sb.toString(), 133 tr("Warning"), 134 JOptionPane.WARNING_MESSAGE 135 ); 136 } 137 138 // load the plugins that can be loaded at runtime 139 List<PluginInformation> newPlugins = preference.getNewlyActivatedPlugins(); 140 if (newPlugins != null) { 141 Collection<PluginInformation> downloadedPlugins = null; 142 if (task != null && !task.isCanceled()) { 143 downloadedPlugins = task.getDownloadedPlugins(); 144 } 145 List<PluginInformation> toLoad = new ArrayList<>(); 146 for (PluginInformation pi : newPlugins) { 147 if (toDownload.contains(pi) && downloadedPlugins != null && !downloadedPlugins.contains(pi)) { 148 continue; // failed download 149 } 150 if (pi.canloadatruntime) { 151 toLoad.add(pi); 152 } 153 } 154 // check if plugin dependences can also be loaded 155 Collection<PluginInformation> allPlugins = new HashSet<>(toLoad); 156 for (PluginProxy proxy : PluginHandler.pluginList) { 157 allPlugins.add(proxy.getPluginInformation()); 158 } 159 boolean removed; 160 do { 161 removed = false; 162 Iterator<PluginInformation> it = toLoad.iterator(); 163 while (it.hasNext()) { 164 if (!PluginHandler.checkRequiredPluginsPreconditions(null, allPlugins, it.next(), requiresRestart)) { 165 it.remove(); 166 removed = true; 167 } 168 } 169 } while (removed); 170 171 if (!toLoad.isEmpty()) { 172 PluginHandler.loadPlugins(PreferenceTabbedPane.this, toLoad, null); 173 } 174 } 175 176 Main.parent.repaint(); 177 } 178 } 179 75 180 /** 76 181 * Allows PreferenceSettings to do validation of entered values when ok was pressed. … … 304 409 */ 305 410 public void savePreferences() { 306 // create a task for downloading plugins if the user has activated, yet not downloaded, 307 // new plugins 411 // create a task for downloading plugins if the user has activated, yet not downloaded, new plugins 308 412 // 309 413 final PluginPreference preference = getPluginPreference(); … … 318 422 // this is the task which will run *after* the plugins are downloaded 319 423 // 320 final Runnable continuation = new Runnable() { 321 @Override 322 public void run() { 323 boolean requiresRestart = false; 324 325 for (PreferenceSetting setting : settingsInitialized) { 326 if (setting.ok()) { 327 requiresRestart = true; 328 } 329 } 330 331 // build the messages. We only display one message, including the status 332 // information from the plugin download task and - if necessary - a hint 333 // to restart JOSM 334 // 335 StringBuilder sb = new StringBuilder(); 336 sb.append("<html>"); 337 if (task != null && !task.isCanceled()) { 338 PluginHandler.refreshLocalUpdatedPluginInfo(task.getDownloadedPlugins()); 339 sb.append(PluginPreference.buildDownloadSummary(task)); 340 } 341 if (requiresRestart) { 342 sb.append(tr("You have to restart JOSM for some settings to take effect.")); 343 sb.append("<br/><br/>"); 344 sb.append(tr("Would you like to restart now?")); 345 } 346 sb.append("</html>"); 347 348 // display the message, if necessary 349 // 350 if (requiresRestart) { 351 final ButtonSpec[] options = RestartAction.getButtonSpecs(); 352 if (0 == HelpAwareOptionPane.showOptionDialog( 353 Main.parent, 354 sb.toString(), 355 tr("Restart"), 356 JOptionPane.INFORMATION_MESSAGE, 357 null, /* no special icon */ 358 options, 359 options[0], 360 null /* no special help */ 361 )) { 362 Main.main.menu.restart.actionPerformed(null); 363 } 364 } else if (task != null && !task.isCanceled()) { 365 JOptionPane.showMessageDialog( 366 Main.parent, 367 sb.toString(), 368 tr("Warning"), 369 JOptionPane.WARNING_MESSAGE 370 ); 371 } 372 373 // load the plugins that can be loaded at runtime 374 List<PluginInformation> newPlugins = preference.getNewlyActivatedPlugins(); 375 if (newPlugins != null) { 376 Collection<PluginInformation> downloadedPlugins = null; 377 if (task != null && !task.isCanceled()) { 378 downloadedPlugins = task.getDownloadedPlugins(); 379 } 380 List<PluginInformation> toLoad = new ArrayList<>(); 381 for (PluginInformation pi : newPlugins) { 382 if (toDownload.contains(pi) && downloadedPlugins != null && !downloadedPlugins.contains(pi)) { 383 continue; // failed download 384 } 385 if (pi.canloadatruntime) { 386 toLoad.add(pi); 387 } 388 } 389 // check if plugin dependences can also be loaded 390 Collection<PluginInformation> allPlugins = new HashSet<>(toLoad); 391 for (PluginProxy proxy : PluginHandler.pluginList) { 392 allPlugins.add(proxy.getPluginInformation()); 393 } 394 boolean removed; 395 do { 396 removed = false; 397 Iterator<PluginInformation> it = toLoad.iterator(); 398 while (it.hasNext()) { 399 if (!PluginHandler.checkRequiredPluginsPreconditions(null, allPlugins, it.next(), requiresRestart)) { 400 it.remove(); 401 removed = true; 402 } 403 } 404 } while (removed); 405 406 if (!toLoad.isEmpty()) { 407 PluginHandler.loadPlugins(PreferenceTabbedPane.this, toLoad, null); 408 } 409 } 410 411 Main.parent.repaint(); 412 } 413 }; 424 final Runnable continuation = new PluginDownloadAfterTask(preference, task, toDownload); 414 425 415 426 if (task != null) { -
trunk/src/org/openstreetmap/josm/gui/preferences/ToolbarPreferences.java
r8461 r8509 491 491 public class Settings extends DefaultTabPreferenceSetting { 492 492 493 private final class SelectedListTransferHandler extends TransferHandler { 494 @Override 495 @SuppressWarnings("unchecked") 496 protected Transferable createTransferable(JComponent c) { 497 List<ActionDefinition> actions = new ArrayList<>(); 498 for (ActionDefinition o: ((JList<ActionDefinition>)c).getSelectedValuesList()) { 499 actions.add(o); 500 } 501 return new ActionTransferable(actions); 502 } 503 504 @Override 505 public int getSourceActions(JComponent c) { 506 return TransferHandler.MOVE; 507 } 508 509 @Override 510 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { 511 for (DataFlavor f : transferFlavors) { 512 if (ACTION_FLAVOR.equals(f)) 513 return true; 514 } 515 return false; 516 } 517 518 @Override 519 public void exportAsDrag(JComponent comp, InputEvent e, int action) { 520 super.exportAsDrag(comp, e, action); 521 movingComponent = "list"; 522 } 523 524 @Override 525 public boolean importData(JComponent comp, Transferable t) { 526 try { 527 int dropIndex = selectedList.locationToIndex(selectedList.getMousePosition(true)); 528 @SuppressWarnings("unchecked") 529 List<ActionDefinition> draggedData = (List<ActionDefinition>) t.getTransferData(ACTION_FLAVOR); 530 531 Object leadItem = dropIndex >= 0 ? selected.elementAt(dropIndex) : null; 532 int dataLength = draggedData.size(); 533 534 if (leadItem != null) { 535 for (Object o: draggedData) { 536 if (leadItem.equals(o)) 537 return false; 538 } 539 } 540 541 int dragLeadIndex = -1; 542 boolean localDrop = "list".equals(movingComponent); 543 544 if (localDrop) { 545 dragLeadIndex = selected.indexOf(draggedData.get(0)); 546 for (Object o: draggedData) { 547 selected.removeElement(o); 548 } 549 } 550 int[] indices = new int[dataLength]; 551 552 if (localDrop) { 553 int adjustedLeadIndex = selected.indexOf(leadItem); 554 int insertionAdjustment = dragLeadIndex <= adjustedLeadIndex ? 1 : 0; 555 for (int i = 0; i < dataLength; i++) { 556 selected.insertElementAt(draggedData.get(i), adjustedLeadIndex + insertionAdjustment + i); 557 indices[i] = adjustedLeadIndex + insertionAdjustment + i; 558 } 559 } else { 560 for (int i = 0; i < dataLength; i++) { 561 selected.add(dropIndex, draggedData.get(i)); 562 indices[i] = dropIndex + i; 563 } 564 } 565 selectedList.clearSelection(); 566 selectedList.setSelectedIndices(indices); 567 movingComponent = ""; 568 return true; 569 } catch (Exception e) { 570 Main.error(e); 571 } 572 return false; 573 } 574 575 @Override 576 protected void exportDone(JComponent source, Transferable data, int action) { 577 if ("list".equals(movingComponent)) { 578 try { 579 List<?> draggedData = (List<?>) data.getTransferData(ACTION_FLAVOR); 580 boolean localDrop = selected.contains(draggedData.get(0)); 581 if (localDrop) { 582 int[] indices = selectedList.getSelectedIndices(); 583 Arrays.sort(indices); 584 for (int i = indices.length - 1; i >= 0; i--) { 585 selected.remove(indices[i]); 586 } 587 } 588 } catch (Exception e) { 589 Main.error(e); 590 } 591 movingComponent = ""; 592 } 593 } 594 } 595 493 596 private final class Move implements ActionListener { 494 597 @Override … … 662 765 663 766 selectedList.setDragEnabled(true); 664 selectedList.setTransferHandler(new TransferHandler() { 665 @Override 666 @SuppressWarnings("unchecked") 667 protected Transferable createTransferable(JComponent c) { 668 List<ActionDefinition> actions = new ArrayList<>(); 669 for (ActionDefinition o: ((JList<ActionDefinition>)c).getSelectedValuesList()) { 670 actions.add(o); 671 } 672 return new ActionTransferable(actions); 673 } 674 675 @Override 676 public int getSourceActions(JComponent c) { 677 return TransferHandler.MOVE; 678 } 679 680 @Override 681 public boolean canImport(JComponent comp, DataFlavor[] transferFlavors) { 682 for (DataFlavor f : transferFlavors) { 683 if (ACTION_FLAVOR.equals(f)) 684 return true; 685 } 686 return false; 687 } 688 689 @Override 690 public void exportAsDrag(JComponent comp, InputEvent e, int action) { 691 super.exportAsDrag(comp, e, action); 692 movingComponent = "list"; 693 } 694 695 @Override 696 public boolean importData(JComponent comp, Transferable t) { 697 try { 698 int dropIndex = selectedList.locationToIndex(selectedList.getMousePosition(true)); 699 @SuppressWarnings("unchecked") 700 List<ActionDefinition> draggedData = (List<ActionDefinition>) t.getTransferData(ACTION_FLAVOR); 701 702 Object leadItem = dropIndex >= 0 ? selected.elementAt(dropIndex) : null; 703 int dataLength = draggedData.size(); 704 705 if (leadItem != null) { 706 for (Object o: draggedData) { 707 if (leadItem.equals(o)) 708 return false; 709 } 710 } 711 712 int dragLeadIndex = -1; 713 boolean localDrop = "list".equals(movingComponent); 714 715 if (localDrop) { 716 dragLeadIndex = selected.indexOf(draggedData.get(0)); 717 for (Object o: draggedData) { 718 selected.removeElement(o); 719 } 720 } 721 int[] indices = new int[dataLength]; 722 723 if (localDrop) { 724 int adjustedLeadIndex = selected.indexOf(leadItem); 725 int insertionAdjustment = dragLeadIndex <= adjustedLeadIndex ? 1 : 0; 726 for (int i = 0; i < dataLength; i++) { 727 selected.insertElementAt(draggedData.get(i), adjustedLeadIndex + insertionAdjustment + i); 728 indices[i] = adjustedLeadIndex + insertionAdjustment + i; 729 } 730 } else { 731 for (int i = 0; i < dataLength; i++) { 732 selected.add(dropIndex, draggedData.get(i)); 733 indices[i] = dropIndex + i; 734 } 735 } 736 selectedList.clearSelection(); 737 selectedList.setSelectedIndices(indices); 738 movingComponent = ""; 739 return true; 740 } catch (Exception e) { 741 Main.error(e); 742 } 743 return false; 744 } 745 746 @Override 747 protected void exportDone(JComponent source, Transferable data, int action) { 748 if ("list".equals(movingComponent)) { 749 try { 750 List<?> draggedData = (List<?>) data.getTransferData(ACTION_FLAVOR); 751 boolean localDrop = selected.contains(draggedData.get(0)); 752 if (localDrop) { 753 int[] indices = selectedList.getSelectedIndices(); 754 Arrays.sort(indices); 755 for (int i = indices.length - 1; i >= 0; i--) { 756 selected.remove(indices[i]); 757 } 758 } 759 } catch (Exception e) { 760 Main.error(e); 761 } 762 movingComponent = ""; 763 } 764 } 765 }); 767 selectedList.setTransferHandler(new SelectedListTransferHandler()); 766 768 767 769 actionsTree.setTransferHandler(new TransferHandler() { -
trunk/src/org/openstreetmap/josm/gui/preferences/advanced/ExportProfileAction.java
r8404 r8509 74 74 } 75 75 }; 76 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(false, false, title, filter, JFileChooser.FILES_ONLY, "customsettings.lastDirectory"); 76 AbstractFileChooser fc = DiskAccessAction.createAndOpenFileChooser(false, false, title, filter, 77 JFileChooser.FILES_ONLY, "customsettings.lastDirectory"); 77 78 if (fc != null) { 78 79 File sel = fc.getSelectedFile(); -
trunk/src/org/openstreetmap/josm/gui/preferences/audio/AudioPreference.java
r8444 r8509 65 65 // audioTraceVisible 66 66 markerAudioTraceVisible.setSelected(Main.pref.getBoolean("marker.traceaudio", true)); 67 markerAudioTraceVisible.setToolTipText(tr("Display a moving icon representing the point on the synchronized track where the audio currently playing was recorded.")); 67 markerAudioTraceVisible.setToolTipText( 68 tr("Display a moving icon representing the point on the synchronized track where the audio currently playing was recorded.")); 68 69 audio.add(markerAudioTraceVisible, GBC.eol().insets(0,0,0,0)); 69 70 … … 87 88 // audioMarkersFromNamedTrackpoints 88 89 audioMarkersFromNamedTrackpoints.setSelected(Main.pref.getBoolean("marker.audiofromnamedtrackpoints", false)); 89 audioMarkersFromNamedTrackpoints.setToolTipText(tr("Automatically create audio markers from trackpoints (rather than explicit waypoints) with names or descriptions.")); 90 audioMarkersFromNamedTrackpoints.setToolTipText( 91 tr("Automatically create audio markers from trackpoints (rather than explicit waypoints) with names or descriptions.")); 90 92 audio.add(audioMarkersFromNamedTrackpoints, GBC.eol().insets(10,0,0,0)); 91 93 92 94 // audioMarkersFromWavTimestamps 93 95 audioMarkersFromWavTimestamps.setSelected(Main.pref.getBoolean("marker.audiofromwavtimestamps", false)); 94 audioMarkersFromWavTimestamps.setToolTipText(tr("Create audio markers at the position on the track corresponding to the modified time of each audio WAV file imported.")); 96 audioMarkersFromWavTimestamps.setToolTipText( 97 tr("Create audio markers at the position on the track corresponding to the modified time of each audio WAV file imported.")); 95 98 audio.add(audioMarkersFromWavTimestamps, GBC.eol().insets(10,0,0,0)); 96 99 97 100 // audioMarkersFromStart 98 101 audioMarkersFromStart.setSelected(Main.pref.getBoolean("marker.audiofromstart")); 99 audioMarkersFromStart.setToolTipText(tr("Automatically create audio markers from trackpoints (rather than explicit waypoints) with names or descriptions.")); 102 audioMarkersFromStart.setToolTipText( 103 tr("Automatically create audio markers from trackpoints (rather than explicit waypoints) with names or descriptions.")); 100 104 audio.add(audioMarkersFromStart, GBC.eol().insets(10,0,0,0)); 101 105 … … 111 115 112 116 audioLeadIn.setText(Main.pref.get("audio.leadin", "1.0")); 113 audioLeadIn.setToolTipText(tr("Playback starts this number of seconds before (or after, if negative) the audio track position requested")); 117 audioLeadIn.setToolTipText( 118 tr("Playback starts this number of seconds before (or after, if negative) the audio track position requested")); 114 119 audio.add(new JLabel(tr("Lead-in time (seconds)")), GBC.std()); 115 120 audio.add(audioLeadIn, GBC.eol().fill(GBC.HORIZONTAL).insets(5,0,0,5)); -
trunk/src/org/openstreetmap/josm/gui/preferences/display/DisplayPreference.java
r8378 r8509 29 29 30 30 private DisplayPreference() { 31 super(/* ICON(preferences/) */ "display", tr("Display Settings"), tr("Various settings that influence the visual representation of the whole program."), false, new JTabbedPane()); 31 super(/* ICON(preferences/) */ "display", tr("Display Settings"), 32 tr("Various settings that influence the visual representation of the whole program."), false, new JTabbedPane()); 32 33 } 33 34 -
trunk/src/org/openstreetmap/josm/gui/preferences/display/GPXSettingsPanel.java
r8426 r8509 247 247 colorTypeVelocity.setToolTipText(tr("Colors points and track segments by velocity.")); 248 248 colorTypeDirection.setToolTipText(tr("Colors points and track segments by direction.")); 249 colorTypeDilution.setToolTipText(tr("Colors points and track segments by dilution of position (HDOP). Your capture device needs to log that information.")); 249 colorTypeDilution.setToolTipText( 250 tr("Colors points and track segments by dilution of position (HDOP). Your capture device needs to log that information.")); 250 251 colorTypeTime.setToolTipText(tr("Colors points and track segments by its timestamp.")); 251 252 … … 476 477 parser.parse(); 477 478 } catch (ParseError e) { 478 JOptionPane.showMessageDialog(Main.parent, tr("Incorrect waypoint label pattern: {0}", e.getMessage()), tr("Incorrect pattern"), JOptionPane.ERROR_MESSAGE); 479 JOptionPane.showMessageDialog(Main.parent, 480 tr("Incorrect waypoint label pattern: {0}", e.getMessage()), tr("Incorrect pattern"), JOptionPane.ERROR_MESSAGE); 479 481 waypointLabelPattern.requestFocus(); 480 482 return false; … … 484 486 parser.parse(); 485 487 } catch (ParseError e) { 486 JOptionPane.showMessageDialog(Main.parent, tr("Incorrect audio waypoint label pattern: {0}", e.getMessage()), tr("Incorrect pattern"), JOptionPane.ERROR_MESSAGE); 488 JOptionPane.showMessageDialog(Main.parent, 489 tr("Incorrect audio waypoint label pattern: {0}", e.getMessage()), tr("Incorrect pattern"), JOptionPane.ERROR_MESSAGE); 487 490 audioWaypointLabelPattern.requestFocus(); 488 491 return false; -
trunk/src/org/openstreetmap/josm/gui/preferences/map/MapPreference.java
r8378 r8509 28 28 29 29 private MapPreference() { 30 super(/* ICON(preferences/) */ "map", tr("Map Settings"), tr("Settings for the map projection and data interpretation."), false, new JTabbedPane()); 30 super(/* ICON(preferences/) */ "map", tr("Map Settings"), 31 tr("Settings for the map projection and data interpretation."), false, new JTabbedPane()); 31 32 } 32 33 -
trunk/src/org/openstreetmap/josm/gui/preferences/map/TaggingPresetPreference.java
r8444 r8509 43 43 public final class TaggingPresetPreference implements SubPreferenceSetting { 44 44 45 /** 46 * Factory used to create a new {@code TaggingPresetPreference}. 47 */ 48 public static class Factory implements PreferenceSettingFactory { 49 @Override 50 public PreferenceSetting createPreferenceSetting() { 51 return new TaggingPresetPreference(); 52 } 53 } 54 55 private TaggingPresetPreference() { 56 super(); 57 } 58 59 private static final List<SourceProvider> presetSourceProviders = new ArrayList<>(); 60 61 private SourceEditor sources; 62 private JCheckBox sortMenu; 63 64 /** 65 * Registers a new additional preset source provider. 66 * @param provider The preset source provider 67 * @return {@code true}, if the provider has been added, {@code false} otherwise 68 */ 69 public static boolean registerSourceProvider(SourceProvider provider) { 70 if (provider != null) 71 return presetSourceProviders.add(provider); 72 return false; 73 } 74 75 private ValidationListener validationListener = new ValidationListener() { 45 private final class TaggingPresetValidationListener implements ValidationListener { 76 46 @Override 77 47 public boolean validatePreferences() { … … 134 104 source, e.getMessage()); 135 105 } 136 137 106 } 138 107 … … 155 124 sources.removeSources(sourcesToRemove); 156 125 return true; 157 } else 126 } else { 158 127 return true; 159 } 160 }; 128 } 129 } 130 } 131 132 /** 133 * Factory used to create a new {@code TaggingPresetPreference}. 134 */ 135 public static class Factory implements PreferenceSettingFactory { 136 @Override 137 public PreferenceSetting createPreferenceSetting() { 138 return new TaggingPresetPreference(); 139 } 140 } 141 142 private TaggingPresetPreference() { 143 super(); 144 } 145 146 private static final List<SourceProvider> presetSourceProviders = new ArrayList<>(); 147 148 private SourceEditor sources; 149 private JCheckBox sortMenu; 150 151 /** 152 * Registers a new additional preset source provider. 153 * @param provider The preset source provider 154 * @return {@code true}, if the provider has been added, {@code false} otherwise 155 */ 156 public static boolean registerSourceProvider(SourceProvider provider) { 157 if (provider != null) 158 return presetSourceProviders.add(provider); 159 return false; 160 } 161 162 private final ValidationListener validationListener = new TaggingPresetValidationListener(); 161 163 162 164 @Override -
trunk/src/org/openstreetmap/josm/gui/preferences/plugin/PluginUpdatePolicyPanel.java
r8426 r8509 82 82 bgVersionBasedUpdatePolicy.add(btn); 83 83 84 JMultilineLabel lbl = new JMultilineLabel(tr("Please decide whether JOSM shall automatically update active plugins at startup after an update of JOSM itself.")); 84 JMultilineLabel lbl = new JMultilineLabel( 85 tr("Please decide whether JOSM shall automatically update active plugins at startup after an update of JOSM itself.")); 85 86 gc.gridy=0; 86 87 pnl.add(lbl, gc); -
trunk/src/org/openstreetmap/josm/gui/preferences/remotecontrol/RemoteControlPreference.java
r7668 r8509 88 88 remote.add(descLabel, GBC.eol().insets(5, 5, 0, 10).fill(GBC.HORIZONTAL)); 89 89 90 final JLabel portLabel = new JLabel("<html>" + tr("JOSM will always listen at <b>port {0}</b> (http) and <b>port {1}</b> (https) on localhost." 90 final JLabel portLabel = new JLabel("<html>" 91 + tr("JOSM will always listen at <b>port {0}</b> (http) and <b>port {1}</b> (https) on localhost." 91 92 + "<br>These ports are not configurable because they are referenced by external applications talking to JOSM.", 92 93 Main.pref.get("remote.control.port", "8111"), -
trunk/src/org/openstreetmap/josm/gui/preferences/server/AuthenticationPreferencesPanel.java
r8218 r8509 124 124 rbOAuth.setSelected(true); 125 125 } else { 126 Main.warn(tr("Unsupported value in preference ''{0}'', got ''{1}''. Using authentication method ''Basic Authentication''.", "osm-server.auth-method", authMethod)); 126 Main.warn(tr("Unsupported value in preference ''{0}'', got ''{1}''. Using authentication method ''Basic Authentication''.", 127 "osm-server.auth-method", authMethod)); 127 128 rbBasicAuthentication.setSelected(true); 128 129 } -
trunk/src/org/openstreetmap/josm/gui/preferences/server/OAuthAuthenticationPreferencesPanel.java
r8444 r8509 180 180 */ 181 181 private class NotYetAuthorisedPanel extends JPanel { 182 /** 183 * Constructs a new {@code NotYetAuthorisedPanel}. 184 */ 185 public NotYetAuthorisedPanel() { 186 build(); 187 } 188 182 189 protected void build() { 183 190 setLayout(new GridBagLayout()); … … 190 197 gc.weightx = 1.0; 191 198 JMultilineLabel lbl; 192 add(lbl = new JMultilineLabel(tr("You do not have an Access Token yet to access the OSM server using OAuth. Please authorize first.")), gc); 199 add(lbl = new JMultilineLabel( 200 tr("You do not have an Access Token yet to access the OSM server using OAuth. Please authorize first.")), gc); 193 201 lbl.setFont(lbl.getFont().deriveFont(Font.PLAIN)); 194 202 … … 205 213 gc.weighty = 1.0; 206 214 add(new JPanel(), gc); 207 }208 209 public NotYetAuthorisedPanel() {210 build();211 215 } 212 216 } -
trunk/src/org/openstreetmap/josm/gui/preferences/server/ServerAccessPreference.java
r7668 r8509 35 35 36 36 private ServerAccessPreference() { 37 super(/* ICON(preferences/) */ "connection", tr("Connection Settings"), tr("Connection Settings for the OSM server."), false, new JTabbedPane()); 37 super(/* ICON(preferences/) */ "connection", tr("Connection Settings"), 38 tr("Connection Settings for the OSM server."), false, new JTabbedPane()); 38 39 } 39 40 -
trunk/src/org/openstreetmap/josm/gui/preferences/validator/ValidatorTestsPreference.java
r8444 r8509 70 70 testPanel.add(prefOther, GBC.eol()); 71 71 72 prefOtherUpload = new JCheckBox(tr("Show informational level on upload."), Main.pref.getBoolean(ValidatorPreference.PREF_OTHER_UPLOAD, false)); 72 prefOtherUpload = new JCheckBox(tr("Show informational level on upload."), 73 Main.pref.getBoolean(ValidatorPreference.PREF_OTHER_UPLOAD, false)); 73 74 prefOtherUpload.setToolTipText(tr("Show the informational tests in the upload check windows.")); 74 75 testPanel.add(prefOtherUpload, GBC.eol()); -
trunk/src/org/openstreetmap/josm/gui/progress/PleaseWaitProgressMonitor.java
r8387 r8509 28 28 void setCurrentAction(String text); 29 29 void setIndeterminate(boolean newValue); 30 void appendLogMessage(String message); //TODO Not implemented properly in background monitor, log message will get lost if progress runs in background 30 // TODO Not implemented properly in background monitor, log message will get lost if progress runs in background 31 void appendLogMessage(String message); 31 32 } 32 33 … … 47 48 48 49 private void doInEDT(Runnable runnable) { 49 // This must be invoke later even if current thread is EDT because inside there is dialog.setVisible which freeze current code flow until modal dialog is closed 50 // This must be invoke later even if current thread is EDT because inside there is dialog.setVisible 51 // which freeze current code flow until modal dialog is closed 50 52 SwingUtilities.invokeLater(runnable); 51 53 } -
trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPreset.java
r8492 r8509 489 489 } 490 490 491 public static Collection<TaggingPreset> getMatchingPresets(final Collection<TaggingPresetType> t, final Map<String, String> tags, final boolean onlyShowable) { 491 public static Collection<TaggingPreset> getMatchingPresets(final Collection<TaggingPresetType> t, 492 final Map<String, String> tags, final boolean onlyShowable) { 492 493 return Utils.filter(TaggingPresets.getTaggingPresets(), new Predicate<TaggingPreset>() { 493 494 @Override -
trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetItems.java
r8493 r8509 1107 1107 1108 1108 if (display_array.length != value_array.length) { 1109 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''", key, text)); 1109 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''display_values'' must be the same as in ''values''", 1110 key, text)); 1110 1111 display_array = value_array; 1111 1112 } 1112 1113 1113 1114 if (short_descriptions_array != null && short_descriptions_array.length != value_array.length) { 1114 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''", key, text)); 1115 Main.error(tr("Broken tagging preset \"{0}-{1}\" - number of items in ''short_descriptions'' must be the same as in ''values''", 1116 key, text)); 1115 1117 short_descriptions_array = null; 1116 1118 } … … 1200 1202 private static final ListCellRenderer<PresetListEntry> RENDERER = new ListCellRenderer<PresetListEntry>() { 1201 1203 1202 private JLabel lbl = new JLabel();1204 private final JLabel lbl = new JLabel(); 1203 1205 1204 1206 @Override 1205 public Component getListCellRendererComponent( 1206 JList<? extends PresetListEntry> list, 1207 PresetListEntry item, 1208 int index, 1209 boolean isSelected, 1210 boolean cellHasFocus) { 1207 public Component getListCellRendererComponent(JList<? extends PresetListEntry> list, PresetListEntry item, int index, 1208 boolean isSelected, boolean cellHasFocus) { 1211 1209 1212 1210 // Only return cached size, item is not shown … … 1221 1219 1222 1220 lbl.setPreferredSize(null); 1223 1224 1221 1225 1222 if (isSelected) { -
trunk/src/org/openstreetmap/josm/gui/tagging/TaggingPresetSelector.java
r8404 r8509 89 89 private final DefaultListCellRenderer def = new DefaultListCellRenderer(); 90 90 @Override 91 public Component getListCellRendererComponent(JList<? extends TaggingPreset> list, TaggingPreset tp, int index, boolean isSelected, boolean cellHasFocus) { 91 public Component getListCellRendererComponent(JList<? extends TaggingPreset> list, TaggingPreset tp, int index, 92 boolean isSelected, boolean cellHasFocus) { 92 93 JLabel result = (JLabel) def.getListCellRendererComponent(list, tp, index, isSelected, cellHasFocus); 93 94 result.setText(tp.getName()); -
trunk/src/org/openstreetmap/josm/gui/util/AdjustmentSynchronizer.java
r8444 r8509 79 79 CheckParameterUtil.ensureParameterNotNull(adjustable, "adjustable"); 80 80 if (!synchronizedAdjustables.contains(adjustable)) 81 throw new IllegalStateException(tr("Adjustable {0} not registered yet. Cannot set participation in synchronized adjustment.", adjustable)); 81 throw new IllegalStateException( 82 tr("Adjustable {0} not registered yet. Cannot set participation in synchronized adjustment.", adjustable)); 82 83 83 84 enabledMap.put(adjustable, isParticipating); -
trunk/src/org/openstreetmap/josm/gui/widgets/EditableList.java
r8378 r8509 101 101 public void actionPerformed(ActionEvent e) { 102 102 if (sourcesList.getSelectedIndex() == -1) { 103 JOptionPane.showMessageDialog(Main.parent, tr("Please select the row to delete."), tr("Information"), JOptionPane.QUESTION_MESSAGE); 103 JOptionPane.showMessageDialog(Main.parent, tr("Please select the row to delete."), tr("Information"), 104 JOptionPane.QUESTION_MESSAGE); 104 105 } else { 105 106 ((DefaultListModel<String>) sourcesList.getModel()).remove(sourcesList.getSelectedIndex()); -
trunk/src/org/openstreetmap/josm/gui/widgets/JosmTextField.java
r8291 r8509 22 22 * <li>disables the global advanced key press detector when focused</li> 23 23 * <li>implements a workaround to <a href="https://bugs.openjdk.java.net/browse/JDK-6322854">JDK bug 6322854</a></li> 24 * < br>This class must be used everywhere in core and plugins instead of {@code JTextField}.24 * </ul><br>This class must be used everywhere in core and plugins instead of {@code JTextField}. 25 25 * @since 5886 26 26 */ -
trunk/src/org/openstreetmap/josm/io/CachedFile.java
r8470 r8509 461 461 * @since 6867 462 462 */ 463 public static HttpURLConnection connectFollowingRedirect(URL downloadUrl, String httpAccept, Long ifModifiedSince) throws MalformedURLException, IOException { 463 public static HttpURLConnection connectFollowingRedirect(URL downloadUrl, String httpAccept, Long ifModifiedSince) 464 throws MalformedURLException, IOException { 464 465 CheckParameterUtil.ensureParameterNotNull(downloadUrl, "downloadUrl"); 465 466 String downloadString = downloadUrl.toExternalForm(); -
trunk/src/org/openstreetmap/josm/io/DefaultProxySelector.java
r8394 r8509 116 116 proxyPolicy = ProxyPolicy.fromName(value); 117 117 if (proxyPolicy == null) { 118 Main.warn(tr("Unexpected value for preference ''{0}'' found. Got ''{1}''. Will use no proxy.", ProxyPreferencesPanel.PROXY_POLICY, value)); 118 Main.warn(tr("Unexpected value for preference ''{0}'' found. Got ''{1}''. Will use no proxy.", 119 ProxyPreferencesPanel.PROXY_POLICY, value)); 119 120 proxyPolicy = ProxyPolicy.NO_PROXY; 120 121 } -
trunk/src/org/openstreetmap/josm/io/MessageNotifier.java
r8126 r8509 59 59 public void run() { 60 60 try { 61 final UserInfo userInfo = new OsmServerUserInfoReader().fetchUserInfo(NullProgressMonitor.INSTANCE, tr("get number of unread messages")); 61 final UserInfo userInfo = new OsmServerUserInfoReader().fetchUserInfo(NullProgressMonitor.INSTANCE, 62 tr("get number of unread messages")); 62 63 final int unread = userInfo.getUnreadMessages(); 63 64 if (unread > 0 && unread != lastUnreadCount) { … … 66 67 public void run() { 67 68 JPanel panel = new JPanel(new GridBagLayout()); 68 panel.add(new JLabel(trn("You have {0} unread message.", "You have {0} unread messages.", unread, unread)), GBC.eol()); 69 panel.add(new UrlLabel(Main.getBaseUserUrl() + "/"+userInfo.getDisplayName()+"/inbox", tr("Click here to see your inbox.")), GBC.eol()); 69 panel.add(new JLabel(trn("You have {0} unread message.", "You have {0} unread messages.", unread, unread)), 70 GBC.eol()); 71 panel.add(new UrlLabel(Main.getBaseUserUrl() + "/" + userInfo.getDisplayName() + "/inbox", 72 tr("Click here to see your inbox.")), GBC.eol()); 70 73 panel.setOpaque(false); 71 74 new Notification().setContent(panel) -
trunk/src/org/openstreetmap/josm/io/MultiFetchServerObjectReader.java
r8390 r8509 109 109 * @param ds the dataset (must not be null) 110 110 * @param id the primitive id 111 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 111 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 112 * {@link OsmPrimitiveType#RELATION RELATION} 112 113 * @throws IllegalArgumentException if ds is null 113 114 * @throws NoSuchElementException if ds does not include an {@link OsmPrimitive} with id=<code>id</code> … … 128 129 * @param ds the {@link DataSet} to which the primitive belongs 129 130 * @param id the primitive id 130 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 131 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 132 * {@link OsmPrimitiveType#RELATION RELATION} 131 133 * @return this 132 134 */ … … 258 260 * builds the Multi Get request string for a set of ids and a given {@link OsmPrimitiveType}. 259 261 * 260 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 262 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 263 * {@link OsmPrimitiveType#RELATION RELATION} 261 264 * @param idPackage the package of ids 262 265 * @return the request string … … 280 283 * builds the Multi Get request string for a single id and a given {@link OsmPrimitiveType}. 281 284 * 282 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 285 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 286 * {@link OsmPrimitiveType#RELATION RELATION} 283 287 * @param id the id 284 288 * @return the request string … … 318 322 * 319 323 * @param ids the set of ids 320 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 324 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 325 * {@link OsmPrimitiveType#RELATION RELATION} 321 326 * @throws OsmTransferException if an error occurs while communicating with the API server 322 327 */ … … 443 448 444 449 /** 445 * The class that actually download data from OSM API. Several instances of this class are used by {@link MultiFetchServerObjectReader} (one per set of primitives to fetch). 450 * The class that actually download data from OSM API. 451 * Several instances of this class are used by {@link MultiFetchServerObjectReader} (one per set of primitives to fetch). 446 452 * The inheritance of {@link OsmServerReader} is only explained by the need to have a distinct OSM connection by {@code Fetcher} instance. 447 453 * @see FetchResult … … 455 461 /** 456 462 * Constructs a {@code Fetcher} 457 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 463 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 464 * {@link OsmPrimitiveType#RELATION RELATION} 458 465 * @param idsPackage The set of primitives ids to fetch 459 466 * @param progressMonitor The progress monitor … … 467 474 @Override 468 475 public DataSet parseOsm(ProgressMonitor progressMonitor) throws OsmTransferException { 469 // This method is implemented because of the OsmServerReader inheritance, but not used, as the main target of this class is the call() method. 476 // This method is implemented because of the OsmServerReader inheritance, but not used, 477 // as the main target of this class is the call() method. 470 478 return fetch(progressMonitor).dataSet; 471 479 } … … 499 507 * The retrieved primitives are merged to {@link #outputDataSet}. 500 508 * 501 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 509 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 510 * {@link OsmPrimitiveType#RELATION RELATION} 502 511 * @param pkg the package of ids 503 512 * @return the {@link FetchResult} of this operation … … 525 534 * The retrieved primitive is merged to {@link #outputDataSet}. 526 535 * 527 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 536 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 537 * {@link OsmPrimitiveType#RELATION RELATION} 528 538 * @param id the id 529 539 * @return the {@link DataSet} resulting of this operation … … 555 565 * Unfortunately, the server does not provide an error header or an error body for a 404 reply. 556 566 * 557 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, {@link OsmPrimitiveType#RELATION RELATION} 567 * @param type The primitive type. Must be one of {@link OsmPrimitiveType#NODE NODE}, {@link OsmPrimitiveType#WAY WAY}, 568 * {@link OsmPrimitiveType#RELATION RELATION} 558 569 * @param pkg the set of ids 559 570 * @return the {@link FetchResult} of this operation -
trunk/src/org/openstreetmap/josm/io/OsmApiException.java
r8390 r8509 16 16 /** 17 17 * Constructs an {@code OsmApiException} with the specified response code, error header and error body 18 * @param responseCode The HTTP response code replied by the OSM server. See {@link java.net.HttpURLConnection HttpURLConnection} for predefined HTTP response code values 18 * @param responseCode The HTTP response code replied by the OSM server. 19 * See {@link java.net.HttpURLConnection HttpURLConnection} for predefined HTTP response code values 19 20 * @param errorHeader The error header, as transmitted in the {@code Error} field of the HTTP response header 20 21 * @param errorBody The error body, as transmitted in the HTTP response body … … 31 32 /** 32 33 * Constructs an {@code OsmApiException} with the specified response code, error header and error body 33 * @param responseCode The HTTP response code replied by the OSM server. See {@link java.net.HttpURLConnection HttpURLConnection} for predefined HTTP response code values 34 * @param responseCode The HTTP response code replied by the OSM server. 35 * See {@link java.net.HttpURLConnection HttpURLConnection} for predefined HTTP response code values 34 36 * @param errorHeader The error header, as transmitted in the {@code Error} field of the HTTP response header 35 37 * @param errorBody The error body, as transmitted in the HTTP response body … … 78 80 /** 79 81 * Replies the HTTP response code. 80 * @return The HTTP response code replied by the OSM server. Refer to <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a> to see the list of response codes returned by the API for each call. 82 * @return The HTTP response code replied by the OSM server. Refer to 83 * <a href="http://wiki.openstreetmap.org/wiki/API_v0.6">OSM API</a> to see the list of response codes returned by the API for each call. 81 84 */ 82 85 public int getResponseCode() { … … 86 89 /** 87 90 * Sets the HTTP response code. 88 * @param responseCode The HTTP response code replied by the OSM server. See {@link java.net.HttpURLConnection HttpURLConnection} for predefined HTTP response code values 91 * @param responseCode The HTTP response code replied by the OSM server. 92 * See {@link java.net.HttpURLConnection HttpURLConnection} for predefined HTTP response code values 89 93 */ 90 94 public void setResponseCode(int responseCode) { … … 175 179 176 180 /** 177 * Sets the complete URL accessed when this error occured. This is distinct from the one set with {@link #setUrl}, which is generally only the base URL of the server. 181 * Sets the complete URL accessed when this error occured. 182 * This is distinct from the one set with {@link #setUrl}, which is generally only the base URL of the server. 178 183 * @param url the complete URL accessed when this error occured. 179 184 */ … … 183 188 184 189 /** 185 * Replies the complete URL accessed when this error occured. This is distinct from the one returned by {@link #getUrl}, which is generally only the base URL of the server. 190 * Replies the complete URL accessed when this error occured. 191 * This is distinct from the one returned by {@link #getUrl}, which is generally only the base URL of the server. 186 192 * @return the complete URL accessed when this error occured. 187 193 */ -
trunk/src/org/openstreetmap/josm/io/OsmChangesetParser.java
r8347 r8509 33 33 * <pre> 34 34 * <osm version="0.6" generator="OpenStreetMap server"> 35 * <changeset id="143" user="guggis" uid="1" created_at="2009-09-08T20:35:39Z" closed_at="2009-09-08T21:36:12Z" open="false" min_lon="7.380925" min_lat="46.9215164" max_lon="7.3984718" max_lat="46.9226502"> 35 * <changeset id="143" user="guggis" uid="1" created_at="2009-09-08T20:35:39Z" closed_at="2009-09-08T21:36:12Z" open="false" 36 * min_lon="7.380925" min_lat="46.9215164" max_lon="7.3984718" max_lat="46.9226502"> 36 37 * <tag k="asdfasdf" v="asdfasdf"/> 37 38 * <tag k="created_by" v="JOSM/1.5 (UNKNOWN de)"/> -
trunk/src/org/openstreetmap/josm/io/OsmImporter.java
r7816 r8509 123 123 * @param progressMonitor handler for progress monitoring and canceling 124 124 */ 125 public OsmImporterData loadLayer(InputStream in, final File associatedFile, final String layerName, ProgressMonitor progressMonitor) throws IllegalDataException { 125 public OsmImporterData loadLayer(InputStream in, final File associatedFile, final String layerName, ProgressMonitor progressMonitor) 126 throws IllegalDataException { 126 127 final DataSet dataSet = parseDataSet(in, progressMonitor); 127 128 if (dataSet == null) { -
trunk/src/org/openstreetmap/josm/io/OsmReader.java
r8461 r8509 326 326 type = OsmPrimitiveType.fromApiTypeName(value); 327 327 } catch(IllegalArgumentException e) { 328 throwException(tr("Illegal value for attribute ''type'' on member {0} in relation {1}. Got {2}.", Long.toString(id), Long.toString(r.getUniqueId()), value), e); 328 throwException(tr("Illegal value for attribute ''type'' on member {0} in relation {1}. Got {2}.", 329 Long.toString(id), Long.toString(r.getUniqueId()), value), e); 329 330 } 330 331 value = parser.getAttributeValue(null, "role"); … … 627 628 } 628 629 if (e.getLocation() != null) 629 throw new IllegalDataException(tr("Line {0} column {1}: ", e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()) + msg, e); 630 throw new IllegalDataException(tr("Line {0} column {1}: ", 631 e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()) + msg, e); 630 632 else 631 633 throw new IllegalDataException(msg, e); … … 645 647 * 646 648 * @return the dataset with the parsed data 647 * @throws IllegalDataException if thean error was found while parsing the data from the source649 * @throws IllegalDataException if an error was found while parsing the data from the source 648 650 * @throws IllegalArgumentException if source is null 649 651 */ -
trunk/src/org/openstreetmap/josm/io/OsmServerBackreferenceReader.java
r8470 r8509 203 203 for (Relation relation: relationsToCheck) { 204 204 if (!relation.isNew() && relation.hasIncompleteMembers()) { 205 OsmServerObjectReader reader = new OsmServerObjectReader(relation.getId(), OsmPrimitiveType.from(relation), true /* read full */);205 OsmServerObjectReader reader = new OsmServerObjectReader(relation.getId(), OsmPrimitiveType.from(relation), true); 206 206 DataSet wayDs = reader.parseOsm(progressMonitor.createSubTaskMonitor(1, false)); 207 207 DataSetMerger visitor = new DataSetMerger(ds, wayDs); -
trunk/src/org/openstreetmap/josm/io/OsmServerReader.java
r8470 r8509 117 117 */ 118 118 @SuppressWarnings("resource") 119 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason, boolean uncompressAccordingToContentDisposition) throws OsmTransferException { 119 protected InputStream getInputStreamRaw(String urlStr, ProgressMonitor progressMonitor, String reason, 120 boolean uncompressAccordingToContentDisposition) throws OsmTransferException { 120 121 try { 121 122 OnlineResource.JOSM_WEBSITE.checkOfflineAccess(urlStr, Main.getJOSMWebsite()); … … 159 160 } catch (Exception e) { 160 161 Main.error(e); 161 OsmTransferException ote = new OsmTransferException(tr("Could not connect to the OSM server. Please check your internet connection."), e); 162 OsmTransferException ote = new OsmTransferException( 163 tr("Could not connect to the OSM server. Please check your internet connection."), e); 162 164 ote.setUrl(url.toString()); 163 165 throw ote; -
trunk/src/org/openstreetmap/josm/io/OsmServerWriter.java
r8449 r8509 84 84 * @throws OsmTransferException if an exception occurs 85 85 */ 86 protected void uploadChangesIndividually(Collection<? extends OsmPrimitive> primitives, ProgressMonitor progressMonitor) throws OsmTransferException { 86 protected void uploadChangesIndividually(Collection<? extends OsmPrimitive> primitives, ProgressMonitor progressMonitor) 87 throws OsmTransferException { 87 88 try { 88 89 progressMonitor.beginTask(tr("Starting to upload with one request per primitive ...")); … … 126 127 * @throws OsmTransferException if an exception occurs 127 128 */ 128 protected void uploadChangesAsDiffUpload(Collection<? extends OsmPrimitive> primitives, ProgressMonitor progressMonitor) throws OsmTransferException { 129 protected void uploadChangesAsDiffUpload(Collection<? extends OsmPrimitive> primitives, ProgressMonitor progressMonitor) 130 throws OsmTransferException { 129 131 try { 130 132 progressMonitor.beginTask(tr("Starting to upload in one request ...")); … … 146 148 * @throws OsmTransferException if an exception occurs 147 149 */ 148 protected void uploadChangesInChunks(Collection<? extends OsmPrimitive> primitives, ProgressMonitor progressMonitor, int chunkSize) throws OsmTransferException, IllegalArgumentException { 150 protected void uploadChangesInChunks(Collection<? extends OsmPrimitive> primitives, ProgressMonitor progressMonitor, int chunkSize) 151 throws OsmTransferException, IllegalArgumentException { 149 152 if (chunkSize <=0) 150 153 throw new IllegalArgumentException(tr("Value >0 expected for parameter ''{0}'', got {1}", "chunkSize", chunkSize)); -
trunk/src/org/openstreetmap/josm/io/auth/CredentialsAgent.java
r8291 r8509 53 53 54 54 */ 55 CredentialsAgentResponse getCredentials(RequestorType requestorType, String host, boolean noSuccessWithLastResponse) throws CredentialsAgentException; 55 CredentialsAgentResponse getCredentials(RequestorType requestorType, String host, boolean noSuccessWithLastResponse) 56 throws CredentialsAgentException; 56 57 57 58 /** -
trunk/src/org/openstreetmap/josm/io/auth/CredentialsAgentResponse.java
r6222 r8509 5 5 6 6 /** 7 * CredentialsAgentResponse represents the response from {@link CredentialsAgent#getCredentials(java.net.Authenticator.RequestorType, String, boolean)}. 7 * CredentialsAgentResponse represents the response from 8 * {@link CredentialsAgent#getCredentials(java.net.Authenticator.RequestorType, String, boolean)}. 8 9 * 9 10 * The response consists of the username and the password the requested credentials consists of. -
trunk/src/org/openstreetmap/josm/io/auth/CredentialsManager.java
r8419 r8509 126 126 127 127 @Override 128 public CredentialsAgentResponse getCredentials(RequestorType requestorType, String host, boolean noSuccessWithLastResponse) throws CredentialsAgentException { 128 public CredentialsAgentResponse getCredentials(RequestorType requestorType, String host, boolean noSuccessWithLastResponse) 129 throws CredentialsAgentException { 129 130 return delegate.getCredentials(requestorType, host, noSuccessWithLastResponse); 130 131 } -
trunk/src/org/openstreetmap/josm/io/auth/JosmPreferencesCredentialAgent.java
r8291 r8509 131 131 HtmlPanel pnlMessage = new HtmlPanel(); 132 132 HTMLEditorKit kit = (HTMLEditorKit)pnlMessage.getEditorPane().getEditorKit(); 133 kit.getStyleSheet().addRule(".warning-body {background-color:rgb(253,255,221);padding: 10pt; border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}"); 133 kit.getStyleSheet().addRule( 134 ".warning-body {background-color:rgb(253,255,221);padding: 10pt; border-color:rgb(128,128,128);border-style: solid;border-width: 1px;}"); 134 135 pnlMessage.setText( 135 136 tr( … … 150 151 return tr("Save user and password (unencrypted)"); 151 152 } 152 153 153 } -
trunk/src/org/openstreetmap/josm/io/imagery/WMSImagery.java
r8404 r8509 217 217 static boolean isImageFormatSupported(final String format) { 218 218 return ImageIO.getImageReadersByMIMEType(format).hasNext() 219 || (format.startsWith("image/tiff") || format.startsWith("image/geotiff")) && ImageIO.getImageReadersBySuffix("tiff").hasNext() // handles image/tiff image/tiff8 image/geotiff image/geotiff8 219 // handles image/tiff image/tiff8 image/geotiff image/geotiff8 220 || (format.startsWith("image/tiff") || format.startsWith("image/geotiff")) && ImageIO.getImageReadersBySuffix("tiff").hasNext() 220 221 || format.startsWith("image/png") && ImageIO.getImageReadersBySuffix("png").hasNext() 221 222 || format.startsWith("image/svg") && ImageIO.getImageReadersBySuffix("svg").hasNext() -
trunk/src/org/openstreetmap/josm/io/remotecontrol/AddTagsDialog.java
r8444 r8509 228 228 229 229 /** 230 * If you click the "Add tags" button build a ChangePropertyCommand for every key that has a checked checkbox to apply the key value pair to all selected osm objects. 230 * If you click the "Add tags" button build a ChangePropertyCommand for every key that has a checked checkbox 231 * to apply the key value pair to all selected osm objects. 231 232 * You get a entry for every key in the command queue. 232 233 */ -
trunk/src/org/openstreetmap/josm/io/remotecontrol/handler/ImageryHandler.java
r8444 r8509 133 133 @Override 134 134 public String[] getUsageExamples() { 135 final String types = Utils.join("|", Utils.transform(Arrays.asList(ImageryInfo.ImageryType.values()), new Utils.Function<ImageryInfo.ImageryType, String>() { 135 final String types = Utils.join("|", Utils.transform(Arrays.asList(ImageryInfo.ImageryType.values()), 136 new Utils.Function<ImageryInfo.ImageryType, String>() { 136 137 @Override 137 138 public String apply(ImageryInfo.ImageryType x) { -
trunk/src/org/openstreetmap/josm/io/remotecontrol/handler/LoadAndZoomHandler.java
r8444 r8509 138 138 Main.info("RemoteControl: no download necessary"); 139 139 } else { 140 Future<?> future = osmTask.download(newLayer, new Bounds(minlat,minlon,maxlat,maxlon), null /* let the task manage the progress monitor */); 140 Future<?> future = osmTask.download(newLayer, new Bounds(minlat,minlon,maxlat,maxlon), 141 null /* let the task manage the progress monitor */); 141 142 Main.worker.submit(new PostDownloadHandler(osmTask, future)); 142 143 } -
trunk/src/org/openstreetmap/josm/io/session/MarkerSessionImporter.java
r7937 r8509 41 41 42 42 try (InputStream in = support.getInputStream(fileStr)) { 43 GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), null, progressMonitor); 43 GpxImporter.GpxImporterData importData = GpxImporter.loadLayers(in, support.getFile(fileStr), support.getLayerName(), 44 null, progressMonitor); 44 45 45 46 support.addPostLayersTask(importData.getPostLayerTask()); -
trunk/src/org/openstreetmap/josm/io/session/SessionReader.java
r8444 r8509 593 593 } 594 594 595 private void loadSession(InputStream josIS, URI sessionFileURI, boolean zip, ProgressMonitor progressMonitor) throws IOException, IllegalDataException { 595 private void loadSession(InputStream josIS, URI sessionFileURI, boolean zip, ProgressMonitor progressMonitor) 596 throws IOException, IllegalDataException { 596 597 597 598 this.sessionFileURI = sessionFileURI; -
trunk/src/org/openstreetmap/josm/plugins/PluginHandler.java
r8471 r8509 614 614 * @since 5601 615 615 */ 616 public static boolean checkRequiredPluginsPreconditions(Component parent, Collection<PluginInformation> plugins, PluginInformation plugin, boolean local) { 616 public static boolean checkRequiredPluginsPreconditions(Component parent, Collection<PluginInformation> plugins, 617 PluginInformation plugin, boolean local) { 617 618 618 619 String requires = local ? plugin.localrequires : plugin.requires; … … 1173 1174 if (plugin.exists() && !plugin.delete() && dowarn) { 1174 1175 Main.warn(tr("Failed to delete outdated plugin ''{0}''.", plugin.toString())); 1175 Main.warn(tr("Failed to install already downloaded plugin ''{0}''. Skipping installation. JOSM is still going to load the old plugin version.", pluginName)); 1176 Main.warn(tr("Failed to install already downloaded plugin ''{0}''. Skipping installation. JOSM is still going to load the old plugin version.", 1177 pluginName)); 1176 1178 continue; 1177 1179 } … … 1181 1183 } catch (Exception e) { 1182 1184 if (dowarn) { 1183 Main.warn(tr("Failed to install plugin ''{0}'' from temporary download file ''{1}''. {2}", plugin.toString(), updatedPlugin.toString(), e.getLocalizedMessage())); 1185 Main.warn(tr("Failed to install plugin ''{0}'' from temporary download file ''{1}''. {2}", 1186 plugin.toString(), updatedPlugin.toString(), e.getLocalizedMessage())); 1184 1187 } 1185 1188 continue; … … 1187 1190 // Install plugin 1188 1191 if (!updatedPlugin.renameTo(plugin) && dowarn) { 1189 Main.warn(tr("Failed to install plugin ''{0}'' from temporary download file ''{1}''. Renaming failed.", plugin.toString(), updatedPlugin.toString())); 1190 Main.warn(tr("Failed to install already downloaded plugin ''{0}''. Skipping installation. JOSM is still going to load the old plugin version.", pluginName)); 1192 Main.warn(tr("Failed to install plugin ''{0}'' from temporary download file ''{1}''. Renaming failed.", 1193 plugin.toString(), updatedPlugin.toString())); 1194 Main.warn(tr("Failed to install already downloaded plugin ''{0}''. Skipping installation. JOSM is still going to load the old plugin version.", 1195 pluginName)); 1191 1196 } 1192 1197 } -
trunk/src/org/openstreetmap/josm/plugins/ReadRemotePluginInformationTask.java
r8461 r8509 221 221 } 222 222 223 private void displayErrorMessage(final ProgressMonitor monitor, final String msg, final String details, final String title, final String firstMessage) { 223 private void displayErrorMessage(final ProgressMonitor monitor, final String msg, final String details, final String title, 224 final String firstMessage) { 224 225 GuiHelper.runInEDTAndWait(new Runnable() { 225 226 @Override public void run() { … … 255 256 File pluginDir = Main.pref.getPluginsDirectory(); 256 257 if (!pluginDir.exists() && !pluginDir.mkdirs()) { 257 Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", pluginDir.toString(), site)); 258 Main.warn(tr("Failed to create plugin directory ''{0}''. Cannot cache plugin list from plugin site ''{1}''.", 259 pluginDir.toString(), site)); 258 260 } 259 261 File cacheFile = createSiteCacheFile(pluginDir, site); -
trunk/src/org/openstreetmap/josm/tools/BugReportExceptionHandler.java
r8374 r8509 48 48 private static class BugReporterThread extends Thread { 49 49 50 private final class BugReporterWorker implements Runnable { 51 private final PluginDownloadTask pluginDownloadTask; 52 53 private BugReporterWorker(PluginDownloadTask pluginDownloadTask) { 54 this.pluginDownloadTask = pluginDownloadTask; 55 } 56 57 @Override 58 public void run() { 59 // Then ask for submitting a bug report, for exceptions thrown from a plugin too, unless updated to a new version 60 if (pluginDownloadTask == null) { 61 String[] buttonTexts = new String[] {tr("Do nothing"), tr("Report Bug")}; 62 String[] buttonIcons = new String[] {"cancel", "bug"}; 63 int defaultButtonIdx = 1; 64 String message = tr("An unexpected exception occurred.<br>" + 65 "This is always a coding error. If you are running the latest<br>" + 66 "version of JOSM, please consider being kind and file a bug report." 67 ); 68 // Check user is running current tested version, the error may already be fixed 69 int josmVersion = Version.getInstance().getVersion(); 70 if (josmVersion != Version.JOSM_UNKNOWN_VERSION) { 71 try { 72 int latestVersion = Integer.parseInt(new WikiReader(). 73 read(Main.getJOSMWebsite()+"/wiki/TestedVersion?format=txt").trim()); 74 if (latestVersion > josmVersion) { 75 buttonTexts = new String[] {tr("Do nothing"), tr("Update JOSM"), tr("Report Bug")}; 76 buttonIcons = new String[] {"cancel", "download", "bug"}; 77 defaultButtonIdx = 2; 78 message = tr("An unexpected exception occurred. This is always a coding error.<br><br>" + 79 "However, you are running an old version of JOSM ({0}),<br>" + 80 "instead of using the current tested version (<b>{1}</b>).<br><br>"+ 81 "<b>Please update JOSM</b> before considering to file a bug report.", 82 String.valueOf(josmVersion), String.valueOf(latestVersion)); 83 } 84 } catch (IOException | NumberFormatException e) { 85 Main.warn("Unable to detect latest version of JOSM: "+e.getMessage()); 86 } 87 } 88 // Show dialog 89 ExtendedDialog ed = new ExtendedDialog(Main.parent, tr("Unexpected Exception"), buttonTexts); 90 ed.setButtonIcons(buttonIcons); 91 ed.setIcon(JOptionPane.ERROR_MESSAGE); 92 ed.setCancelButton(1); 93 ed.setDefaultButton(defaultButtonIdx); 94 JPanel pnl = new JPanel(new GridBagLayout()); 95 pnl.add(new JLabel("<html>" + message + "</html>"), GBC.eol()); 96 JCheckBox cbSuppress = null; 97 if (exceptionCounter > 1) { 98 cbSuppress = new JCheckBox(tr("Suppress further error dialogs for this session.")); 99 pnl.add(cbSuppress, GBC.eol()); 100 } 101 ed.setContent(pnl); 102 ed.setFocusOnDefaultButton(true); 103 ed.showDialog(); 104 if (cbSuppress != null && cbSuppress.isSelected()) { 105 suppressExceptionDialogs = true; 106 } 107 if (ed.getValue() <= 1) { 108 // "Do nothing" 109 return; 110 } else if (ed.getValue() < buttonTexts.length) { 111 // "Update JOSM" 112 try { 113 Main.platform.openUrl(Main.getJOSMWebsite()); 114 } catch (IOException e) { 115 Main.warn("Unable to access JOSM website: "+e.getMessage()); 116 } 117 } else { 118 // "Report bug" 119 askForBugReport(e); 120 } 121 } else { 122 // Ask for restart to install new plugin 123 PluginPreference.notifyDownloadResults( 124 Main.parent, pluginDownloadTask, !pluginDownloadTask.getDownloadedPlugins().isEmpty()); 125 } 126 } 127 } 128 50 129 private final Throwable e; 51 130 131 /** 132 * Constructs a new {@code BugReporterThread}. 133 * @param t the exception 134 */ 52 135 public BugReporterThread(Throwable t) { 53 136 super("Bug Reporter"); … … 58 141 public void run() { 59 142 // Give the user a chance to deactivate the plugin which threw the exception (if it was thrown from a plugin) 60 final PluginDownloadTask pluginDownloadTask = PluginHandler.updateOrdisablePluginAfterException(e); 61 62 SwingUtilities.invokeLater(new Runnable() { 63 @Override 64 public void run() { 65 // Then ask for submitting a bug report, for exceptions thrown from a plugin too, unless updated to a new version 66 if (pluginDownloadTask == null) { 67 String[] buttonTexts = new String[] {tr("Do nothing"), tr("Report Bug")}; 68 String[] buttonIcons = new String[] {"cancel", "bug"}; 69 int defaultButtonIdx = 1; 70 String message = tr("An unexpected exception occurred.<br>" + 71 "This is always a coding error. If you are running the latest<br>" + 72 "version of JOSM, please consider being kind and file a bug report." 73 ); 74 // Check user is running current tested version, the error may already be fixed 75 int josmVersion = Version.getInstance().getVersion(); 76 if (josmVersion != Version.JOSM_UNKNOWN_VERSION) { 77 try { 78 int latestVersion = Integer.parseInt(new WikiReader(). 79 read(Main.getJOSMWebsite()+"/wiki/TestedVersion?format=txt").trim()); 80 if (latestVersion > josmVersion) { 81 buttonTexts = new String[] {tr("Do nothing"), tr("Update JOSM"), tr("Report Bug")}; 82 buttonIcons = new String[] {"cancel", "download", "bug"}; 83 defaultButtonIdx = 2; 84 message = tr("An unexpected exception occurred. This is always a coding error.<br><br>" + 85 "However, you are running an old version of JOSM ({0}),<br>" + 86 "instead of using the current tested version (<b>{1}</b>).<br><br>"+ 87 "<b>Please update JOSM</b> before considering to file a bug report.", 88 String.valueOf(josmVersion), String.valueOf(latestVersion)); 89 } 90 } catch (IOException | NumberFormatException e) { 91 Main.warn("Unable to detect latest version of JOSM: "+e.getMessage()); 92 } 93 } 94 // Show dialog 95 ExtendedDialog ed = new ExtendedDialog(Main.parent, tr("Unexpected Exception"), buttonTexts); 96 ed.setButtonIcons(buttonIcons); 97 ed.setIcon(JOptionPane.ERROR_MESSAGE); 98 ed.setCancelButton(1); 99 ed.setDefaultButton(defaultButtonIdx); 100 JPanel pnl = new JPanel(new GridBagLayout()); 101 pnl.add(new JLabel("<html>" + message + "</html>"), GBC.eol()); 102 JCheckBox cbSuppress = null; 103 if (exceptionCounter > 1) { 104 cbSuppress = new JCheckBox(tr("Suppress further error dialogs for this session.")); 105 pnl.add(cbSuppress, GBC.eol()); 106 } 107 ed.setContent(pnl); 108 ed.setFocusOnDefaultButton(true); 109 ed.showDialog(); 110 if (cbSuppress != null && cbSuppress.isSelected()) { 111 suppressExceptionDialogs = true; 112 } 113 if (ed.getValue() <= 1) { 114 // "Do nothing" 115 return; 116 } else if (ed.getValue() < buttonTexts.length) { 117 // "Update JOSM" 118 try { 119 Main.platform.openUrl(Main.getJOSMWebsite()); 120 } catch (IOException e) { 121 Main.warn("Unable to access JOSM website: "+e.getMessage()); 122 } 123 } else { 124 // "Report bug" 125 askForBugReport(e); 126 } 127 } else { 128 // Ask for restart to install new plugin 129 PluginPreference.notifyDownloadResults( 130 Main.parent, pluginDownloadTask, !pluginDownloadTask.getDownloadedPlugins().isEmpty()); 131 } 132 } 133 }); 143 SwingUtilities.invokeLater(new BugReporterWorker(PluginHandler.updateOrdisablePluginAfterException(e))); 134 144 } 135 145 } -
trunk/src/org/openstreetmap/josm/tools/ExceptionUtil.java
r8470 r8509 105 105 return Pair.create(n, refs); 106 106 } 107 m = Pattern.compile(".*Way (\\d+) requires the nodes with id in " + ids + ".*").matcher(msg); // ... ", which either do not exist, or are not visible" 107 m = Pattern.compile(".*Way (\\d+) requires the nodes with id in " + ids + ".*").matcher(msg); 108 // ... ", which either do not exist, or are not visible" 108 109 if (m.matches()) { 109 110 OsmPrimitive n = new Way(Long.parseLong(m.group(1))); -
trunk/src/org/openstreetmap/josm/tools/ExifReader.java
r8470 r8509 83 83 * <li>The 0th row is the visual left-hand side of the image, and the 0th column is the visual bottom.</li></ol> 84 84 * @see <a href="http://www.impulseadventure.com/photo/exif-orientation.html">http://www.impulseadventure.com/photo/exif-orientation.html</a> 85 * @see <a href="http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto">http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto</a> 85 * @see <a href="http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto"> 86 * http://www.daveperrett.com/articles/2012/07/28/exif-orientation-handling-is-a-ghetto</a> 86 87 */ 87 88 public static Integer readOrientation(File filename) { … … 136 137 * Returns the direction of the given JPEG file. 137 138 * @param filename The JPEG file to read 138 * @return The direction of the image when it was captures (in degrees between 0.0 and 359.99), or {@code null} if missing or if {@code dirGps} is null 139 * @return The direction of the image when it was captures (in degrees between 0.0 and 359.99), 140 * or {@code null} if missing or if {@code dirGps} is null 139 141 * @since 6209 140 142 */ … … 155 157 * Returns the direction of the given EXIF GPS directory. 156 158 * @param dirGps The EXIF GPS directory 157 * @return The direction of the image when it was captures (in degrees between 0.0 and 359.99), or {@code null} if missing or if {@code dirGps} is null 159 * @return The direction of the image when it was captures (in degrees between 0.0 and 359.99), 160 * or {@code null} if missing or if {@code dirGps} is null 158 161 * @since 6209 159 162 */ -
trunk/src/org/openstreetmap/josm/tools/Geometry.java
r8470 r8509 905 905 if (nodes.size() == 1 906 906 ? nodeInsidePolygon(nodes.get(0), out.getNodes()) 907 : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains(polygonIntersection(nodes, out.getNodes()))) { 907 : EnumSet.of(PolygonIntersection.FIRST_INSIDE_SECOND, PolygonIntersection.CROSSING).contains( 908 polygonIntersection(nodes, out.getNodes()))) { 908 909 boolean insideInner = false; 909 910 // If inside an outer, check it is not inside an inner … … 920 921 if (!insideInner) { 921 922 // Final check using predicate 922 if (isOuterWayAMatch == null || isOuterWayAMatch.evaluate(out.ways.get(0) /* TODO give a better representation of the outer ring to the predicate */)) { 923 if (isOuterWayAMatch == null || isOuterWayAMatch.evaluate(out.ways.get(0) 924 /* TODO give a better representation of the outer ring to the predicate */)) { 923 925 return true; 924 926 } -
trunk/src/org/openstreetmap/josm/tools/ImageProvider.java
r8459 r8509 546 546 if (!optional) { 547 547 String ext = name.indexOf('.') != -1 ? "" : ".???"; 548 throw new RuntimeException(tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.", name + ext)); 548 throw new RuntimeException( 549 tr("Fatal: failed to locate image ''{0}''. This is a serious configuration problem. JOSM will stop working.", 550 name + ext)); 549 551 } else { 550 552 if (!suppressWarnings) { -
trunk/src/org/openstreetmap/josm/tools/MultikeyActionsHandler.java
r8376 r8509 34 34 private Map<MultikeyShortcutAction, MyAction> myActions = new HashMap<>(); 35 35 36 private final class ShowLayersPopupWorker implements Runnable { 37 private final MyAction action; 38 39 private ShowLayersPopupWorker(MyAction action) { 40 this.action = action; 41 } 42 43 @Override 44 public void run() { 45 JPopupMenu layers = new JPopupMenu(); 46 47 JMenuItem lbTitle = new JMenuItem((String) action.action.getValue(Action.SHORT_DESCRIPTION)); 48 lbTitle.setEnabled(false); 49 JPanel pnTitle = new JPanel(); 50 pnTitle.add(lbTitle); 51 layers.add(pnTitle); 52 53 char repeatKey = (char) action.shortcut.getKeyStroke().getKeyCode(); 54 boolean repeatKeyUsed = false; 55 56 for (final MultikeyInfo info: action.action.getMultikeyCombinations()) { 57 58 if (info.getShortcut() == repeatKey) { 59 repeatKeyUsed = true; 60 } 61 62 JMenuItem item = new JMenuItem(formatMenuText(action.shortcut.getKeyStroke(), 63 String.valueOf(info.getShortcut()), info.getDescription())); 64 item.setMnemonic(info.getShortcut()); 65 item.addActionListener(new ActionListener() { 66 @Override 67 public void actionPerformed(ActionEvent e) { 68 action.action.executeMultikeyAction(info.getIndex(), false); 69 } 70 }); 71 layers.add(item); 72 } 73 74 if (!repeatKeyUsed) { 75 MultikeyInfo lastLayer = action.action.getLastMultikeyAction(); 76 if (lastLayer != null) { 77 JMenuItem repeateItem = new JMenuItem(formatMenuText(action.shortcut.getKeyStroke(), 78 KeyEvent.getKeyText(action.shortcut.getKeyStroke().getKeyCode()), 79 "Repeat " + lastLayer.getDescription())); 80 repeateItem.setMnemonic(action.shortcut.getKeyStroke().getKeyCode()); 81 repeateItem.addActionListener(new ActionListener() { 82 @Override 83 public void actionPerformed(ActionEvent e) { 84 action.action.executeMultikeyAction(-1, true); 85 } 86 }); 87 layers.add(repeateItem); 88 } 89 } 90 layers.addPopupMenuListener(new PopupMenuListener() { 91 92 @Override 93 public void popupMenuWillBecomeVisible(PopupMenuEvent e) { 94 // Do nothing 95 } 96 97 @Override 98 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { 99 Main.map.statusLine.resetHelpText(STATUS_BAR_ID); 100 } 101 102 @Override 103 public void popupMenuCanceled(PopupMenuEvent e) { 104 // Do nothing 105 } 106 }); 107 108 layers.show(Main.parent, Integer.MAX_VALUE, Integer.MAX_VALUE); 109 layers.setLocation(Main.parent.getX() + Main.parent.getWidth() - layers.getWidth(), 110 Main.parent.getY() + Main.parent.getHeight() - layers.getHeight()); 111 } 112 } 113 36 114 private class MyKeyEventDispatcher implements KeyEventDispatcher { 37 115 @Override … … 102 180 if (lastTimestamp == MultikeyActionsHandler.this.lastTimestamp && 103 181 lastAction == MultikeyActionsHandler.this.lastAction) { 104 showLayersPopup(lastAction);182 SwingUtilities.invokeLater(new ShowLayersPopupWorker(lastAction)); 105 183 MultikeyActionsHandler.this.lastAction = null; 106 184 } … … 112 190 private Timer timer; 113 191 114 115 192 private MultikeyActionsHandler() { 116 193 KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new MyKeyEventDispatcher()); 117 timer = new Timer();194 timer = new Timer(); 118 195 } 119 196 … … 132 209 133 210 private String formatMenuText(KeyStroke keyStroke, String index, String description) { 134 String shortcutText = KeyEvent.getKeyModifiersText(keyStroke.getModifiers()) + "+" + KeyEvent.getKeyText(keyStroke.getKeyCode()) + "," + index; 211 String shortcutText = KeyEvent.getKeyModifiersText(keyStroke.getModifiers()) + "+" 212 + KeyEvent.getKeyText(keyStroke.getKeyCode()) + "," + index; 135 213 136 214 return "<html><i>" + shortcutText + "</i> " + description; 137 138 }139 140 private void showLayersPopup(final MyAction action) {141 SwingUtilities.invokeLater(new Runnable() {142 @Override143 public void run() {144 JPopupMenu layers = new JPopupMenu();145 146 JMenuItem lbTitle = new JMenuItem((String) action.action.getValue(Action.SHORT_DESCRIPTION));147 lbTitle.setEnabled(false);148 JPanel pnTitle = new JPanel();149 pnTitle.add(lbTitle);150 layers.add(pnTitle);151 152 char repeatKey = (char) action.shortcut.getKeyStroke().getKeyCode();153 boolean repeatKeyUsed = false;154 155 156 for (final MultikeyInfo info: action.action.getMultikeyCombinations()) {157 158 if (info.getShortcut() == repeatKey) {159 repeatKeyUsed = true;160 }161 162 JMenuItem item = new JMenuItem(formatMenuText(action.shortcut.getKeyStroke(), String.valueOf(info.getShortcut()), info.getDescription()));163 item.setMnemonic(info.getShortcut());164 item.addActionListener(new ActionListener() {165 @Override166 public void actionPerformed(ActionEvent e) {167 action.action.executeMultikeyAction(info.getIndex(), false);168 }169 });170 layers.add(item);171 }172 173 if (!repeatKeyUsed) {174 MultikeyInfo lastLayer = action.action.getLastMultikeyAction();175 if (lastLayer != null) {176 JMenuItem repeateItem = new JMenuItem(formatMenuText(action.shortcut.getKeyStroke(),177 KeyEvent.getKeyText(action.shortcut.getKeyStroke().getKeyCode()),178 "Repeat " + lastLayer.getDescription()));179 repeateItem.setMnemonic(action.shortcut.getKeyStroke().getKeyCode());180 repeateItem.addActionListener(new ActionListener() {181 @Override182 public void actionPerformed(ActionEvent e) {183 action.action.executeMultikeyAction(-1, true);184 }185 });186 layers.add(repeateItem);187 }188 }189 layers.addPopupMenuListener(new PopupMenuListener() {190 191 @Override192 public void popupMenuWillBecomeVisible(PopupMenuEvent e) {}193 194 @Override195 public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {196 Main.map.statusLine.resetHelpText(STATUS_BAR_ID);197 }198 199 @Override200 public void popupMenuCanceled(PopupMenuEvent e) {}201 });202 203 layers.show(Main.parent, Integer.MAX_VALUE, Integer.MAX_VALUE);204 layers.setLocation(Main.parent.getX() + Main.parent.getWidth() - layers.getWidth(), Main.parent.getY() + Main.parent.getHeight() - layers.getHeight());205 }206 });207 215 } 208 216 -
trunk/src/org/openstreetmap/josm/tools/PlatformHookUnixoid.java
r8461 r8509 132 132 // TODO: Insert system shortcuts here. See Windows and especially OSX to see how to. 133 133 for(int i = KeyEvent.VK_F1; i <= KeyEvent.VK_F12; ++i) 134 Shortcut.registerSystemShortcut("screen:toogle"+i, tr("reserved"), i, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK).setAutomatic(); 135 Shortcut.registerSystemShortcut("system:reset", tr("reserved"), KeyEvent.VK_DELETE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK).setAutomatic(); 136 Shortcut.registerSystemShortcut("system:resetX", tr("reserved"), KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK).setAutomatic(); 134 Shortcut.registerSystemShortcut("screen:toogle"+i, tr("reserved"), 135 i, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK).setAutomatic(); 136 Shortcut.registerSystemShortcut("system:reset", tr("reserved"), 137 KeyEvent.VK_DELETE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK).setAutomatic(); 138 Shortcut.registerSystemShortcut("system:resetX", tr("reserved"), 139 KeyEvent.VK_BACK_SPACE, KeyEvent.CTRL_DOWN_MASK | KeyEvent.ALT_DOWN_MASK).setAutomatic(); 137 140 } 138 141 … … 407 410 "Oracle", tr("April 2015"))+"</b><br><br>"; 408 411 } 409 content += "<b>"+tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", "8")+"</b><br><br>"+ 412 content += "<b>" + 413 tr("JOSM will soon stop working with this version; we highly recommend you to update to Java {0}.", "8") 414 + "</b><br><br>" + 410 415 tr("Would you like to update now ?"); 411 416 ed.setContent(content); -
trunk/src/org/openstreetmap/josm/tools/Shortcut.java
r8443 r8509 47 47 48 48 // simple constructor 49 private Shortcut(String shortText, String longText, int requestedKey, int requestedGroup, int assignedKey, int assignedModifier, boolean assignedDefault, boolean assignedUser) { 49 private Shortcut(String shortText, String longText, int requestedKey, int requestedGroup, int assignedKey, int assignedModifier, 50 boolean assignedDefault, boolean assignedUser) { 50 51 this.shortText = shortText; 51 52 this.longText = longText; … … 68 69 } 69 70 70 // a shortcut will be renamed when it is handed out again, because the original name 71 // may be a dummy 71 // a shortcut will be renamed when it is handed out again, because the original name may be a dummy 72 72 private void setLongText(String longText) { 73 73 this.longText = longText; -
trunk/src/org/openstreetmap/josm/tools/XmlObjectParser.java
r8419 r8509 133 133 private void setValue(Entry entry, String fieldName, String value) throws SAXException { 134 134 CheckParameterUtil.ensureParameterNotNull(entry, "entry"); 135 if ("class".equals(fieldName) || "default".equals(fieldName) || "throw".equals(fieldName) || "new".equals(fieldName) || "null".equals(fieldName)) { 135 if ("class".equals(fieldName) || "default".equals(fieldName) || "throw".equals(fieldName) || 136 "new".equals(fieldName) || "null".equals(fieldName)) { 136 137 fieldName += "_"; 137 138 } -
trunk/src/org/openstreetmap/josm/tools/template_engine/ContextSwitchTemplate.java
r8285 r8509 220 220 return new OrSet((ContextProvider)lhs, (ContextProvider)rhs); 221 221 else if (lhs instanceof ContextProvider) 222 throw new ParseError(tr("Error in search expression on position {0} - right side of or(|) expression must return set of primitives", searchExpressionPosition)); 222 throw new ParseError( 223 tr("Error in search expression on position {0} - right side of or(|) expression must return set of primitives", 224 searchExpressionPosition)); 223 225 else if (rhs instanceof ContextProvider) 224 throw new ParseError(tr("Error in search expression on position {0} - left side of or(|) expression must return set of primitives", searchExpressionPosition)); 226 throw new ParseError( 227 tr("Error in search expression on position {0} - left side of or(|) expression must return set of primitives", 228 searchExpressionPosition)); 225 229 else 226 230 return m; … … 228 232 Match match = transform(((Not) m).getMatch(), searchExpressionPosition); 229 233 if (match instanceof ContextProvider) 230 throw new ParseError(tr("Error in search expression on position {0} - not(-) cannot be used in this context", searchExpressionPosition)); 234 throw new ParseError( 235 tr("Error in search expression on position {0} - not(-) cannot be used in this context", 236 searchExpressionPosition)); 231 237 else 232 238 return m; … … 238 244 Match m = transform(match, searchExpressionPosition); 239 245 if (!(m instanceof ContextProvider)) 240 throw new ParseError(tr("Error in search expression on position {0} - expression must return different then current primitive", searchExpressionPosition)); 246 throw new ParseError( 247 tr("Error in search expression on position {0} - expression must return different then current primitive", 248 searchExpressionPosition)); 241 249 else { 242 250 context = (ContextProvider) m; -
trunk/src/org/openstreetmap/josm/tools/template_engine/TemplateParser.java
r7937 r8509 89 89 } else { 90 90 try { 91 result.getEntries().add(new SearchExpressionCondition(SearchCompiler.compile(searchExpression.getText(), false, false), condition)); 91 result.getEntries().add(new SearchExpressionCondition( 92 SearchCompiler.compile(searchExpression.getText(), false, false), condition)); 92 93 } catch (org.openstreetmap.josm.actions.search.SearchCompiler.ParseError e) { 93 94 throw new ParseError(searchExpression.getPosition(), e);
Note:
See TracChangeset
for help on using the changeset viewer.