1 | // License: GPL. For details, see LICENSE file.
|
---|
2 | package org.openstreetmap.josm.io.remotecontrol.handler;
|
---|
3 |
|
---|
4 | import static org.openstreetmap.josm.tools.I18n.tr;
|
---|
5 |
|
---|
6 | import java.awt.geom.Area;
|
---|
7 | import java.awt.geom.Rectangle2D;
|
---|
8 | import java.util.Arrays;
|
---|
9 | import java.util.Collection;
|
---|
10 | import java.util.Collections;
|
---|
11 | import java.util.LinkedHashSet;
|
---|
12 | import java.util.Map;
|
---|
13 | import java.util.Set;
|
---|
14 | import java.util.concurrent.ExecutionException;
|
---|
15 | import java.util.concurrent.Future;
|
---|
16 | import java.util.concurrent.TimeUnit;
|
---|
17 | import java.util.concurrent.TimeoutException;
|
---|
18 |
|
---|
19 | import javax.swing.JOptionPane;
|
---|
20 |
|
---|
21 | import org.openstreetmap.josm.actions.AutoScaleAction;
|
---|
22 | import org.openstreetmap.josm.actions.AutoScaleAction.AutoScaleMode;
|
---|
23 | import org.openstreetmap.josm.actions.downloadtasks.DownloadOsmTask;
|
---|
24 | import org.openstreetmap.josm.actions.downloadtasks.DownloadParams;
|
---|
25 | import org.openstreetmap.josm.actions.downloadtasks.PostDownloadHandler;
|
---|
26 | import org.openstreetmap.josm.data.Bounds;
|
---|
27 | import org.openstreetmap.josm.data.coor.LatLon;
|
---|
28 | import org.openstreetmap.josm.data.osm.BBox;
|
---|
29 | import org.openstreetmap.josm.data.osm.DataSet;
|
---|
30 | import org.openstreetmap.josm.data.osm.OsmPrimitive;
|
---|
31 | import org.openstreetmap.josm.data.osm.Relation;
|
---|
32 | import org.openstreetmap.josm.data.osm.SimplePrimitiveId;
|
---|
33 | import org.openstreetmap.josm.data.osm.search.SearchCompiler;
|
---|
34 | import org.openstreetmap.josm.data.osm.search.SearchParseError;
|
---|
35 | import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
|
---|
36 | import org.openstreetmap.josm.gui.MainApplication;
|
---|
37 | import org.openstreetmap.josm.gui.MapFrame;
|
---|
38 | import org.openstreetmap.josm.gui.Notification;
|
---|
39 | import org.openstreetmap.josm.gui.util.GuiHelper;
|
---|
40 | import org.openstreetmap.josm.io.OsmApiException;
|
---|
41 | import org.openstreetmap.josm.io.remotecontrol.AddTagsDialog;
|
---|
42 | import org.openstreetmap.josm.io.remotecontrol.PermissionPrefWithDefault;
|
---|
43 | import org.openstreetmap.josm.tools.Logging;
|
---|
44 | import org.openstreetmap.josm.tools.SubclassFilteredCollection;
|
---|
45 | import org.openstreetmap.josm.tools.Utils;
|
---|
46 |
|
---|
47 | /**
|
---|
48 | * Handler for {@code load_and_zoom} and {@code zoom} requests.
|
---|
49 | * @since 3707
|
---|
50 | */
|
---|
51 | public class LoadAndZoomHandler extends RequestHandler {
|
---|
52 |
|
---|
53 | /**
|
---|
54 | * The remote control command name used to load data and zoom.
|
---|
55 | */
|
---|
56 | public static final String command = "load_and_zoom";
|
---|
57 |
|
---|
58 | /**
|
---|
59 | * The remote control command name used to zoom.
|
---|
60 | */
|
---|
61 | public static final String command2 = "zoom";
|
---|
62 | private static final String CURRENT_SELECTION = "currentselection";
|
---|
63 |
|
---|
64 | // Mandatory arguments
|
---|
65 | private double minlat;
|
---|
66 | private double maxlat;
|
---|
67 | private double minlon;
|
---|
68 | private double maxlon;
|
---|
69 |
|
---|
70 | // Optional argument 'select'
|
---|
71 | private final Set<SimplePrimitiveId> toSelect = new LinkedHashSet<>();
|
---|
72 |
|
---|
73 | private boolean isKeepingCurrentSelection;
|
---|
74 |
|
---|
75 | @Override
|
---|
76 | public String getPermissionMessage() {
|
---|
77 | String msg = tr("Remote Control has been asked to load data from the API.") +
|
---|
78 | "<br>" + tr("Bounding box: ") + new BBox(minlon, minlat, maxlon, maxlat).toStringCSV(", ");
|
---|
79 | if (args.containsKey("select") && !toSelect.isEmpty()) {
|
---|
80 | msg += "<br>" + tr("Selection: {0}", toSelect.size());
|
---|
81 | }
|
---|
82 | return msg;
|
---|
83 | }
|
---|
84 |
|
---|
85 | @Override
|
---|
86 | public String[] getMandatoryParams() {
|
---|
87 | return new String[] {"bottom", "top", "left", "right"};
|
---|
88 | }
|
---|
89 |
|
---|
90 | @Override
|
---|
91 | public String[] getOptionalParams() {
|
---|
92 | return new String[] {"new_layer", "layer_name", "addtags", "select", "zoom_mode",
|
---|
93 | "changeset_comment", "changeset_source", "changeset_hashtags", "changeset_tags",
|
---|
94 | "search", "layer_locked", "download_policy", "upload_policy"};
|
---|
95 | }
|
---|
96 |
|
---|
97 | @Override
|
---|
98 | public String getUsage() {
|
---|
99 | return "download a bounding box from the API, zoom to the downloaded area and optionally select one or more objects";
|
---|
100 | }
|
---|
101 |
|
---|
102 | @Override
|
---|
103 | public String[] getUsageExamples() {
|
---|
104 | return getUsageExamples(myCommand);
|
---|
105 | }
|
---|
106 |
|
---|
107 | @Override
|
---|
108 | public String[] getUsageExamples(String cmd) {
|
---|
109 | if (command.equals(cmd)) {
|
---|
110 | return new String[] {
|
---|
111 | "/load_and_zoom?addtags=wikipedia:de=Wei%C3%9Fe_Gasse|maxspeed=5&select=way23071688,way23076176,way23076177," +
|
---|
112 | "&left=13.740&right=13.741&top=51.05&bottom=51.049",
|
---|
113 | "/load_and_zoom?left=8.19&right=8.20&top=48.605&bottom=48.590&select=node413602999&new_layer=true"};
|
---|
114 | } else {
|
---|
115 | return new String[] {
|
---|
116 | "/zoom?left=8.19&right=8.20&top=48.605&bottom=48.590&select=node413602999",
|
---|
117 | "/zoom?left=8.19&right=8.20&top=48.605&bottom=48.590&search=highway+OR+railway",
|
---|
118 | "/zoom?left=8.19&right=8.20&top=48.605&bottom=48.590&search=" + CURRENT_SELECTION + "&addtags=foo=bar",
|
---|
119 | };
|
---|
120 | }
|
---|
121 | }
|
---|
122 |
|
---|
123 | @Override
|
---|
124 | protected void handleRequest() throws RequestHandlerErrorException {
|
---|
125 | DownloadOsmTask osmTask = new DownloadOsmTask();
|
---|
126 | try {
|
---|
127 | DownloadParams settings = getDownloadParams();
|
---|
128 |
|
---|
129 | if (command.equals(myCommand)) {
|
---|
130 | if (!PermissionPrefWithDefault.LOAD_DATA.isAllowed()) {
|
---|
131 | Logging.info("RemoteControl: download forbidden by preferences");
|
---|
132 | } else {
|
---|
133 | Area toDownload = null;
|
---|
134 | if (!settings.isNewLayer()) {
|
---|
135 | // find out whether some data has already been downloaded
|
---|
136 | Area present = null;
|
---|
137 | DataSet ds = MainApplication.getLayerManager().getEditDataSet();
|
---|
138 | if (ds != null) {
|
---|
139 | present = ds.getDataSourceArea();
|
---|
140 | }
|
---|
141 | if (present != null && !present.isEmpty()) {
|
---|
142 | toDownload = new Area(new Rectangle2D.Double(minlon, minlat, maxlon-minlon, maxlat-minlat));
|
---|
143 | toDownload.subtract(present);
|
---|
144 | if (!toDownload.isEmpty()) {
|
---|
145 | // the result might not be a rectangle (L shaped etc)
|
---|
146 | Rectangle2D downloadBounds = toDownload.getBounds2D();
|
---|
147 | minlat = downloadBounds.getMinY();
|
---|
148 | minlon = downloadBounds.getMinX();
|
---|
149 | maxlat = downloadBounds.getMaxY();
|
---|
150 | maxlon = downloadBounds.getMaxX();
|
---|
151 | }
|
---|
152 | }
|
---|
153 | }
|
---|
154 | if (toDownload != null && toDownload.isEmpty()) {
|
---|
155 | Logging.info("RemoteControl: no download necessary");
|
---|
156 | } else {
|
---|
157 | Future<?> future = osmTask.download(settings, new Bounds(minlat, minlon, maxlat, maxlon),
|
---|
158 | null /* let the task manage the progress monitor */);
|
---|
159 | MainApplication.worker.submit(new PostDownloadHandler(osmTask, future))
|
---|
160 | .get(OSM_DOWNLOAD_TIMEOUT.get(), TimeUnit.SECONDS);
|
---|
161 | if (osmTask.isFailed()) {
|
---|
162 | Object error = osmTask.getErrorObjects().get(0);
|
---|
163 | throw error instanceof OsmApiException
|
---|
164 | ? new RequestHandlerOsmApiException((OsmApiException) error)
|
---|
165 | : new RequestHandlerErrorException(String.join(", ", osmTask.getErrorMessages()));
|
---|
166 | }
|
---|
167 | }
|
---|
168 | }
|
---|
169 | }
|
---|
170 | } catch (RuntimeException | InterruptedException | ExecutionException | TimeoutException ex) { // NOPMD
|
---|
171 | Logging.warn("RemoteControl: Error parsing load_and_zoom remote control request:");
|
---|
172 | Logging.error(ex);
|
---|
173 | throw new RequestHandlerErrorException(ex);
|
---|
174 | }
|
---|
175 |
|
---|
176 | /**
|
---|
177 | * deselect objects if parameter addtags given
|
---|
178 | */
|
---|
179 | if (args.containsKey("addtags") && !isKeepingCurrentSelection) {
|
---|
180 | GuiHelper.executeByMainWorkerInEDT(() -> {
|
---|
181 | DataSet ds = MainApplication.getLayerManager().getEditDataSet();
|
---|
182 | if (ds == null) // e.g. download failed
|
---|
183 | return;
|
---|
184 | ds.clearSelection();
|
---|
185 | });
|
---|
186 | }
|
---|
187 |
|
---|
188 | final Collection<OsmPrimitive> forTagAdd = new LinkedHashSet<>();
|
---|
189 | final Bounds bbox = new Bounds(minlat, minlon, maxlat, maxlon);
|
---|
190 | if (args.containsKey("select") && PermissionPrefWithDefault.CHANGE_SELECTION.isAllowed()) {
|
---|
191 | // select objects after downloading, zoom to selection.
|
---|
192 | GuiHelper.executeByMainWorkerInEDT(() -> {
|
---|
193 | Set<OsmPrimitive> newSel = new LinkedHashSet<>();
|
---|
194 | DataSet ds = MainApplication.getLayerManager().getEditDataSet();
|
---|
195 | if (ds == null) // e.g. download failed
|
---|
196 | return;
|
---|
197 | for (SimplePrimitiveId id : toSelect) {
|
---|
198 | final OsmPrimitive p = ds.getPrimitiveById(id);
|
---|
199 | if (p != null) {
|
---|
200 | newSel.add(p);
|
---|
201 | forTagAdd.add(p);
|
---|
202 | }
|
---|
203 | }
|
---|
204 | if (isKeepingCurrentSelection) {
|
---|
205 | Collection<OsmPrimitive> sel = ds.getSelected();
|
---|
206 | newSel.addAll(sel);
|
---|
207 | forTagAdd.addAll(sel);
|
---|
208 | }
|
---|
209 | toSelect.clear();
|
---|
210 | ds.setSelected(newSel);
|
---|
211 | zoom(newSel, bbox);
|
---|
212 | MapFrame map = MainApplication.getMap();
|
---|
213 | if (MainApplication.isDisplayingMapView() && map.relationListDialog != null) {
|
---|
214 | map.relationListDialog.selectRelations(null); // unselect all relations to fix #7342
|
---|
215 | map.relationListDialog.dataChanged(null);
|
---|
216 | map.relationListDialog.selectRelations(Utils.filteredCollection(newSel, Relation.class));
|
---|
217 | }
|
---|
218 | });
|
---|
219 | } else if (args.containsKey("search") && PermissionPrefWithDefault.CHANGE_SELECTION.isAllowed()) {
|
---|
220 | try {
|
---|
221 | final SearchCompiler.Match search = SearchCompiler.compile(args.get("search"));
|
---|
222 | MainApplication.worker.submit(() -> {
|
---|
223 | final DataSet ds = MainApplication.getLayerManager().getEditDataSet();
|
---|
224 | final Collection<OsmPrimitive> filteredPrimitives = SubclassFilteredCollection.filter(ds.allPrimitives(), search);
|
---|
225 | ds.setSelected(filteredPrimitives);
|
---|
226 | forTagAdd.addAll(filteredPrimitives);
|
---|
227 | zoom(filteredPrimitives, bbox);
|
---|
228 | });
|
---|
229 | } catch (SearchParseError ex) {
|
---|
230 | Logging.error(ex);
|
---|
231 | throw new RequestHandlerErrorException(ex);
|
---|
232 | }
|
---|
233 | } else {
|
---|
234 | // after downloading, zoom to downloaded area.
|
---|
235 | zoom(Collections.<OsmPrimitive>emptySet(), bbox);
|
---|
236 | }
|
---|
237 |
|
---|
238 | // This comes before the other changeset tags, so that they can be overridden
|
---|
239 | parseChangesetTags(args);
|
---|
240 |
|
---|
241 | // add changeset tags after download if necessary
|
---|
242 | if (args.containsKey("changeset_comment") || args.containsKey("changeset_source") || args.containsKey("changeset_hashtags")) {
|
---|
243 | MainApplication.worker.submit(() -> {
|
---|
244 | DataSet ds = MainApplication.getLayerManager().getEditDataSet();
|
---|
245 | if (ds != null) {
|
---|
246 | for (String tag : Arrays.asList("changeset_comment", "changeset_source", "changeset_hashtags")) {
|
---|
247 | if (args.containsKey(tag)) {
|
---|
248 | ds.addChangeSetTag(tag.substring("changeset_".length()), args.get(tag));
|
---|
249 | }
|
---|
250 | }
|
---|
251 | }
|
---|
252 | });
|
---|
253 | }
|
---|
254 |
|
---|
255 | // add tags to objects
|
---|
256 | if (args.containsKey("addtags")) {
|
---|
257 | // needs to run in EDT since forTagAdd is updated in EDT as well
|
---|
258 | GuiHelper.executeByMainWorkerInEDT(() -> {
|
---|
259 | if (!forTagAdd.isEmpty()) {
|
---|
260 | AddTagsDialog.addTags(args, sender, forTagAdd);
|
---|
261 | } else {
|
---|
262 | new Notification(isKeepingCurrentSelection
|
---|
263 | ? tr("You clicked on a JOSM remotecontrol link that would apply tags onto selected objects.\n"
|
---|
264 | + "Since no objects have been selected before this click, no tags were added.\n"
|
---|
265 | + "Select one or more objects and click the link again.")
|
---|
266 | : tr("You clicked on a JOSM remotecontrol link that would apply tags onto objects.\n"
|
---|
267 | + "Unfortunately that link seems to be broken.\n"
|
---|
268 | + "Technical explanation: the URL query parameter ''select='' or ''search='' has an invalid value.\n"
|
---|
269 | + "Ask someone at the origin of the clicked link to fix this.")
|
---|
270 | ).setIcon(JOptionPane.WARNING_MESSAGE).setDuration(Notification.TIME_LONG).show();
|
---|
271 | }
|
---|
272 | });
|
---|
273 | }
|
---|
274 | }
|
---|
275 |
|
---|
276 | static void parseChangesetTags(Map<String, String> args) {
|
---|
277 | if (args.containsKey("changeset_tags")) {
|
---|
278 | MainApplication.worker.submit(() -> {
|
---|
279 | DataSet ds = MainApplication.getLayerManager().getEditDataSet();
|
---|
280 | if (ds != null) {
|
---|
281 | AddTagsDialog.parseUrlTagsToKeyValues(args.get("changeset_tags")).forEach(ds::addChangeSetTag);
|
---|
282 | }
|
---|
283 | });
|
---|
284 | }
|
---|
285 | }
|
---|
286 |
|
---|
287 | protected void zoom(Collection<OsmPrimitive> primitives, final Bounds bbox) {
|
---|
288 | if (!PermissionPrefWithDefault.CHANGE_VIEWPORT.isAllowed()) {
|
---|
289 | return;
|
---|
290 | }
|
---|
291 | // zoom_mode=(download|selection), defaults to selection
|
---|
292 | if (!"download".equals(args.get("zoom_mode")) && !primitives.isEmpty()) {
|
---|
293 | AutoScaleAction.autoScale(AutoScaleMode.SELECTION);
|
---|
294 | } else if (MainApplication.isDisplayingMapView()) {
|
---|
295 | // make sure this isn't called unless there *is* a MapView
|
---|
296 | GuiHelper.executeByMainWorkerInEDT(() -> {
|
---|
297 | BoundingXYVisitor bbox1 = new BoundingXYVisitor();
|
---|
298 | bbox1.visit(bbox);
|
---|
299 | MainApplication.getMap().mapView.zoomTo(bbox1);
|
---|
300 | });
|
---|
301 | }
|
---|
302 | }
|
---|
303 |
|
---|
304 | @Override
|
---|
305 | public PermissionPrefWithDefault getPermissionPref() {
|
---|
306 | return null;
|
---|
307 | }
|
---|
308 |
|
---|
309 | @Override
|
---|
310 | protected void validateRequest() throws RequestHandlerBadRequestException {
|
---|
311 | validateDownloadParams();
|
---|
312 | // Process mandatory arguments
|
---|
313 | minlat = 0;
|
---|
314 | maxlat = 0;
|
---|
315 | minlon = 0;
|
---|
316 | maxlon = 0;
|
---|
317 | try {
|
---|
318 | minlat = LatLon.roundToOsmPrecision(Double.parseDouble(args != null ? args.get("bottom") : ""));
|
---|
319 | maxlat = LatLon.roundToOsmPrecision(Double.parseDouble(args != null ? args.get("top") : ""));
|
---|
320 | minlon = LatLon.roundToOsmPrecision(Double.parseDouble(args != null ? args.get("left") : ""));
|
---|
321 | maxlon = LatLon.roundToOsmPrecision(Double.parseDouble(args != null ? args.get("right") : ""));
|
---|
322 | } catch (NumberFormatException e) {
|
---|
323 | throw new RequestHandlerBadRequestException("NumberFormatException ("+e.getMessage()+')', e);
|
---|
324 | }
|
---|
325 |
|
---|
326 | // Current API 0.6 check: "The latitudes must be between -90 and 90"
|
---|
327 | if (!LatLon.isValidLat(minlat) || !LatLon.isValidLat(maxlat)) {
|
---|
328 | throw new RequestHandlerBadRequestException(tr("The latitudes must be between {0} and {1}", -90d, 90d));
|
---|
329 | }
|
---|
330 | // Current API 0.6 check: "longitudes between -180 and 180"
|
---|
331 | if (!LatLon.isValidLon(minlon) || !LatLon.isValidLon(maxlon)) {
|
---|
332 | throw new RequestHandlerBadRequestException(tr("The longitudes must be between {0} and {1}", -180d, 180d));
|
---|
333 | }
|
---|
334 | // Current API 0.6 check: "the minima must be less than the maxima"
|
---|
335 | if (minlat > maxlat || minlon > maxlon) {
|
---|
336 | throw new RequestHandlerBadRequestException(tr("The minima must be less than the maxima"));
|
---|
337 | }
|
---|
338 |
|
---|
339 | // Process optional argument 'select'
|
---|
340 | if (args != null && args.containsKey("select")) {
|
---|
341 | toSelect.clear();
|
---|
342 | for (String item : args.get("select").split(",", -1)) {
|
---|
343 | if (!item.isEmpty()) {
|
---|
344 | if (CURRENT_SELECTION.equalsIgnoreCase(item)) {
|
---|
345 | isKeepingCurrentSelection = true;
|
---|
346 | continue;
|
---|
347 | }
|
---|
348 | try {
|
---|
349 | toSelect.add(SimplePrimitiveId.fromString(item));
|
---|
350 | } catch (IllegalArgumentException ex) {
|
---|
351 | Logging.log(Logging.LEVEL_WARN, "RemoteControl: invalid selection '" + item + "' ignored", ex);
|
---|
352 | }
|
---|
353 | }
|
---|
354 | }
|
---|
355 | }
|
---|
356 | }
|
---|
357 | }
|
---|