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

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

drop support of OSM API 0.5

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