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

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

see #8503 - Allo plugins to warn about conflicts

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