source: josm/trunk/src/org/openstreetmap/josm/gui/layer/OsmDataLayer.java

Last change on this file was 18753, checked in by taylor.smock, 12 months ago

Fix #23001: ClassCastException in GpxDrawHelper#calculateColors

This occurs when a working GPX file with HDOP information is converted to an OSM
Data Layer and back to a GPX Data Layer. This is fixed by (a) converting casts
for get operations to Number instead of Float/Integer and (b) actually
putting the number in the attribute map instead of a string.

  • Property svn:eol-style set to native
File size: 52.2 KB
RevLine 
[8378]1// License: GPL. For details, see LICENSE file.
[444]2package org.openstreetmap.josm.gui.layer;
3
[2381]4import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
[786]5import static org.openstreetmap.josm.tools.I18n.marktr;
[444]6import static org.openstreetmap.josm.tools.I18n.tr;
7import static org.openstreetmap.josm.tools.I18n.trn;
8
[1082]9import java.awt.AlphaComposite;
[444]10import java.awt.Color;
[1082]11import java.awt.Composite;
[1078]12import java.awt.Graphics2D;
[444]13import java.awt.GridBagLayout;
[1078]14import java.awt.Rectangle;
15import java.awt.TexturePaint;
[14500]16import java.awt.datatransfer.Transferable;
17import java.awt.datatransfer.UnsupportedFlavorException;
[444]18import java.awt.event.ActionEvent;
[1078]19import java.awt.geom.Area;
[11633]20import java.awt.geom.Path2D;
[10806]21import java.awt.geom.Rectangle2D;
[1078]22import java.awt.image.BufferedImage;
[444]23import java.io.File;
[14500]24import java.io.IOException;
[17166]25import java.time.DateTimeException;
[1523]26import java.util.ArrayList;
[5025]27import java.util.Arrays;
[444]28import java.util.Collection;
[7414]29import java.util.Collections;
[2907]30import java.util.HashMap;
[444]31import java.util.HashSet;
[3669]32import java.util.List;
[2907]33import java.util.Map;
[15496]34import java.util.Map.Entry;
[16438]35import java.util.Objects;
[8338]36import java.util.Set;
[5519]37import java.util.concurrent.CopyOnWriteArrayList;
[13133]38import java.util.concurrent.atomic.AtomicBoolean;
[11033]39import java.util.concurrent.atomic.AtomicInteger;
[8956]40import java.util.regex.Pattern;
[16438]41import java.util.stream.Collectors;
42import java.util.stream.Stream;
[444]43
44import javax.swing.AbstractAction;
[3408]45import javax.swing.Action;
[444]46import javax.swing.Icon;
47import javax.swing.JLabel;
48import javax.swing.JOptionPane;
49import javax.swing.JPanel;
[2500]50import javax.swing.JScrollPane;
[444]51
[16967]52import org.openstreetmap.josm.actions.AutoScaleAction;
[5025]53import org.openstreetmap.josm.actions.ExpertToggleAction;
[444]54import org.openstreetmap.josm.actions.RenameLayerAction;
[5025]55import org.openstreetmap.josm.actions.ToggleUploadDiscouragedLayerAction;
[7358]56import org.openstreetmap.josm.data.APIDataSet;
[2450]57import org.openstreetmap.josm.data.Bounds;
[16548]58import org.openstreetmap.josm.data.Data;
[10371]59import org.openstreetmap.josm.data.ProjectionBounds;
[14134]60import org.openstreetmap.josm.data.UndoRedoHandler;
[1750]61import org.openstreetmap.josm.data.conflict.Conflict;
62import org.openstreetmap.josm.data.conflict.ConflictCollection;
[10806]63import org.openstreetmap.josm.data.coor.EastNorth;
[628]64import org.openstreetmap.josm.data.coor.LatLon;
[7518]65import org.openstreetmap.josm.data.gpx.GpxConstants;
[1523]66import org.openstreetmap.josm.data.gpx.GpxData;
[15496]67import org.openstreetmap.josm.data.gpx.GpxExtensionCollection;
[7518]68import org.openstreetmap.josm.data.gpx.GpxLink;
[15496]69import org.openstreetmap.josm.data.gpx.GpxTrack;
70import org.openstreetmap.josm.data.gpx.GpxTrackSegment;
71import org.openstreetmap.josm.data.gpx.IGpxTrackSegment;
[1523]72import org.openstreetmap.josm.data.gpx.WayPoint;
[3965]73import org.openstreetmap.josm.data.osm.DataIntegrityProblemException;
[12152]74import org.openstreetmap.josm.data.osm.DataSelectionListener;
[444]75import org.openstreetmap.josm.data.osm.DataSet;
[2434]76import org.openstreetmap.josm.data.osm.DataSetMerger;
[2500]77import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
[13852]78import org.openstreetmap.josm.data.osm.DownloadPolicy;
[12014]79import org.openstreetmap.josm.data.osm.HighlightUpdateListener;
[4534]80import org.openstreetmap.josm.data.osm.IPrimitive;
[444]81import org.openstreetmap.josm.data.osm.Node;
82import org.openstreetmap.josm.data.osm.OsmPrimitive;
[8807]83import org.openstreetmap.josm.data.osm.OsmPrimitiveComparator;
[1523]84import org.openstreetmap.josm.data.osm.Relation;
[14075]85import org.openstreetmap.josm.data.osm.Tagged;
[13852]86import org.openstreetmap.josm.data.osm.UploadPolicy;
[444]87import org.openstreetmap.josm.data.osm.Way;
[3116]88import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
89import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter;
90import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter.Listener;
[444]91import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
[12809]92import org.openstreetmap.josm.data.osm.visitor.OsmPrimitiveVisitor;
[13987]93import org.openstreetmap.josm.data.osm.visitor.paint.AbstractMapRenderer;
[4087]94import org.openstreetmap.josm.data.osm.visitor.paint.MapRendererFactory;
[4623]95import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
[14060]96import org.openstreetmap.josm.data.preferences.BooleanProperty;
[9668]97import org.openstreetmap.josm.data.preferences.IntegerProperty;
[12987]98import org.openstreetmap.josm.data.preferences.NamedColorProperty;
[9721]99import org.openstreetmap.josm.data.preferences.StringProperty;
[4126]100import org.openstreetmap.josm.data.projection.Projection;
[3669]101import org.openstreetmap.josm.data.validation.TestError;
[5459]102import org.openstreetmap.josm.gui.ExtendedDialog;
[12630]103import org.openstreetmap.josm.gui.MainApplication;
104import org.openstreetmap.josm.gui.MapFrame;
[444]105import org.openstreetmap.josm.gui.MapView;
[10806]106import org.openstreetmap.josm.gui.MapViewState.MapViewPoint;
[14500]107import org.openstreetmap.josm.gui.datatransfer.ClipboardUtils;
108import org.openstreetmap.josm.gui.datatransfer.data.OsmLayerTransferData;
[444]109import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
110import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
[7358]111import org.openstreetmap.josm.gui.io.AbstractIOTask;
112import org.openstreetmap.josm.gui.io.AbstractUploadDialog;
113import org.openstreetmap.josm.gui.io.UploadDialog;
114import org.openstreetmap.josm.gui.io.UploadLayerTask;
[14668]115import org.openstreetmap.josm.gui.io.importexport.NoteExporter;
[16548]116import org.openstreetmap.josm.gui.io.importexport.OsmExporter;
[12671]117import org.openstreetmap.josm.gui.io.importexport.OsmImporter;
[14668]118import org.openstreetmap.josm.gui.io.importexport.ValidatorErrorExporter;
119import org.openstreetmap.josm.gui.io.importexport.WMSLayerImporter;
[8805]120import org.openstreetmap.josm.gui.layer.markerlayer.MarkerLayer;
[14648]121import org.openstreetmap.josm.gui.preferences.display.DrawingPreference;
[4684]122import org.openstreetmap.josm.gui.progress.ProgressMonitor;
[12675]123import org.openstreetmap.josm.gui.progress.swing.PleaseWaitProgressMonitor;
[7204]124import org.openstreetmap.josm.gui.util.GuiHelper;
[16080]125import org.openstreetmap.josm.gui.util.LruCache;
[9670]126import org.openstreetmap.josm.gui.widgets.FileChooserManager;
[5886]127import org.openstreetmap.josm.gui.widgets.JosmTextArea;
[12846]128import org.openstreetmap.josm.spi.preferences.Config;
[11033]129import org.openstreetmap.josm.tools.AlphanumComparator;
[8910]130import org.openstreetmap.josm.tools.CheckParameterUtil;
[444]131import org.openstreetmap.josm.tools.GBC;
[8323]132import org.openstreetmap.josm.tools.ImageOverlay;
[444]133import org.openstreetmap.josm.tools.ImageProvider;
[8323]134import org.openstreetmap.josm.tools.ImageProvider.ImageSizes;
[12620]135import org.openstreetmap.josm.tools.Logging;
[14430]136import org.openstreetmap.josm.tools.UncheckedParseException;
[18208]137import org.openstreetmap.josm.tools.Utils;
[7299]138import org.openstreetmap.josm.tools.date.DateUtils;
[444]139
140/**
[5275]141 * A layer that holds OSM data from a specific dataset.
[444]142 * The data can be fully edited.
[1169]143 *
[444]144 * @author imi
[7414]145 * @since 17
[444]146 */
[13926]147public class OsmDataLayer extends AbstractOsmDataLayer implements Listener, DataSelectionListener, HighlightUpdateListener {
[10806]148 private static final int HATCHED_SIZE = 15;
[17757]149 // U+2205 EMPTY SET
150 private static final String IS_EMPTY_SYMBOL = "\u2205";
[7414]151 /** Property used to know if this layer has to be uploaded */
[6889]152 public static final String REQUIRES_UPLOAD_TO_SERVER_PROP = OsmDataLayer.class.getName() + ".requiresUploadToServer";
[444]153
[8840]154 private boolean requiresSaveToFile;
155 private boolean requiresUploadToServer;
[13434]156 /** Flag used to know if the layer is being uploaded */
157 private final AtomicBoolean isUploadInProgress = new AtomicBoolean(false);
[2025]158
[6436]159 /**
160 * List of validation errors in this layer.
161 * @since 3669
162 */
[7005]163 public final List<TestError> validationErrors = new ArrayList<>();
[3669]164
[12115]165 /**
166 * The default number of relations in the recent relations cache.
167 * @see #getRecentRelations()
168 */
[9668]169 public static final int DEFAULT_RECENT_RELATIONS_NUMBER = 20;
[12115]170 /**
171 * The number of relations to use in the recent relations cache.
172 * @see #getRecentRelations()
173 */
[9668]174 public static final IntegerProperty PROPERTY_RECENT_RELATIONS_NUMBER = new IntegerProperty("properties.last-closed-relations-size",
175 DEFAULT_RECENT_RELATIONS_NUMBER);
[12115]176 /**
177 * The extension that should be used when saving the OSM file.
178 */
[9721]179 public static final StringProperty PROPERTY_SAVE_EXTENSION = new StringProperty("save.extension.osm", "osm");
[9668]180
[14060]181 /**
182 * Property to determine if labels must be hidden while dragging the map.
183 */
184 public static final BooleanProperty PROPERTY_HIDE_LABELS_WHILE_DRAGGING = new BooleanProperty("mappaint.hide.labels.while.dragging", true);
185
[12987]186 private static final NamedColorProperty PROPERTY_BACKGROUND_COLOR = new NamedColorProperty(marktr("background"), Color.BLACK);
187 private static final NamedColorProperty PROPERTY_OUTSIDE_COLOR = new NamedColorProperty(marktr("outside downloaded area"), Color.YELLOW);
[9721]188
[9668]189 /** List of recent relations */
[16080]190 private final Map<Relation, Void> recentRelations = new LruCache<>(PROPERTY_RECENT_RELATIONS_NUMBER.get());
[9668]191
192 /**
193 * Returns list of recently closed relations or null if none.
[9679]194 * @return list of recently closed relations or <code>null</code> if none
[12291]195 * @since 12291 (signature)
[9679]196 * @since 9668
[9668]197 */
[12291]198 public List<Relation> getRecentRelations() {
[9971]199 ArrayList<Relation> list = new ArrayList<>(recentRelations.keySet());
[9668]200 Collections.reverse(list);
201 return list;
202 }
203
[9678]204 /**
[9679]205 * Adds recently closed relation.
206 * @param relation new entry for the list of recently closed relations
[12116]207 * @see #PROPERTY_RECENT_RELATIONS_NUMBER
[9679]208 * @since 9668
[9678]209 */
[9668]210 public void setRecentRelation(Relation relation) {
211 recentRelations.put(relation, null);
[12630]212 MapFrame map = MainApplication.getMap();
213 if (map != null && map.relationListDialog != null) {
214 map.relationListDialog.enableRecentRelations();
[10280]215 }
[9668]216 }
217
[9678]218 /**
219 * Remove relation from list of recent relations.
220 * @param relation relation to remove
[9679]221 * @since 9668
[9678]222 */
[9668]223 public void removeRecentRelation(Relation relation) {
224 recentRelations.remove(relation);
[12630]225 MapFrame map = MainApplication.getMap();
226 if (map != null && map.relationListDialog != null) {
227 map.relationListDialog.enableRecentRelations();
[10280]228 }
[9668]229 }
230
[2025]231 protected void setRequiresSaveToFile(boolean newValue) {
232 boolean oldValue = requiresSaveToFile;
233 requiresSaveToFile = newValue;
234 if (oldValue != newValue) {
[13462]235 GuiHelper.runInEDT(() ->
236 propertyChangeSupport.firePropertyChange(REQUIRES_SAVE_TO_DISK_PROP, oldValue, newValue)
237 );
[2025]238 }
239 }
240
241 protected void setRequiresUploadToServer(boolean newValue) {
242 boolean oldValue = requiresUploadToServer;
243 requiresUploadToServer = newValue;
244 if (oldValue != newValue) {
[13462]245 GuiHelper.runInEDT(() ->
246 propertyChangeSupport.firePropertyChange(REQUIRES_UPLOAD_TO_SERVER_PROP, oldValue, newValue)
247 );
[2025]248 }
249 }
250
[1750]251 /** the global counter for created data layers */
[11033]252 private static final AtomicInteger dataLayerCounter = new AtomicInteger();
[1750]253
254 /**
255 * Replies a new unique name for a data layer
[1843]256 *
[1750]257 * @return a new unique name for a data layer
258 */
[6889]259 public static String createNewName() {
[11033]260 return createLayerName(dataLayerCounter.incrementAndGet());
[1750]261 }
262
[11033]263 static String createLayerName(Object arg) {
264 return tr("Data Layer {0}", arg);
265 }
266
[12115]267 /**
268 * A listener that counts the number of primitives it encounters
269 */
[12809]270 public static final class DataCountVisitor implements OsmPrimitiveVisitor {
[12115]271 /**
272 * Nodes that have been visited
273 */
[2386]274 public int nodes;
[12115]275 /**
276 * Ways that have been visited
277 */
[2386]278 public int ways;
[12115]279 /**
280 * Relations that have been visited
281 */
[2386]282 public int relations;
[12115]283 /**
284 * Deleted nodes that have been visited
285 */
[2386]286 public int deletedNodes;
[12115]287 /**
288 * Deleted ways that have been visited
289 */
[2386]290 public int deletedWays;
[12115]291 /**
292 * Deleted relations that have been visited
293 */
[2386]294 public int deletedRelations;
[15280]295 /**
296 * Incomplete nodes that have been visited
297 */
298 public int incompleteNodes;
299 /**
300 * Incomplete ways that have been visited
301 */
302 public int incompleteWays;
303 /**
304 * Incomplete relations that have been visited
305 */
306 public int incompleteRelations;
[444]307
[6084]308 @Override
[2386]309 public void visit(final Node n) {
310 nodes++;
311 if (n.isDeleted()) {
312 deletedNodes++;
[1670]313 }
[15280]314 if (n.isIncomplete()) {
315 incompleteNodes++;
316 }
[1078]317 }
[444]318
[6084]319 @Override
[2386]320 public void visit(final Way w) {
321 ways++;
322 if (w.isDeleted()) {
323 deletedWays++;
324 }
[15280]325 if (w.isIncomplete()) {
326 incompleteWays++;
327 }
[1078]328 }
[444]329
[6084]330 @Override
[2386]331 public void visit(final Relation r) {
332 relations++;
333 if (r.isDeleted()) {
334 deletedRelations++;
335 }
[15280]336 if (r.isIncomplete()) {
337 incompleteRelations++;
338 }
[1078]339 }
340 }
[444]341
[12115]342 /**
[5519]343 * Listener called when a state of this layer has changed.
[10600]344 * @since 10600 (functional interface)
[5519]345 */
[10600]346 @FunctionalInterface
[5519]347 public interface LayerStateChangeListener {
348 /**
349 * Notifies that the "upload discouraged" (upload=no) state has changed.
350 * @param layer The layer that has been modified
351 * @param newValue The new value of the state
352 */
353 void uploadDiscouragedChanged(OsmDataLayer layer, boolean newValue);
354 }
[6070]355
[7005]356 private final CopyOnWriteArrayList<LayerStateChangeListener> layerStateChangeListeners = new CopyOnWriteArrayList<>();
[6070]357
[5519]358 /**
359 * Adds a layer state change listener
360 *
361 * @param listener the listener. Ignored if null or already registered.
362 * @since 5519
363 */
364 public void addLayerStateChangeListener(LayerStateChangeListener listener) {
365 if (listener != null) {
366 layerStateChangeListeners.addIfAbsent(listener);
367 }
368 }
[6070]369
[5519]370 /**
[10340]371 * Removes a layer state change listener
[5519]372 *
373 * @param listener the listener. Ignored if null or already registered.
[10340]374 * @since 10340
375 */
376 public void removeLayerStateChangeListener(LayerStateChangeListener listener) {
[5519]377 layerStateChangeListeners.remove(listener);
378 }
[444]379
[1078]380 /**
381 * The data behind this layer.
382 */
383 public final DataSet data;
[16913]384 private final DataSetListenerAdapter dataSetListenerAdapter;
[444]385
[1078]386 /**
[10806]387 * a texture for non-downloaded area
[1078]388 */
[10806]389 private static volatile BufferedImage hatched;
[1169]390
[1082]391 static {
392 createHatchTexture();
393 }
394
[7414]395 /**
396 * Replies background color for downloaded areas.
397 * @return background color for downloaded areas. Black by default
398 */
[3233]399 public static Color getBackgroundColor() {
[10853]400 return PROPERTY_BACKGROUND_COLOR.get();
[3233]401 }
402
[7414]403 /**
404 * Replies background color for non-downloaded areas.
405 * @return background color for non-downloaded areas. Yellow by default
406 */
[3233]407 public static Color getOutsideColor() {
[10853]408 return PROPERTY_OUTSIDE_COLOR.get();
[3233]409 }
410
[1078]411 /**
[1082]412 * Initialize the hatch pattern used to paint the non-downloaded area
[1078]413 */
[1082]414 public static void createHatchTexture() {
[10806]415 BufferedImage bi = new BufferedImage(HATCHED_SIZE, HATCHED_SIZE, BufferedImage.TYPE_INT_ARGB);
[1078]416 Graphics2D big = bi.createGraphics();
[3233]417 big.setColor(getBackgroundColor());
[1082]418 Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
419 big.setComposite(comp);
[10806]420 big.fillRect(0, 0, HATCHED_SIZE, HATCHED_SIZE);
[3233]421 big.setColor(getOutsideColor());
[10344]422 big.drawLine(-1, 6, 6, -1);
423 big.drawLine(4, 16, 16, 4);
[10806]424 hatched = bi;
[1078]425 }
[444]426
[1078]427 /**
[7414]428 * Construct a new {@code OsmDataLayer}.
429 * @param data OSM data
430 * @param name Layer name
431 * @param associatedFile Associated .osm file (can be null)
[1082]432 */
433 public OsmDataLayer(final DataSet data, final String name, final File associatedFile) {
434 super(name);
[8910]435 CheckParameterUtil.ensureParameterNotNull(data, "data");
[1082]436 this.data = data;
[12718]437 this.data.setName(name);
[14556]438 this.dataSetListenerAdapter = new DataSetListenerAdapter(this);
[1646]439 this.setAssociatedFile(associatedFile);
[14556]440 data.addDataSetListener(dataSetListenerAdapter);
[4623]441 data.addDataSetListener(MultipolygonCache.getInstance());
[12014]442 data.addHighlightUpdateListener(this);
[12152]443 data.addSelectionListener(this);
[11277]444 if (name != null && name.startsWith(createLayerName("")) && Character.isDigit(
445 (name.substring(createLayerName("").length()) + "XX" /*avoid StringIndexOutOfBoundsException*/).charAt(1))) {
[11033]446 while (AlphanumComparator.getInstance().compare(createLayerName(dataLayerCounter), name) < 0) {
[11261]447 final int i = dataLayerCounter.incrementAndGet();
448 if (i > 1_000_000) {
449 break; // to avoid looping in unforeseen case
450 }
[11033]451 }
452 }
[1082]453 }
454
[8323]455 /**
[13558]456 * Returns the {@link DataSet} behind this layer.
457 * @return the {@link DataSet} behind this layer.
458 * @since 13558
459 */
[13926]460 @Override
[13558]461 public DataSet getDataSet() {
462 return data;
463 }
464
465 /**
[8323]466 * Return the image provider to get the base icon
467 * @return image provider class which can be modified
468 * @since 8323
469 */
470 protected ImageProvider getBaseIconProvider() {
471 return new ImageProvider("layer", "osmdata_small");
[5025]472 }
[6070]473
[8323]474 @Override
475 public Icon getIcon() {
476 ImageProvider base = getBaseIconProvider().setMaxSize(ImageSizes.LAYER);
[13453]477 if (data.getDownloadPolicy() != null && data.getDownloadPolicy() != DownloadPolicy.NORMAL) {
478 base.addOverlay(new ImageOverlay(new ImageProvider("warning-small"), 0.5, 0.0, 1.0, 0.5));
479 }
480 if (data.getUploadPolicy() != null && data.getUploadPolicy() != UploadPolicy.NORMAL) {
[8323]481 base.addOverlay(new ImageOverlay(new ImageProvider("warning-small"), 0.5, 0.5, 1.0, 1.0));
[5025]482 }
[13133]483
[13434]484 if (isUploadInProgress()) {
485 // If the layer is being uploaded then change the default icon to a clock
[13133]486 base = new ImageProvider("clock").setMaxSize(ImageSizes.LAYER);
[13453]487 } else if (isLocked()) {
[13434]488 // If the layer is read only then change the default icon to a lock
489 base = new ImageProvider("lock").setMaxSize(ImageSizes.LAYER);
[13133]490 }
[8323]491 return base.get();
[1078]492 }
[444]493
[1078]494 /**
495 * Draw all primitives in this layer but do not draw modified ones (they
496 * are drawn by the edit layer).
497 * Draw nodes last to overlap the ways they belong to.
498 */
[2450]499 @Override public void paint(final Graphics2D g, final MapView mv, Bounds box) {
[10395]500 boolean active = mv.getLayerManager().getActiveLayer() == this;
[12846]501 boolean inactive = !active && Config.getPref().getBoolean("draw.data.inactive_color", true);
[1823]502 boolean virtual = !inactive && mv.isVirtualNodesEnabled();
[1169]503
504 // draw the hatched area for non-downloaded region. only draw if we're the active
[1083]505 // and bounds are defined; don't draw for inactive layers or loaded GPX files etc
[14648]506 if (active && DrawingPreference.SOURCE_BOUNDS_PROP.get() && !data.getDataSources().isEmpty()) {
[1078]507 // initialize area with current viewport
[1823]508 Rectangle b = mv.getBounds();
[1169]509 // on some platforms viewport bounds seem to be offset from the left,
[1083]510 // over-grow it just to be sure
511 b.grow(100, 100);
[11633]512 Path2D p = new Path2D.Double();
[1169]513
[11633]514 // combine successively downloaded areas
[4087]515 for (Bounds bounds : data.getDataSourceBounds()) {
516 if (bounds.isCollapsed()) {
517 continue;
[1078]518 }
[11633]519 p.append(mv.getState().getArea(bounds), false);
[1078]520 }
[11633]521 // subtract combined areas
522 Area a = new Area(b);
523 a.subtract(new Area(p));
[1169]524
[1078]525 // paint remainder
[10806]526 MapViewPoint anchor = mv.getState().getPointFor(new EastNorth(0, 0));
527 Rectangle2D anchorRect = new Rectangle2D.Double(anchor.getInView().getX() % HATCHED_SIZE,
528 anchor.getInView().getY() % HATCHED_SIZE, HATCHED_SIZE, HATCHED_SIZE);
[14037]529 if (hatched != null) {
530 g.setPaint(new TexturePaint(hatched, anchorRect));
531 }
[14182]532 try {
[14648]533 g.fill(a);
[14182]534 } catch (ArrayIndexOutOfBoundsException e) {
535 // #16686 - AIOOBE in java.awt.TexturePaintContext$Int.setRaster
536 Logging.error(e);
537 }
[1078]538 }
[1169]539
[13987]540 AbstractMapRenderer painter = MapRendererFactory.getInstance().createActiveRenderer(g, mv, inactive);
[14060]541 painter.enableSlowOperations(mv.getMapMover() == null || !mv.getMapMover().movementInProgress()
542 || !PROPERTY_HIDE_LABELS_WHILE_DRAGGING.get());
[4087]543 painter.render(data, virtual, box);
[12630]544 MainApplication.getMap().conflictDialog.paintConflicts(g, mv);
[1078]545 }
[444]546
[1078]547 @Override public String getToolTipText() {
[12153]548 DataCountVisitor counter = new DataCountVisitor();
549 for (final OsmPrimitive osm : data.allPrimitives()) {
550 osm.accept(counter);
551 }
552 int nodes = counter.nodes - counter.deletedNodes;
553 int ways = counter.ways - counter.deletedWays;
554 int rels = counter.relations - counter.deletedRelations;
[2386]555
[12160]556 StringBuilder tooltip = new StringBuilder("<html>")
557 .append(trn("{0} node", "{0} nodes", nodes, nodes))
558 .append("<br>")
559 .append(trn("{0} way", "{0} ways", ways, ways))
560 .append("<br>")
561 .append(trn("{0} relation", "{0} relations", rels, rels));
[2386]562
[1646]563 File f = getAssociatedFile();
[1670]564 if (f != null) {
[12160]565 tooltip.append("<br>").append(f.getPath());
[1670]566 }
[12153]567 tooltip.append("</html>");
568 return tooltip.toString();
[1078]569 }
[444]570
[1078]571 @Override public void mergeFrom(final Layer from) {
[4684]572 final PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Merging layers"));
573 monitor.setCancelable(false);
[8510]574 if (from instanceof OsmDataLayer && ((OsmDataLayer) from).isUploadDiscouraged()) {
[5233]575 setUploadDiscouraged(true);
576 }
[8510]577 mergeFrom(((OsmDataLayer) from).data, monitor);
[4684]578 monitor.close();
[1670]579 }
580
581 /**
582 * merges the primitives in dataset <code>from</code> into the dataset of
583 * this layer
[1677]584 *
[1670]585 * @param from the source data set
586 */
587 public void mergeFrom(final DataSet from) {
[4684]588 mergeFrom(from, null);
589 }
[6070]590
[4684]591 /**
[9674]592 * merges the primitives in dataset <code>from</code> into the dataset of this layer
[4684]593 *
594 * @param from the source data set
[5869]595 * @param progressMonitor the progress monitor, can be {@code null}
[4684]596 */
597 public void mergeFrom(final DataSet from, ProgressMonitor progressMonitor) {
[8510]598 final DataSetMerger visitor = new DataSetMerger(data, from);
[3965]599 try {
[4684]600 visitor.merge(progressMonitor);
[3965]601 } catch (DataIntegrityProblemException e) {
[12620]602 Logging.error(e);
[3965]603 JOptionPane.showMessageDialog(
[14153]604 MainApplication.getMainFrame(),
[5059]605 e.getHtmlMessage() != null ? e.getHtmlMessage() : e.getMessage(),
[3965]606 tr("Error"),
607 JOptionPane.ERROR_MESSAGE
608 );
609 return;
610 }
611
[1750]612 int numNewConflicts = 0;
[2198]613 for (Conflict<?> c : visitor.getConflicts()) {
[12672]614 if (!data.getConflicts().hasConflict(c)) {
[1750]615 numNewConflicts++;
[12672]616 data.getConflicts().add(c);
[1750]617 }
[1670]618 }
[2198]619 // repaint to make sure new data is displayed properly.
[12176]620 invalidate();
[5869]621 // warn about new conflicts
[12630]622 MapFrame map = MainApplication.getMap();
623 if (numNewConflicts > 0 && map != null && map.conflictDialog != null) {
624 map.conflictDialog.warnNumNewConflicts(numNewConflicts);
[5869]625 }
[2198]626 }
627
[8510]628 @Override
629 public boolean isMergable(final Layer other) {
[8855]630 // allow merging between normal layers and discouraged layers with a warning (see #7684)
631 return other instanceof OsmDataLayer;
[1078]632 }
[444]633
[8510]634 @Override
635 public void visitBoundingBox(final BoundingXYVisitor v) {
[2381]636 for (final Node n: data.getNodes()) {
[2120]637 if (n.isUsable()) {
[1078]638 v.visit(n);
[1670]639 }
[2381]640 }
[1078]641 }
[444]642
[1078]643 /**
644 * Clean out the data behind the layer. This means clearing the redo/undo lists,
[1894]645 * really deleting all deleted objects and reset the modified flags. This should
646 * be done after an upload, even after a partial upload.
[1169]647 *
648 * @param processed A list of all objects that were actually uploaded.
[1894]649 * May be <code>null</code>, which means nothing has been uploaded
[1078]650 */
[10205]651 public void cleanupAfterUpload(final Collection<? extends IPrimitive> processed) {
[1078]652 // return immediately if an upload attempt failed
[18208]653 if (Utils.isEmpty(processed))
[1078]654 return;
[1169]655
[17399]656 UndoRedoHandler.getInstance().clean(data);
[444]657
[1078]658 // if uploaded, clean the modified flags as well
[3426]659 data.cleanupDeletedPrimitives();
[16187]660 data.update(() -> {
[9941]661 for (OsmPrimitive p: data.allPrimitives()) {
662 if (processed.contains(p)) {
663 p.setModified(false);
664 }
[3206]665 }
[16187]666 });
[1078]667 }
[444]668
[15280]669 private static String counterText(String text, int deleted, int incomplete) {
670 StringBuilder sb = new StringBuilder(text);
671 if (deleted > 0 || incomplete > 0) {
672 sb.append(" (");
673 if (deleted > 0) {
674 sb.append(trn("{0} deleted", "{0} deleted", deleted, deleted));
675 }
676 if (deleted > 0 && incomplete > 0) {
677 sb.append(", ");
678 }
679 if (incomplete > 0) {
680 sb.append(trn("{0} incomplete", "{0} incomplete", incomplete, incomplete));
681 }
682 sb.append(')');
683 }
684 return sb.toString();
685 }
686
[8510]687 @Override
688 public Object getInfoComponent() {
[1078]689 final DataCountVisitor counter = new DataCountVisitor();
[1670]690 for (final OsmPrimitive osm : data.allPrimitives()) {
[6009]691 osm.accept(counter);
[1670]692 }
[1078]693 final JPanel p = new JPanel(new GridBagLayout());
[2386]694
[15280]695 String nodeText = counterText(trn("{0} node", "{0} nodes", counter.nodes, counter.nodes),
696 counter.deletedNodes, counter.incompleteNodes);
697 String wayText = counterText(trn("{0} way", "{0} ways", counter.ways, counter.ways),
698 counter.deletedWays, counter.incompleteWays);
699 String relationText = counterText(trn("{0} relation", "{0} relations", counter.relations, counter.relations),
700 counter.deletedRelations, counter.incompleteRelations);
[2386]701
[1890]702 p.add(new JLabel(tr("{0} consists of:", getName())), GBC.eol());
[8510]703 p.add(new JLabel(nodeText, ImageProvider.get("data", "node"), JLabel.HORIZONTAL), GBC.eop().insets(15, 0, 0, 0));
704 p.add(new JLabel(wayText, ImageProvider.get("data", "way"), JLabel.HORIZONTAL), GBC.eop().insets(15, 0, 0, 0));
705 p.add(new JLabel(relationText, ImageProvider.get("data", "relation"), JLabel.HORIZONTAL), GBC.eop().insets(15, 0, 0, 0));
706 p.add(new JLabel(tr("API version: {0}", (data.getVersion() != null) ? data.getVersion() : tr("unset"))),
707 GBC.eop().insets(15, 0, 0, 0));
[15824]708 addConditionalInformation(p, tr("Layer is locked"), isLocked());
709 addConditionalInformation(p, tr("Download is blocked"), data.getDownloadPolicy() == DownloadPolicy.BLOCKED);
710 addConditionalInformation(p, tr("Upload is discouraged"), isUploadDiscouraged());
711 addConditionalInformation(p, tr("Upload is blocked"), data.getUploadPolicy() == UploadPolicy.BLOCKED);
[17757]712 addConditionalInformation(p, IS_EMPTY_SYMBOL + " " + tr("Empty layer"), this.getDataSet().isEmpty());
713 addConditionalInformation(p, IS_DIRTY_SYMBOL + " " + tr("Unsaved changes"), this.isDirty());
[1523]714
[1078]715 return p;
716 }
[444]717
[15824]718 private static void addConditionalInformation(JPanel p, String text, boolean condition) {
719 if (condition) {
720 p.add(new JLabel(text), GBC.eop().insets(15, 0, 0, 0));
721 }
722 }
723
724 @Override
725 public Action[] getMenuEntries() {
[16967]726 List<Action> actions = new ArrayList<>(Arrays.asList(
[3408]727 LayerListDialog.getInstance().createActivateLayerAction(this),
728 LayerListDialog.getInstance().createShowHideLayerAction(),
[16967]729 MainApplication.getMenu().autoScaleActions.get(AutoScaleAction.AutoScaleMode.LAYER),
[3408]730 LayerListDialog.getInstance().createDeleteLayerAction(),
731 SeparatorLayerAction.INSTANCE,
732 LayerListDialog.getInstance().createMergeLayerAction(this),
[8728]733 LayerListDialog.getInstance().createDuplicateLayerAction(this),
[3408]734 new LayerSaveAction(this),
[12279]735 new LayerSaveAsAction(this)));
[6039]736 if (ExpertToggleAction.isExpert()) {
[12279]737 actions.addAll(Arrays.asList(
[6039]738 new LayerGpxExportAction(this),
[12279]739 new ConvertToGpxLayerAction()));
[6039]740 }
[12279]741 actions.addAll(Arrays.asList(
[3408]742 SeparatorLayerAction.INSTANCE,
[12279]743 new RenameLayerAction(getAssociatedFile(), this)));
[9873]744 if (ExpertToggleAction.isExpert()) {
[5025]745 actions.add(new ToggleUploadDiscouragedLayerAction(this));
746 }
[12279]747 actions.addAll(Arrays.asList(
[3408]748 new ConsistencyTestAction(),
749 SeparatorLayerAction.INSTANCE,
[12279]750 new LayerListPopup.InfoAction(this)));
[13206]751 return actions.toArray(new Action[0]);
[1078]752 }
[444]753
[7414]754 /**
755 * Converts given OSM dataset to GPX data.
756 * @param data OSM dataset
757 * @param file output .gpx file
758 * @return GPX data
759 */
[1508]760 public static GpxData toGpxData(DataSet data, File file) {
[18466]761 GpxData gpxData = new GpxData(true);
[18078]762 fillGpxData(gpxData, data, file, GpxConstants.GPX_PREFIX);
[18466]763 gpxData.endUpdate();
[18078]764 return gpxData;
765 }
766
767 protected static void fillGpxData(GpxData gpxData, DataSet data, File file, String gpxPrefix) {
[15496]768 if (data.getGPXNamespaces() != null) {
769 gpxData.getNamespaces().addAll(data.getGPXNamespaces());
770 }
[1508]771 gpxData.storageFile = file;
[8338]772 Set<Node> doneNodes = new HashSet<>();
[18078]773 waysToGpxData(data.getWays(), gpxData, doneNodes, gpxPrefix);
774 nodesToGpxData(data.getNodes(), gpxData, doneNodes, gpxPrefix);
[7414]775 }
776
[18078]777 private static void waysToGpxData(Collection<Way> ways, GpxData gpxData, Set<Node> doneNodes, String gpxPrefix) {
[8807]778 /* When the dataset has been obtained from a gpx layer and now is being converted back,
779 * the ways have negative ids. The first created way corresponds to the first gpx segment,
780 * and has the highest id (i.e., closest to zero).
781 * Thus, sorting by OsmPrimitive#getUniqueId gives the original order.
782 * (Only works if the data layer has not been saved to and been loaded from an osm file before.)
783 */
[11177]784 ways.stream()
785 .sorted(OsmPrimitiveComparator.comparingUniqueId().reversed())
786 .forEachOrdered(w -> {
[2120]787 if (!w.isUsable()) {
[11177]788 return;
[1670]789 }
[15496]790 List<IGpxTrackSegment> trk = new ArrayList<>();
[7005]791 Map<String, Object> trkAttr = new HashMap<>();
[508]792
[15496]793 GpxExtensionCollection trkExts = new GpxExtensionCollection();
794 GpxExtensionCollection segExts = new GpxExtensionCollection();
795 for (Entry<String, String> e : w.getKeys().entrySet()) {
[18078]796 String k = e.getKey().startsWith(gpxPrefix) ? e.getKey().substring(gpxPrefix.length()) : e.getKey();
[15496]797 String v = e.getValue();
798 if (GpxConstants.RTE_TRK_KEYS.contains(k)) {
799 trkAttr.put(k, v);
800 } else {
801 k = GpxConstants.EXTENSION_ABBREVIATIONS.entrySet()
802 .stream()
803 .filter(s -> s.getValue().equals(e.getKey()))
[18078]804 .map(s -> s.getKey().substring(gpxPrefix.length()))
[15496]805 .findAny()
806 .orElse(k);
807 if (k.startsWith("extension")) {
[16643]808 String[] chain = k.split(":", -1);
[15496]809 if (chain.length >= 3 && "segment".equals(chain[2])) {
810 segExts.addFlat(chain, v);
811 } else {
812 trkExts.addFlat(chain, v);
813 }
814 }
815
816 }
[1670]817 }
[15496]818 List<WayPoint> trkseg = new ArrayList<>();
[1898]819 for (Node n : w.getNodes()) {
[2120]820 if (!n.isUsable()) {
[15496]821 if (!trkseg.isEmpty()) {
822 trk.add(new GpxTrackSegment(trkseg));
823 trkseg.clear();
824 }
[1078]825 continue;
826 }
[18078]827 if (!n.isTagged() || containsOnlyGpxTags(n, gpxPrefix)) {
[1078]828 doneNodes.add(n);
829 }
[18078]830 trkseg.add(nodeToWayPoint(n, Long.MIN_VALUE, gpxPrefix));
[1078]831 }
[15496]832 trk.add(new GpxTrackSegment(trkseg));
833 trk.forEach(gpxseg -> gpxseg.getExtensions().addAll(segExts));
834 GpxTrack gpxtrk = new GpxTrack(trk, trkAttr);
835 gpxtrk.getExtensions().addAll(trkExts);
836 gpxData.addTrack(gpxtrk);
[11177]837 });
[7414]838 }
[1169]839
[18078]840 private static boolean containsOnlyGpxTags(Tagged t, String gpxPrefix) {
[17584]841 return t.keys()
[18078]842 .allMatch(key -> GpxConstants.WPT_KEYS.contains(key) || key.startsWith(gpxPrefix));
[14075]843 }
844
[13210]845 /**
[15419]846 * Reads the Gpx key from the given {@link OsmPrimitive}, with or without &quot;gpx:&quot; prefix
[15422]847 * @param prim OSM primitive
[18078]848 * @param gpxPrefix the GPX prefix
[15422]849 * @param key GPX key without prefix
[15419]850 * @return the value or <code>null</code> if not present
851 */
[18078]852 private static String gpxVal(OsmPrimitive prim, String gpxPrefix, String key) {
853 String val = prim.get(gpxPrefix + key);
[17847]854 return val != null ? val : prim.get(key);
[15419]855 }
856
857 /**
[18078]858 * Converts a node to a waypoint with default {@link GpxConstants#GPX_PREFIX} for tags.
[13210]859 * @param n the {@code Node} to convert
[18078]860 * @param time a timestamp value in milliseconds from the epoch.
[13210]861 * @return {@code WayPoint} object
862 * @since 13210
863 */
[18078]864 public static WayPoint nodeToWayPoint(Node n, long time) {
865 return nodeToWayPoint(n, time, GpxConstants.GPX_PREFIX);
[13210]866 }
867
868 /**
[18078]869 * Converts a node to a waypoint with a configurable GPX prefix for tags.
[13210]870 * @param n the {@code Node} to convert
[14434]871 * @param time a timestamp value in milliseconds from the epoch.
[18078]872 * @param gpxPrefix the GPX prefix for tags
[13210]873 * @return {@code WayPoint} object
[18078]874 * @since 18078
[13210]875 */
[18078]876 public static WayPoint nodeToWayPoint(Node n, long time, String gpxPrefix) {
[8158]877 WayPoint wpt = new WayPoint(n.getCoor());
[7518]878
[8158]879 // Position info
[7518]880
[18078]881 addDoubleIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_ELE, null);
[7518]882
[14430]883 try {
[15419]884 String v;
[14434]885 if (time > Long.MIN_VALUE) {
886 wpt.setTimeInMillis(time);
[18078]887 } else if ((v = gpxVal(n, gpxPrefix, GpxConstants.PT_TIME)) != null) {
[17749]888 wpt.setInstant(DateUtils.parseInstant(v));
[14430]889 } else if (!n.isTimestampEmpty()) {
[17749]890 wpt.setInstant(n.getInstant());
[14430]891 }
[17166]892 } catch (UncheckedParseException | DateTimeException e) {
[14430]893 Logging.error(e);
[8158]894 }
[7518]895
[18078]896 addDoubleIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_MAGVAR, null);
897 addDoubleIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_GEOIDHEIGHT, null);
[7518]898
[8158]899 // Description info
[7518]900
[18078]901 addStringIfPresent(wpt, n, gpxPrefix, GpxConstants.GPX_NAME, null, null);
902 addStringIfPresent(wpt, n, gpxPrefix, GpxConstants.GPX_DESC, "description", null);
903 addStringIfPresent(wpt, n, gpxPrefix, GpxConstants.GPX_CMT, "comment", null);
904 addStringIfPresent(wpt, n, gpxPrefix, GpxConstants.GPX_SRC, "source", "source:position");
[7518]905
[16438]906 Collection<GpxLink> links = Stream.of("link", "url", "website", "contact:website")
[18078]907 .map(key -> gpxVal(n, gpxPrefix, key))
[16438]908 .filter(Objects::nonNull)
909 .map(GpxLink::new)
910 .collect(Collectors.toList());
[8158]911 wpt.put(GpxConstants.META_LINKS, links);
[4046]912
[18078]913 addStringIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_SYM, "wpt_symbol", null);
914 addStringIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_TYPE, null, null);
[7518]915
[8158]916 // Accuracy info
[18078]917 addStringIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_FIX, "gps:fix", null);
918 addIntegerIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_SAT, "gps:sat");
919 addDoubleIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_HDOP, "gps:hdop");
920 addDoubleIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_VDOP, "gps:vdop");
921 addDoubleIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_PDOP, "gps:pdop");
922 addDoubleIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_AGEOFDGPSDATA, "gps:ageofdgpsdata");
923 addIntegerIfPresent(wpt, n, gpxPrefix, GpxConstants.PT_DGPSID, "gps:dgpsid");
[7518]924
[8158]925 return wpt;
926 }
927
[18078]928 private static void nodesToGpxData(Collection<Node> nodes, GpxData gpxData, Set<Node> doneNodes, String gpxPrefix) {
[8158]929 List<Node> sortedNodes = new ArrayList<>(nodes);
930 sortedNodes.removeAll(doneNodes);
931 Collections.sort(sortedNodes);
932 for (Node n : sortedNodes) {
933 if (n.isIncomplete() || n.isDeleted()) {
934 continue;
935 }
[18078]936 gpxData.waypoints.add(nodeToWayPoint(n, Long.MIN_VALUE, gpxPrefix));
[1078]937 }
938 }
[444]939
[18078]940 private static void addIntegerIfPresent(WayPoint wpt, OsmPrimitive p, String gpxPrefix, String gpxKey, String osmKey) {
941 String value = gpxVal(p, gpxPrefix, gpxKey);
[17847]942 if (value == null && osmKey != null) {
[18078]943 value = gpxVal(p, gpxPrefix, osmKey);
[17847]944 }
945 if (value != null) {
946 try {
[18753]947 final int i = Integer.parseInt(value);
[17847]948 // Sanity checks
949 if ((!GpxConstants.PT_SAT.equals(gpxKey) || i >= 0) &&
[7518]950 (!GpxConstants.PT_DGPSID.equals(gpxKey) || (0 <= i && i <= 1023))) {
[18753]951 wpt.put(gpxKey, i);
[7518]952 }
[17847]953 } catch (NumberFormatException e) {
954 Logging.trace(e);
[7518]955 }
956 }
957 }
958
[18078]959 private static void addDoubleIfPresent(WayPoint wpt, OsmPrimitive p, String gpxPrefix, String gpxKey, String osmKey) {
960 String value = gpxVal(p, gpxPrefix, gpxKey);
[17847]961 if (value == null && osmKey != null) {
[18078]962 value = gpxVal(p, gpxPrefix, osmKey);
[17847]963 }
964 if (value != null) {
965 try {
[18753]966 final double d = Double.parseDouble(value);
[17847]967 // Sanity checks
968 if (!GpxConstants.PT_MAGVAR.equals(gpxKey) || (0.0 <= d && d < 360.0)) {
[18753]969 wpt.put(gpxKey, d);
[7518]970 }
[17847]971 } catch (NumberFormatException e) {
972 Logging.trace(e);
[7518]973 }
974 }
975 }
976
[18078]977 private static void addStringIfPresent(WayPoint wpt, OsmPrimitive p, String gpxPrefix, String gpxKey, String osmKey, String osmKey2) {
978 String value = gpxVal(p, gpxPrefix, gpxKey);
[17847]979 if (value == null && osmKey != null) {
[18078]980 value = gpxVal(p, gpxPrefix, osmKey);
[17847]981 }
982 if (value == null && osmKey2 != null) {
[18078]983 value = gpxVal(p, gpxPrefix, osmKey2);
[17847]984 }
985 // Sanity checks
986 if (value != null && (!GpxConstants.PT_FIX.equals(gpxKey) || GpxConstants.FIX_VALUES.contains(value))) {
987 wpt.put(gpxKey, value);
988 }
[7518]989 }
990
[7414]991 /**
992 * Converts OSM data behind this layer to GPX data.
993 * @return GPX data
994 */
[1078]995 public GpxData toGpxData() {
[1646]996 return toGpxData(data, getAssociatedFile());
[1078]997 }
[628]998
[7414]999 /**
1000 * Action that converts this OSM layer to a GPX layer.
1001 */
[1078]1002 public class ConvertToGpxLayerAction extends AbstractAction {
[7414]1003 /**
1004 * Constructs a new {@code ConvertToGpxLayerAction}.
1005 */
[1078]1006 public ConvertToGpxLayerAction() {
[13130]1007 super(tr("Convert to GPX layer"));
1008 new ImageProvider("converttogpx").getResource().attachImageIcon(this, true);
[4701]1009 putValue("help", ht("/Action/ConvertToGpxLayer"));
[1078]1010 }
[8510]1011
[6084]1012 @Override
[1078]1013 public void actionPerformed(ActionEvent e) {
[18466]1014 String name = getName().replaceAll("^" + tr("Converted from: {0}", ""), "");
[9674]1015 final GpxData gpxData = toGpxData();
[18466]1016 final GpxLayer gpxLayer = new GpxLayer(gpxData, tr("Converted from: {0}", name), true);
[9481]1017 if (getAssociatedFile() != null) {
[10300]1018 String filename = getAssociatedFile().getName().replaceAll(Pattern.quote(".gpx.osm") + '$', "") + ".gpx";
[9481]1019 gpxLayer.setAssociatedFile(new File(getAssociatedFile().getParentFile(), filename));
[18466]1020 gpxLayer.getGpxData().setModified(true);
[9481]1021 }
[13855]1022 MainApplication.getLayerManager().addLayer(gpxLayer, false);
[12846]1023 if (Config.getPref().getBoolean("marker.makeautomarkers", true) && !gpxData.waypoints.isEmpty()) {
[13855]1024 MainApplication.getLayerManager().addLayer(
1025 new MarkerLayer(gpxData, tr("Converted from: {0}", getName()), null, gpxLayer), false);
[8805]1026 }
[12636]1027 MainApplication.getLayerManager().removeLayer(OsmDataLayer.this);
[1078]1028 }
1029 }
1030
[7414]1031 /**
1032 * Determines if this layer contains data at the given coordinate.
1033 * @param coor the coordinate
1034 * @return {@code true} if data sources bounding boxes contain {@code coor}
1035 */
[1523]1036 public boolean containsPoint(LatLon coor) {
[628]1037 // we'll assume that if this has no data sources
1038 // that it also has no borders
[11627]1039 if (this.data.getDataSources().isEmpty())
[628]1040 return true;
1041
[16438]1042 return this.data.getDataSources().stream()
1043 .anyMatch(src -> src.bounds.contains(coor));
[628]1044 }
[1750]1045
1046 /**
[7414]1047 * Replies the set of conflicts currently managed in this layer.
[1823]1048 *
[1750]1049 * @return the set of conflicts currently managed in this layer
1050 */
1051 public ConflictCollection getConflicts() {
[12672]1052 return data.getConflicts();
[1750]1053 }
[2025]1054
[7358]1055 @Override
[13453]1056 public boolean isDownloadable() {
1057 return data.getDownloadPolicy() != DownloadPolicy.BLOCKED && !isLocked();
1058 }
1059
1060 @Override
[9751]1061 public boolean isUploadable() {
[13453]1062 return data.getUploadPolicy() != UploadPolicy.BLOCKED && !isLocked();
[9751]1063 }
1064
1065 @Override
[2025]1066 public boolean requiresUploadToServer() {
[11709]1067 return isUploadable() && requiresUploadToServer;
[2025]1068 }
1069
[7358]1070 @Override
[2025]1071 public boolean requiresSaveToFile() {
1072 return getAssociatedFile() != null && requiresSaveToFile;
1073 }
1074
[5459]1075 @Override
[17626]1076 public String getLabel() {
1077 String label = super.getLabel();
1078 if (this.isDirty()) {
[17757]1079 label += " " + IS_DIRTY_SYMBOL;
[17626]1080 }
1081 if (this.getDataSet().isEmpty()) {
[17757]1082 label += " " + IS_EMPTY_SYMBOL;
[17626]1083 }
1084 return label;
1085 }
1086
1087 @Override
[2025]1088 public void onPostLoadFromFile() {
1089 setRequiresSaveToFile(false);
[18693]1090 setRequiresUploadToServer(getDataSet().requiresUploadToServer());
[10467]1091 invalidate();
[2025]1092 }
1093
[7414]1094 /**
1095 * Actions run after data has been downloaded to this layer.
1096 */
[2434]1097 public void onPostDownloadFromServer() {
1098 setRequiresSaveToFile(true);
[18693]1099 setRequiresUploadToServer(getDataSet().requiresUploadToServer());
[10467]1100 invalidate();
[2434]1101 }
1102
[3116]1103 @Override
[2025]1104 public void onPostSaveToFile() {
1105 setRequiresSaveToFile(false);
[18693]1106 setRequiresUploadToServer(getDataSet().requiresUploadToServer());
[2025]1107 }
1108
[7358]1109 @Override
[2025]1110 public void onPostUploadToServer() {
[18693]1111 setRequiresUploadToServer(getDataSet().requiresUploadToServer());
[2025]1112 // keep requiresSaveToDisk unchanged
1113 }
[2500]1114
1115 private class ConsistencyTestAction extends AbstractAction {
1116
[8836]1117 ConsistencyTestAction() {
[2500]1118 super(tr("Dataset consistency test"));
1119 }
1120
[6084]1121 @Override
[2500]1122 public void actionPerformed(ActionEvent e) {
1123 String result = DatasetConsistencyTest.runTests(data);
[8394]1124 if (result.isEmpty()) {
[14153]1125 JOptionPane.showMessageDialog(MainApplication.getMainFrame(), tr("No problems found"));
[2500]1126 } else {
1127 JPanel p = new JPanel(new GridBagLayout());
1128 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
[5886]1129 JosmTextArea info = new JosmTextArea(result, 20, 60);
[2500]1130 info.setCaretPosition(0);
1131 info.setEditable(false);
1132 p.add(new JScrollPane(info), GBC.eop());
1133
[14153]1134 JOptionPane.showMessageDialog(MainApplication.getMainFrame(), p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
[2500]1135 }
1136 }
1137 }
[3116]1138
[3245]1139 @Override
[12028]1140 public synchronized void destroy() {
[10959]1141 super.destroy();
[12152]1142 data.removeSelectionListener(this);
[12014]1143 data.removeHighlightUpdateListener(this);
[14556]1144 data.removeDataSetListener(dataSetListenerAdapter);
1145 data.removeDataSetListener(MultipolygonCache.getInstance());
[17440]1146 data.clearSelection();
1147 validationErrors.clear();
[14500]1148 removeClipboardDataFor(this);
[14556]1149 recentRelations.clear();
[3245]1150 }
1151
[14500]1152 protected static void removeClipboardDataFor(OsmDataLayer osm) {
1153 Transferable clipboardContents = ClipboardUtils.getClipboardContent();
[14504]1154 if (clipboardContents != null && clipboardContents.isDataFlavorSupported(OsmLayerTransferData.OSM_FLAVOR)) {
[14500]1155 try {
1156 Object o = clipboardContents.getTransferData(OsmLayerTransferData.OSM_FLAVOR);
1157 if (o instanceof OsmLayerTransferData && osm.equals(((OsmLayerTransferData) o).getLayer())) {
1158 ClipboardUtils.clear();
1159 }
1160 } catch (UnsupportedFlavorException | IOException e) {
1161 Logging.error(e);
1162 }
1163 }
1164 }
1165
[6084]1166 @Override
[3116]1167 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
[10031]1168 invalidate();
[3225]1169 setRequiresSaveToFile(true);
[13161]1170 setRequiresUploadToServer(event.getDataset().requiresUploadToServer());
[3116]1171 }
1172
[6084]1173 @Override
[12152]1174 public void selectionChanged(SelectionChangeEvent event) {
[10031]1175 invalidate();
1176 }
1177
1178 @Override
[4126]1179 public void projectionChanged(Projection oldValue, Projection newValue) {
[7414]1180 // No reprojection required. The dataset itself is registered as projection
1181 // change listener and already got notified.
[4126]1182 }
[5025]1183
[7358]1184 @Override
[5025]1185 public final boolean isUploadDiscouraged() {
[11709]1186 return data.getUploadPolicy() == UploadPolicy.DISCOURAGED;
[5025]1187 }
1188
[7414]1189 /**
1190 * Sets the "discouraged upload" flag.
[8540]1191 * @param uploadDiscouraged {@code true} if upload of data managed by this layer is discouraged.
1192 * This feature allows to use "private" data layers.
[7414]1193 */
[5025]1194 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
[11709]1195 if (data.getUploadPolicy() != UploadPolicy.BLOCKED &&
[11710]1196 (uploadDiscouraged ^ isUploadDiscouraged())) {
[11709]1197 data.setUploadPolicy(uploadDiscouraged ? UploadPolicy.DISCOURAGED : UploadPolicy.NORMAL);
[5519]1198 for (LayerStateChangeListener l : layerStateChangeListeners) {
1199 l.uploadDiscouragedChanged(this, uploadDiscouraged);
1200 }
1201 }
[5025]1202 }
[5459]1203
1204 @Override
[7358]1205 public final boolean isModified() {
1206 return data.isModified();
1207 }
1208
1209 @Override
[5459]1210 public boolean isSavable() {
1211 return true; // With OsmExporter
1212 }
1213
1214 @Override
1215 public boolean checkSaveConditions() {
[15121]1216 if (isDataSetEmpty() && 1 != GuiHelper.runInEDTAndWaitAndReturn(() ->
1217 new ExtendedDialog(
[14153]1218 MainApplication.getMainFrame(),
[17757]1219 tr("Empty layer"),
[12279]1220 tr("Save anyway"), tr("Cancel"))
[17757]1221 .setContent(tr("The layer contains no data."))
[12279]1222 .setButtonIcons("save", "cancel")
[15121]1223 .showDialog().getValue()
1224 )) {
[9674]1225 return false;
[5459]1226 }
1227
[9674]1228 ConflictCollection conflictsCol = getConflicts();
[12281]1229 return conflictsCol == null || conflictsCol.isEmpty() || 1 == GuiHelper.runInEDTAndWaitAndReturn(() ->
1230 new ExtendedDialog(
[14153]1231 MainApplication.getMainFrame(),
[10611]1232 /* I18N: Display title of the window showing conflicts */
1233 tr("Conflicts"),
[12279]1234 tr("Reject Conflicts and Save"), tr("Cancel"))
1235 .setContent(
1236 tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"))
1237 .setButtonIcons("save", "cancel")
[12281]1238 .showDialog().getValue()
1239 );
[5459]1240 }
[6070]1241
[5459]1242 /**
1243 * Check the data set if it would be empty on save. It is empty, if it contains
1244 * no objects (after all objects that are created and deleted without being
1245 * transferred to the server have been removed).
1246 *
1247 * @return <code>true</code>, if a save result in an empty data set.
1248 */
1249 private boolean isDataSetEmpty() {
[16438]1250 return data == null || data.allNonDeletedPrimitives().stream()
1251 .allMatch(osm -> osm.isDeleted() && osm.isNewOrUndeleted());
[5459]1252 }
1253
1254 @Override
1255 public File createAndOpenSaveFileChooser() {
[9721]1256 String extension = PROPERTY_SAVE_EXTENSION.get();
[9670]1257 File file = getAssociatedFile();
1258 if (file == null && isRenamed()) {
[12846]1259 StringBuilder filename = new StringBuilder(Config.getPref().get("lastDirectory")).append('/').append(getName());
[11649]1260 if (!OsmImporter.FILE_FILTER.acceptName(filename.toString())) {
1261 filename.append('.').append(extension);
1262 }
1263 file = new File(filename.toString());
[9670]1264 }
1265 return new FileChooserManager()
1266 .title(tr("Save OSM file"))
1267 .extension(extension)
1268 .file(file)
[14668]1269 .additionalTypes(t -> t != WMSLayerImporter.FILE_FILTER && t != NoteExporter.FILE_FILTER && t != ValidatorErrorExporter.FILE_FILTER)
[9670]1270 .getFileForSave();
[5459]1271 }
[7358]1272
1273 @Override
1274 public AbstractIOTask createUploadTask(final ProgressMonitor monitor) {
1275 UploadDialog dialog = UploadDialog.getUploadDialog();
1276 return new UploadLayerTask(
1277 dialog.getUploadStrategySpecification(),
1278 this,
1279 monitor,
1280 dialog.getChangeset());
1281 }
1282
1283 @Override
[18457]1284 public String getChangesetSourceTag() {
1285 return this.data.getChangeSetTags().getOrDefault("source", null);
1286 }
1287
1288 @Override
[7358]1289 public AbstractUploadDialog getUploadDialog() {
1290 UploadDialog dialog = UploadDialog.getUploadDialog();
1291 dialog.setUploadedPrimitives(new APIDataSet(data));
1292 return dialog;
1293 }
[10371]1294
1295 @Override
1296 public ProjectionBounds getViewProjectionBounds() {
1297 BoundingXYVisitor v = new BoundingXYVisitor();
1298 v.visit(data.getDataSourceBoundingBox());
1299 if (!v.hasExtend()) {
1300 v.computeBoundingBox(data.getNodes());
1301 }
1302 return v.getBounds();
1303 }
[12014]1304
1305 @Override
1306 public void highlightUpdated(HighlightUpdateEvent e) {
1307 invalidate();
1308 }
[12718]1309
1310 @Override
1311 public void setName(String name) {
1312 if (data != null) {
1313 data.setName(name);
1314 }
1315 super.setName(name);
1316 }
[13133]1317
[13435]1318 /**
1319 * Sets the "upload in progress" flag, which will result in displaying a new icon and forbid to remove the layer.
1320 * @since 13434
1321 */
[13434]1322 public void setUploadInProgress() {
1323 if (!isUploadInProgress.compareAndSet(false, true)) {
1324 Logging.warn("Trying to set uploadInProgress flag on layer already being uploaded ", getName());
1325 }
1326 }
1327
[13435]1328 /**
1329 * Unsets the "upload in progress" flag, which will result in displaying the standard icon and allow to remove the layer.
1330 * @since 13434
1331 */
[13434]1332 public void unsetUploadInProgress() {
1333 if (!isUploadInProgress.compareAndSet(true, false)) {
1334 Logging.warn("Trying to unset uploadInProgress flag on layer not being uploaded ", getName());
1335 }
1336 }
1337
1338 @Override
1339 public boolean isUploadInProgress() {
1340 return isUploadInProgress.get();
1341 }
[16548]1342
1343 @Override
1344 public Data getData() {
1345 return getDataSet();
1346 }
1347
1348 @Override
1349 public boolean autosave(File file) throws IOException {
1350 new OsmExporter().exportData(file, this, true /* no backup with appended ~ */);
1351 return true;
1352 }
[18233]1353
1354 /**
1355 * Duplicates this layer with a new name and a copy of this layer dataset.
1356 * @param newName name of new layer
1357 * @return A copy of this layer
1358 * @since 18233
1359 */
1360 public OsmDataLayer duplicate(String newName) {
1361 return new OsmDataLayer(new DataSet(getDataSet()), newName, null);
1362 }
[444]1363}
Note: See TracBrowser for help on using the repository browser.