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

Last change on this file since 5519 was 5519, checked in by Don-vip, 12 years ago

fix #8090 - Removing saved non-uploadable layer asks for confirmation

  • Property svn:eol-style set to native
File size: 30.7 KB
Line 
1// License: GPL. See LICENSE file for details.
2
3package org.openstreetmap.josm.gui.layer;
4
5import static org.openstreetmap.josm.gui.help.HelpUtil.ht;
6import static org.openstreetmap.josm.tools.I18n.marktr;
7import static org.openstreetmap.josm.tools.I18n.tr;
8import static org.openstreetmap.josm.tools.I18n.trn;
9
10import java.awt.AlphaComposite;
11import java.awt.Color;
12import java.awt.Composite;
13import java.awt.Graphics2D;
14import java.awt.GridBagLayout;
15import java.awt.Image;
16import java.awt.Point;
17import java.awt.Rectangle;
18import java.awt.TexturePaint;
19import java.awt.event.ActionEvent;
20import java.awt.geom.Area;
21import java.awt.image.BufferedImage;
22import java.io.File;
23import java.util.ArrayList;
24import java.util.Arrays;
25import java.util.Collection;
26import java.util.HashMap;
27import java.util.HashSet;
28import java.util.List;
29import java.util.Map;
30import java.util.concurrent.CopyOnWriteArrayList;
31
32import javax.swing.AbstractAction;
33import javax.swing.Action;
34import javax.swing.Icon;
35import javax.swing.ImageIcon;
36import javax.swing.JLabel;
37import javax.swing.JOptionPane;
38import javax.swing.JPanel;
39import javax.swing.JScrollPane;
40import javax.swing.JTextArea;
41
42import org.openstreetmap.josm.Main;
43import org.openstreetmap.josm.actions.ExpertToggleAction;
44import org.openstreetmap.josm.actions.RenameLayerAction;
45import org.openstreetmap.josm.actions.SaveActionBase;
46import org.openstreetmap.josm.actions.ToggleUploadDiscouragedLayerAction;
47import org.openstreetmap.josm.data.Bounds;
48import org.openstreetmap.josm.data.SelectionChangedListener;
49import org.openstreetmap.josm.data.conflict.Conflict;
50import org.openstreetmap.josm.data.conflict.ConflictCollection;
51import org.openstreetmap.josm.data.coor.LatLon;
52import org.openstreetmap.josm.data.gpx.GpxData;
53import org.openstreetmap.josm.data.gpx.ImmutableGpxTrack;
54import org.openstreetmap.josm.data.gpx.WayPoint;
55import org.openstreetmap.josm.data.osm.DataIntegrityProblemException;
56import org.openstreetmap.josm.data.osm.DataSet;
57import org.openstreetmap.josm.data.osm.DataSetMerger;
58import org.openstreetmap.josm.data.osm.DataSource;
59import org.openstreetmap.josm.data.osm.DatasetConsistencyTest;
60import org.openstreetmap.josm.data.osm.IPrimitive;
61import org.openstreetmap.josm.data.osm.Node;
62import org.openstreetmap.josm.data.osm.OsmPrimitive;
63import org.openstreetmap.josm.data.osm.Relation;
64import org.openstreetmap.josm.data.osm.Way;
65import org.openstreetmap.josm.data.osm.event.AbstractDatasetChangedEvent;
66import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter;
67import org.openstreetmap.josm.data.osm.event.DataSetListenerAdapter.Listener;
68import org.openstreetmap.josm.data.osm.visitor.AbstractVisitor;
69import org.openstreetmap.josm.data.osm.visitor.BoundingXYVisitor;
70import org.openstreetmap.josm.data.osm.visitor.paint.MapRendererFactory;
71import org.openstreetmap.josm.data.osm.visitor.paint.Rendering;
72import org.openstreetmap.josm.data.osm.visitor.paint.relations.MultipolygonCache;
73import org.openstreetmap.josm.data.projection.Projection;
74import org.openstreetmap.josm.data.validation.TestError;
75import org.openstreetmap.josm.gui.ExtendedDialog;
76import org.openstreetmap.josm.gui.HelpAwareOptionPane;
77import org.openstreetmap.josm.gui.HelpAwareOptionPane.ButtonSpec;
78import org.openstreetmap.josm.gui.MapView;
79import org.openstreetmap.josm.gui.dialogs.LayerListDialog;
80import org.openstreetmap.josm.gui.dialogs.LayerListPopup;
81import org.openstreetmap.josm.gui.progress.PleaseWaitProgressMonitor;
82import org.openstreetmap.josm.gui.progress.ProgressMonitor;
83import org.openstreetmap.josm.gui.util.GuiHelper;
84import org.openstreetmap.josm.tools.DateUtils;
85import org.openstreetmap.josm.tools.FilteredCollection;
86import org.openstreetmap.josm.tools.GBC;
87import org.openstreetmap.josm.tools.ImageProvider;
88
89/**
90 * A layer that holds OSM data from a specific dataset.
91 * The data can be fully edited.
92 *
93 * @author imi
94 */
95public class OsmDataLayer extends Layer implements Listener, SelectionChangedListener {
96 static public final String REQUIRES_SAVE_TO_DISK_PROP = OsmDataLayer.class.getName() + ".requiresSaveToDisk";
97 static public final String REQUIRES_UPLOAD_TO_SERVER_PROP = OsmDataLayer.class.getName() + ".requiresUploadToServer";
98
99 private boolean requiresSaveToFile = false;
100 private boolean requiresUploadToServer = false;
101 private boolean isChanged = true;
102 private int highlightUpdateCount;
103
104 public List<TestError> validationErrors = new ArrayList<TestError>();
105
106 protected void setRequiresSaveToFile(boolean newValue) {
107 boolean oldValue = requiresSaveToFile;
108 requiresSaveToFile = newValue;
109 if (oldValue != newValue) {
110 propertyChangeSupport.firePropertyChange(REQUIRES_SAVE_TO_DISK_PROP, oldValue, newValue);
111 }
112 }
113
114 protected void setRequiresUploadToServer(boolean newValue) {
115 boolean oldValue = requiresUploadToServer;
116 requiresUploadToServer = newValue;
117 if (oldValue != newValue) {
118 propertyChangeSupport.firePropertyChange(REQUIRES_UPLOAD_TO_SERVER_PROP, oldValue, newValue);
119 }
120 }
121
122 /** the global counter for created data layers */
123 static private int dataLayerCounter = 0;
124
125 /**
126 * Replies a new unique name for a data layer
127 *
128 * @return a new unique name for a data layer
129 */
130 static public String createNewName() {
131 dataLayerCounter++;
132 return tr("Data Layer {0}", dataLayerCounter);
133 }
134
135 public final static class DataCountVisitor extends AbstractVisitor {
136 public int nodes;
137 public int ways;
138 public int relations;
139 public int deletedNodes;
140 public int deletedWays;
141 public int deletedRelations;
142
143 public void visit(final Node n) {
144 nodes++;
145 if (n.isDeleted()) {
146 deletedNodes++;
147 }
148 }
149
150 public void visit(final Way w) {
151 ways++;
152 if (w.isDeleted()) {
153 deletedWays++;
154 }
155 }
156
157 public void visit(final Relation r) {
158 relations++;
159 if (r.isDeleted()) {
160 deletedRelations++;
161 }
162 }
163 }
164
165 public interface CommandQueueListener {
166 void commandChanged(int queueSize, int redoSize);
167 }
168
169 /**
170 * Listener called when a state of this layer has changed.
171 */
172 public interface LayerStateChangeListener {
173 /**
174 * Notifies that the "upload discouraged" (upload=no) state has changed.
175 * @param layer The layer that has been modified
176 * @param newValue The new value of the state
177 */
178 void uploadDiscouragedChanged(OsmDataLayer layer, boolean newValue);
179 }
180
181 private final CopyOnWriteArrayList<LayerStateChangeListener> layerStateChangeListeners = new CopyOnWriteArrayList<LayerStateChangeListener>();
182
183 /**
184 * Adds a layer state change listener
185 *
186 * @param listener the listener. Ignored if null or already registered.
187 * @since 5519
188 */
189 public void addLayerStateChangeListener(LayerStateChangeListener listener) {
190 if (listener != null) {
191 layerStateChangeListeners.addIfAbsent(listener);
192 }
193 }
194
195 /**
196 * Removes a layer property change listener
197 *
198 * @param listener the listener. Ignored if null or already registered.
199 * @since 5519
200 */
201 public void removeLayerPropertyChangeListener(LayerStateChangeListener listener) {
202 layerStateChangeListeners.remove(listener);
203 }
204
205 /**
206 * The data behind this layer.
207 */
208 public final DataSet data;
209
210 /**
211 * the collection of conflicts detected in this layer
212 */
213 private ConflictCollection conflicts;
214
215 /**
216 * a paint texture for non-downloaded area
217 */
218 private static TexturePaint hatched;
219
220 static {
221 createHatchTexture();
222 }
223
224 public static Color getBackgroundColor() {
225 return Main.pref.getColor(marktr("background"), Color.BLACK);
226 }
227
228 public static Color getOutsideColor() {
229 return Main.pref.getColor(marktr("outside downloaded area"), Color.YELLOW);
230 }
231
232 /**
233 * Initialize the hatch pattern used to paint the non-downloaded area
234 */
235 public static void createHatchTexture() {
236 BufferedImage bi = new BufferedImage(15, 15, BufferedImage.TYPE_INT_ARGB);
237 Graphics2D big = bi.createGraphics();
238 big.setColor(getBackgroundColor());
239 Composite comp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.3f);
240 big.setComposite(comp);
241 big.fillRect(0,0,15,15);
242 big.setColor(getOutsideColor());
243 big.drawLine(0,15,15,0);
244 Rectangle r = new Rectangle(0, 0, 15,15);
245 hatched = new TexturePaint(bi, r);
246 }
247
248 /**
249 * Construct a OsmDataLayer.
250 */
251 public OsmDataLayer(final DataSet data, final String name, final File associatedFile) {
252 super(name);
253 this.data = data;
254 this.setAssociatedFile(associatedFile);
255 conflicts = new ConflictCollection();
256 data.addDataSetListener(new DataSetListenerAdapter(this));
257 data.addDataSetListener(MultipolygonCache.getInstance());
258 DataSet.addSelectionListener(this);
259 }
260
261 protected Icon getBaseIcon() {
262 return ImageProvider.get("layer", "osmdata_small");
263 }
264
265 /**
266 * TODO: @return Return a dynamic drawn icon of the map data. The icon is
267 * updated by a background thread to not disturb the running programm.
268 */
269 @Override public Icon getIcon() {
270 Icon baseIcon = getBaseIcon();
271 if (isUploadDiscouraged()) {
272 return ImageProvider.overlay(baseIcon,
273 new ImageIcon(ImageProvider.get("warning-small").getImage().getScaledInstance(8, 8, Image.SCALE_SMOOTH)),
274 ImageProvider.OverlayPosition.SOUTHEAST);
275 } else {
276 return baseIcon;
277 }
278 }
279
280 /**
281 * Draw all primitives in this layer but do not draw modified ones (they
282 * are drawn by the edit layer).
283 * Draw nodes last to overlap the ways they belong to.
284 */
285 @Override public void paint(final Graphics2D g, final MapView mv, Bounds box) {
286 isChanged = false;
287 highlightUpdateCount = data.getHighlightUpdateCount();
288
289 boolean active = mv.getActiveLayer() == this;
290 boolean inactive = !active && Main.pref.getBoolean("draw.data.inactive_color", true);
291 boolean virtual = !inactive && mv.isVirtualNodesEnabled();
292
293 // draw the hatched area for non-downloaded region. only draw if we're the active
294 // and bounds are defined; don't draw for inactive layers or loaded GPX files etc
295 if (active && Main.pref.getBoolean("draw.data.downloaded_area", true) && !data.dataSources.isEmpty()) {
296 // initialize area with current viewport
297 Rectangle b = mv.getBounds();
298 // on some platforms viewport bounds seem to be offset from the left,
299 // over-grow it just to be sure
300 b.grow(100, 100);
301 Area a = new Area(b);
302
303 // now successively subtract downloaded areas
304 for (Bounds bounds : data.getDataSourceBounds()) {
305 if (bounds.isCollapsed()) {
306 continue;
307 }
308 Point p1 = mv.getPoint(bounds.getMin());
309 Point p2 = mv.getPoint(bounds.getMax());
310 Rectangle r = new Rectangle(Math.min(p1.x, p2.x),Math.min(p1.y, p2.y),Math.abs(p2.x-p1.x),Math.abs(p2.y-p1.y));
311 a.subtract(new Area(r));
312 }
313
314 // paint remainder
315 g.setPaint(hatched);
316 g.fill(a);
317 }
318
319 Rendering painter = MapRendererFactory.getInstance().createActiveRenderer(g, mv, inactive);
320 painter.render(data, virtual, box);
321 Main.map.conflictDialog.paintConflicts(g, mv);
322 }
323
324 @Override public String getToolTipText() {
325 int nodes = new FilteredCollection<Node>(data.getNodes(), OsmPrimitive.nonDeletedPredicate).size();
326 int ways = new FilteredCollection<Way>(data.getWays(), OsmPrimitive.nonDeletedPredicate).size();
327
328 String tool = trn("{0} node", "{0} nodes", nodes, nodes)+", ";
329 tool += trn("{0} way", "{0} ways", ways, ways);
330
331 if (data.getVersion() != null) {
332 tool += ", " + tr("version {0}", data.getVersion());
333 }
334 File f = getAssociatedFile();
335 if (f != null) {
336 tool = "<html>"+tool+"<br>"+f.getPath()+"</html>";
337 }
338 return tool;
339 }
340
341 @Override public void mergeFrom(final Layer from) {
342 final PleaseWaitProgressMonitor monitor = new PleaseWaitProgressMonitor(tr("Merging layers"));
343 monitor.setCancelable(false);
344 if (from instanceof OsmDataLayer && ((OsmDataLayer)from).isUploadDiscouraged()) {
345 setUploadDiscouraged(true);
346 }
347 mergeFrom(((OsmDataLayer)from).data, monitor);
348 monitor.close();
349 }
350
351 /**
352 * merges the primitives in dataset <code>from</code> into the dataset of
353 * this layer
354 *
355 * @param from the source data set
356 */
357 public void mergeFrom(final DataSet from) {
358 mergeFrom(from, null);
359 }
360
361 /**
362 * merges the primitives in dataset <code>from</code> into the dataset of
363 * this layer
364 *
365 * @param from the source data set
366 */
367 public void mergeFrom(final DataSet from, ProgressMonitor progressMonitor) {
368 final DataSetMerger visitor = new DataSetMerger(data,from);
369 try {
370 visitor.merge(progressMonitor);
371 } catch (DataIntegrityProblemException e) {
372 JOptionPane.showMessageDialog(
373 Main.parent,
374 e.getHtmlMessage() != null ? e.getHtmlMessage() : e.getMessage(),
375 tr("Error"),
376 JOptionPane.ERROR_MESSAGE
377 );
378 return;
379
380 }
381
382 Area a = data.getDataSourceArea();
383
384 // copy the merged layer's data source info;
385 // only add source rectangles if they are not contained in the
386 // layer already.
387 for (DataSource src : from.dataSources) {
388 if (a == null || !a.contains(src.bounds.asRect())) {
389 data.dataSources.add(src);
390 }
391 }
392
393 // copy the merged layer's API version, downgrade if required
394 if (data.getVersion() == null) {
395 data.setVersion(from.getVersion());
396 } else if ("0.5".equals(data.getVersion()) ^ "0.5".equals(from.getVersion())) {
397 System.err.println(tr("Warning: mixing 0.6 and 0.5 data results in version 0.5"));
398 data.setVersion("0.5");
399 }
400
401 int numNewConflicts = 0;
402 for (Conflict<?> c : visitor.getConflicts()) {
403 if (!conflicts.hasConflict(c)) {
404 numNewConflicts++;
405 conflicts.add(c);
406 }
407 }
408 // repaint to make sure new data is displayed properly.
409 Main.map.mapView.repaint();
410 warnNumNewConflicts(numNewConflicts);
411 }
412
413 /**
414 * Warns the user about the number of detected conflicts
415 *
416 * @param numNewConflicts the number of detected conflicts
417 */
418 protected void warnNumNewConflicts(int numNewConflicts) {
419 if (numNewConflicts == 0) return;
420
421 String msg1 = trn(
422 "There was {0} conflict detected.",
423 "There were {0} conflicts detected.",
424 numNewConflicts,
425 numNewConflicts
426 );
427
428 final StringBuffer sb = new StringBuffer();
429 sb.append("<html>").append(msg1).append("</html>");
430 if (numNewConflicts > 0) {
431 final ButtonSpec[] options = new ButtonSpec[] {
432 new ButtonSpec(
433 tr("OK"),
434 ImageProvider.get("ok"),
435 tr("Click to close this dialog and continue editing"),
436 null /* no specific help */
437 )
438 };
439 GuiHelper.runInEDT(new Runnable() {
440 @Override
441 public void run() {
442 HelpAwareOptionPane.showOptionDialog(
443 Main.parent,
444 sb.toString(),
445 tr("Conflicts detected"),
446 JOptionPane.WARNING_MESSAGE,
447 null, /* no icon */
448 options,
449 options[0],
450 ht("/Concepts/Conflict#WarningAboutDetectedConflicts")
451 );
452 Main.map.conflictDialog.unfurlDialog();
453 Main.map.repaint();
454 }
455 });
456 }
457 }
458
459
460 @Override public boolean isMergable(final Layer other) {
461 // isUploadDiscouraged commented to allow merging between normal layers and discouraged layers with a warning (see #7684)
462 return other instanceof OsmDataLayer;// && (isUploadDiscouraged() == ((OsmDataLayer)other).isUploadDiscouraged());
463 }
464
465 @Override public void visitBoundingBox(final BoundingXYVisitor v) {
466 for (final Node n: data.getNodes()) {
467 if (n.isUsable()) {
468 v.visit(n);
469 }
470 }
471 }
472
473 /**
474 * Clean out the data behind the layer. This means clearing the redo/undo lists,
475 * really deleting all deleted objects and reset the modified flags. This should
476 * be done after an upload, even after a partial upload.
477 *
478 * @param processed A list of all objects that were actually uploaded.
479 * May be <code>null</code>, which means nothing has been uploaded
480 */
481 public void cleanupAfterUpload(final Collection<IPrimitive> processed) {
482 // return immediately if an upload attempt failed
483 if (processed == null || processed.isEmpty())
484 return;
485
486 Main.main.undoRedo.clean(this);
487
488 // if uploaded, clean the modified flags as well
489 data.cleanupDeletedPrimitives();
490 for (OsmPrimitive p: data.allPrimitives()) {
491 if (processed.contains(p)) {
492 p.setModified(false);
493 }
494 }
495 }
496
497
498 @Override public Object getInfoComponent() {
499 final DataCountVisitor counter = new DataCountVisitor();
500 for (final OsmPrimitive osm : data.allPrimitives()) {
501 osm.visit(counter);
502 }
503 final JPanel p = new JPanel(new GridBagLayout());
504
505 String nodeText = trn("{0} node", "{0} nodes", counter.nodes, counter.nodes);
506 if (counter.deletedNodes > 0) {
507 nodeText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedNodes, counter.deletedNodes)+")";
508 }
509
510 String wayText = trn("{0} way", "{0} ways", counter.ways, counter.ways);
511 if (counter.deletedWays > 0) {
512 wayText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedWays, counter.deletedWays)+")";
513 }
514
515 String relationText = trn("{0} relation", "{0} relations", counter.relations, counter.relations);
516 if (counter.deletedRelations > 0) {
517 relationText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedRelations, counter.deletedRelations)+")";
518 }
519
520 p.add(new JLabel(tr("{0} consists of:", getName())), GBC.eol());
521 p.add(new JLabel(nodeText, ImageProvider.get("data", "node"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
522 p.add(new JLabel(wayText, ImageProvider.get("data", "way"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
523 p.add(new JLabel(relationText, ImageProvider.get("data", "relation"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
524 p.add(new JLabel(tr("API version: {0}", (data.getVersion() != null) ? data.getVersion() : tr("unset"))), GBC.eop().insets(15,0,0,0));
525 if (isUploadDiscouraged()) {
526 p.add(new JLabel(tr("Upload is discouraged")), GBC.eop().insets(15,0,0,0));
527 }
528
529 return p;
530 }
531
532 @Override public Action[] getMenuEntries() {
533 if (Main.applet)
534 return new Action[]{
535 LayerListDialog.getInstance().createActivateLayerAction(this),
536 LayerListDialog.getInstance().createShowHideLayerAction(),
537 LayerListDialog.getInstance().createDeleteLayerAction(),
538 SeparatorLayerAction.INSTANCE,
539 LayerListDialog.getInstance().createMergeLayerAction(this),
540 SeparatorLayerAction.INSTANCE,
541 new RenameLayerAction(getAssociatedFile(), this),
542 new ConsistencyTestAction(),
543 SeparatorLayerAction.INSTANCE,
544 new LayerListPopup.InfoAction(this)};
545 ArrayList<Action> actions = new ArrayList<Action>();
546 actions.addAll(Arrays.asList(new Action[]{
547 LayerListDialog.getInstance().createActivateLayerAction(this),
548 LayerListDialog.getInstance().createShowHideLayerAction(),
549 LayerListDialog.getInstance().createDeleteLayerAction(),
550 SeparatorLayerAction.INSTANCE,
551 LayerListDialog.getInstance().createMergeLayerAction(this),
552 new LayerSaveAction(this),
553 new LayerSaveAsAction(this),
554 new LayerGpxExportAction(this),
555 new ConvertToGpxLayerAction(),
556 SeparatorLayerAction.INSTANCE,
557 new RenameLayerAction(getAssociatedFile(), this)}));
558 if (ExpertToggleAction.isExpert() && Main.pref.getBoolean("data.layer.upload_discouragement.menu_item", false)) {
559 actions.add(new ToggleUploadDiscouragedLayerAction(this));
560 }
561 actions.addAll(Arrays.asList(new Action[]{
562 new ConsistencyTestAction(),
563 SeparatorLayerAction.INSTANCE,
564 new LayerListPopup.InfoAction(this)}));
565 return actions.toArray(new Action[0]);
566 }
567
568 public static GpxData toGpxData(DataSet data, File file) {
569 GpxData gpxData = new GpxData();
570 gpxData.storageFile = file;
571 HashSet<Node> doneNodes = new HashSet<Node>();
572 for (Way w : data.getWays()) {
573 if (!w.isUsable()) {
574 continue;
575 }
576 Collection<Collection<WayPoint>> trk = new ArrayList<Collection<WayPoint>>();
577 Map<String, Object> trkAttr = new HashMap<String, Object>();
578
579 if (w.get("name") != null) {
580 trkAttr.put("name", w.get("name"));
581 }
582
583 List<WayPoint> trkseg = null;
584 for (Node n : w.getNodes()) {
585 if (!n.isUsable()) {
586 trkseg = null;
587 continue;
588 }
589 if (trkseg == null) {
590 trkseg = new ArrayList<WayPoint>();
591 trk.add(trkseg);
592 }
593 if (!n.isTagged()) {
594 doneNodes.add(n);
595 }
596 WayPoint wpt = new WayPoint(n.getCoor());
597 if (!n.isTimestampEmpty()) {
598 wpt.attr.put("time", DateUtils.fromDate(n.getTimestamp()));
599 wpt.setTime();
600 }
601 trkseg.add(wpt);
602 }
603
604 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
605 }
606
607 for (Node n : data.getNodes()) {
608 if (n.isIncomplete() || n.isDeleted() || doneNodes.contains(n)) {
609 continue;
610 }
611 String name = n.get("name");
612 if (name == null) {
613 continue;
614 }
615 WayPoint wpt = new WayPoint(n.getCoor());
616 wpt.attr.put("name", name);
617 if (!n.isTimestampEmpty()) {
618 wpt.attr.put("time", DateUtils.fromDate(n.getTimestamp()));
619 wpt.setTime();
620 }
621 String desc = n.get("description");
622 if (desc != null) {
623 wpt.attr.put("desc", desc);
624 }
625
626 gpxData.waypoints.add(wpt);
627 }
628 return gpxData;
629 }
630
631 public GpxData toGpxData() {
632 return toGpxData(data, getAssociatedFile());
633 }
634
635 public class ConvertToGpxLayerAction extends AbstractAction {
636 public ConvertToGpxLayerAction() {
637 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
638 putValue("help", ht("/Action/ConvertToGpxLayer"));
639 }
640 public void actionPerformed(ActionEvent e) {
641 Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName())));
642 Main.main.removeLayer(OsmDataLayer.this);
643 }
644 }
645
646 public boolean containsPoint(LatLon coor) {
647 // we'll assume that if this has no data sources
648 // that it also has no borders
649 if (this.data.dataSources.isEmpty())
650 return true;
651
652 boolean layer_bounds_point = false;
653 for (DataSource src : this.data.dataSources) {
654 if (src.bounds.contains(coor)) {
655 layer_bounds_point = true;
656 break;
657 }
658 }
659 return layer_bounds_point;
660 }
661
662 /**
663 * replies the set of conflicts currently managed in this layer
664 *
665 * @return the set of conflicts currently managed in this layer
666 */
667 public ConflictCollection getConflicts() {
668 return conflicts;
669 }
670
671 /**
672 * Replies true if the data managed by this layer needs to be uploaded to
673 * the server because it contains at least one modified primitive.
674 *
675 * @return true if the data managed by this layer needs to be uploaded to
676 * the server because it contains at least one modified primitive; false,
677 * otherwise
678 */
679 public boolean requiresUploadToServer() {
680 return requiresUploadToServer;
681 }
682
683 /**
684 * Replies true if the data managed by this layer needs to be saved to
685 * a file. Only replies true if a file is assigned to this layer and
686 * if the data managed by this layer has been modified since the last
687 * save operation to the file.
688 *
689 * @return true if the data managed by this layer needs to be saved to
690 * a file
691 */
692 public boolean requiresSaveToFile() {
693 return getAssociatedFile() != null && requiresSaveToFile;
694 }
695
696 @Override
697 public void onPostLoadFromFile() {
698 setRequiresSaveToFile(false);
699 setRequiresUploadToServer(data.isModified());
700 }
701
702 public void onPostDownloadFromServer() {
703 setRequiresSaveToFile(true);
704 setRequiresUploadToServer(data.isModified());
705 }
706
707 @Override
708 public boolean isChanged() {
709 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
710 }
711
712 /**
713 * Initializes the layer after a successful save of OSM data to a file
714 *
715 */
716 public void onPostSaveToFile() {
717 setRequiresSaveToFile(false);
718 setRequiresUploadToServer(data.isModified());
719 }
720
721 /**
722 * Initializes the layer after a successful upload to the server
723 *
724 */
725 public void onPostUploadToServer() {
726 setRequiresUploadToServer(data.isModified());
727 // keep requiresSaveToDisk unchanged
728 }
729
730 private class ConsistencyTestAction extends AbstractAction {
731
732 public ConsistencyTestAction() {
733 super(tr("Dataset consistency test"));
734 }
735
736 public void actionPerformed(ActionEvent e) {
737 String result = DatasetConsistencyTest.runTests(data);
738 if (result.length() == 0) {
739 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
740 } else {
741 JPanel p = new JPanel(new GridBagLayout());
742 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
743 JTextArea info = new JTextArea(result, 20, 60);
744 info.setCaretPosition(0);
745 info.setEditable(false);
746 p.add(new JScrollPane(info), GBC.eop());
747
748 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
749 }
750 }
751 }
752
753 @Override
754 public void destroy() {
755 DataSet.removeSelectionListener(this);
756 }
757
758 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
759 isChanged = true;
760 setRequiresSaveToFile(true);
761 setRequiresUploadToServer(true);
762 }
763
764 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
765 isChanged = true;
766 }
767
768 @Override
769 public void projectionChanged(Projection oldValue, Projection newValue) {
770 /*
771 * No reprojection required. The dataset itself is registered as projection
772 * change listener and already got notified.
773 */
774 }
775
776 public final boolean isUploadDiscouraged() {
777 return data.isUploadDiscouraged();
778 }
779
780 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
781 if (uploadDiscouraged ^ isUploadDiscouraged()) {
782 data.setUploadDiscouraged(uploadDiscouraged);
783 for (LayerStateChangeListener l : layerStateChangeListeners) {
784 l.uploadDiscouragedChanged(this, uploadDiscouraged);
785 }
786 }
787 }
788
789 @Override
790 public boolean isSavable() {
791 return true; // With OsmExporter
792 }
793
794 @Override
795 public boolean checkSaveConditions() {
796 if (isDataSetEmpty()) {
797 ExtendedDialog dialog = new ExtendedDialog(
798 Main.parent,
799 tr("Empty document"),
800 new String[] {tr("Save anyway"), tr("Cancel")}
801 );
802 dialog.setContent(tr("The document contains no data."));
803 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
804 dialog.showDialog();
805 if (dialog.getValue() != 1) return false;
806 }
807
808 ConflictCollection conflicts = getConflicts();
809 if (conflicts != null && !conflicts.isEmpty()) {
810 ExtendedDialog dialog = new ExtendedDialog(
811 Main.parent,
812 /* I18N: Display title of the window showing conflicts */
813 tr("Conflicts"),
814 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
815 );
816 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
817 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
818 dialog.showDialog();
819 if (dialog.getValue() != 1) return false;
820 }
821 return true;
822 }
823
824 /**
825 * Check the data set if it would be empty on save. It is empty, if it contains
826 * no objects (after all objects that are created and deleted without being
827 * transferred to the server have been removed).
828 *
829 * @return <code>true</code>, if a save result in an empty data set.
830 */
831 private boolean isDataSetEmpty() {
832 if (data != null) {
833 for (OsmPrimitive osm : data.allNonDeletedPrimitives())
834 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
835 return false;
836 }
837 return true;
838 }
839
840 @Override
841 public File createAndOpenSaveFileChooser() {
842 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
843 }
844}
Note: See TracBrowser for help on using the repository browser.