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

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

fix #8609 - NPE

  • 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;
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 * @param progressMonitor the progress monitor, can be {@code null}
364 */
365 public void mergeFrom(final DataSet from, ProgressMonitor progressMonitor) {
366 final DataSetMerger visitor = new DataSetMerger(data,from);
367 try {
368 visitor.merge(progressMonitor);
369 } catch (DataIntegrityProblemException e) {
370 JOptionPane.showMessageDialog(
371 Main.parent,
372 e.getHtmlMessage() != null ? e.getHtmlMessage() : e.getMessage(),
373 tr("Error"),
374 JOptionPane.ERROR_MESSAGE
375 );
376 return;
377
378 }
379
380 Area a = data.getDataSourceArea();
381
382 // copy the merged layer's data source info;
383 // only add source rectangles if they are not contained in the
384 // layer already.
385 for (DataSource src : from.dataSources) {
386 if (a == null || !a.contains(src.bounds.asRect())) {
387 data.dataSources.add(src);
388 }
389 }
390
391 // copy the merged layer's API version, downgrade if required
392 if (data.getVersion() == null) {
393 data.setVersion(from.getVersion());
394 } else if ("0.5".equals(data.getVersion()) ^ "0.5".equals(from.getVersion())) {
395 System.err.println(tr("Warning: mixing 0.6 and 0.5 data results in version 0.5"));
396 data.setVersion("0.5");
397 }
398
399 int numNewConflicts = 0;
400 for (Conflict<?> c : visitor.getConflicts()) {
401 if (!conflicts.hasConflict(c)) {
402 numNewConflicts++;
403 conflicts.add(c);
404 }
405 }
406 // repaint to make sure new data is displayed properly.
407 if (Main.map != null && Main.map.mapView != null) {
408 Main.map.mapView.repaint();
409 }
410 // warn about new conflicts
411 if (numNewConflicts > 0 && Main.map != null && Main.map.conflictDialog != null) {
412 Main.map.conflictDialog.warnNumNewConflicts(numNewConflicts);
413 }
414 }
415
416 @Override public boolean isMergable(final Layer other) {
417 // isUploadDiscouraged commented to allow merging between normal layers and discouraged layers with a warning (see #7684)
418 return other instanceof OsmDataLayer;// && (isUploadDiscouraged() == ((OsmDataLayer)other).isUploadDiscouraged());
419 }
420
421 @Override public void visitBoundingBox(final BoundingXYVisitor v) {
422 for (final Node n: data.getNodes()) {
423 if (n.isUsable()) {
424 v.visit(n);
425 }
426 }
427 }
428
429 /**
430 * Clean out the data behind the layer. This means clearing the redo/undo lists,
431 * really deleting all deleted objects and reset the modified flags. This should
432 * be done after an upload, even after a partial upload.
433 *
434 * @param processed A list of all objects that were actually uploaded.
435 * May be <code>null</code>, which means nothing has been uploaded
436 */
437 public void cleanupAfterUpload(final Collection<IPrimitive> processed) {
438 // return immediately if an upload attempt failed
439 if (processed == null || processed.isEmpty())
440 return;
441
442 Main.main.undoRedo.clean(this);
443
444 // if uploaded, clean the modified flags as well
445 data.cleanupDeletedPrimitives();
446 for (OsmPrimitive p: data.allPrimitives()) {
447 if (processed.contains(p)) {
448 p.setModified(false);
449 }
450 }
451 }
452
453
454 @Override public Object getInfoComponent() {
455 final DataCountVisitor counter = new DataCountVisitor();
456 for (final OsmPrimitive osm : data.allPrimitives()) {
457 osm.visit(counter);
458 }
459 final JPanel p = new JPanel(new GridBagLayout());
460
461 String nodeText = trn("{0} node", "{0} nodes", counter.nodes, counter.nodes);
462 if (counter.deletedNodes > 0) {
463 nodeText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedNodes, counter.deletedNodes)+")";
464 }
465
466 String wayText = trn("{0} way", "{0} ways", counter.ways, counter.ways);
467 if (counter.deletedWays > 0) {
468 wayText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedWays, counter.deletedWays)+")";
469 }
470
471 String relationText = trn("{0} relation", "{0} relations", counter.relations, counter.relations);
472 if (counter.deletedRelations > 0) {
473 relationText += " ("+trn("{0} deleted", "{0} deleted", counter.deletedRelations, counter.deletedRelations)+")";
474 }
475
476 p.add(new JLabel(tr("{0} consists of:", getName())), GBC.eol());
477 p.add(new JLabel(nodeText, ImageProvider.get("data", "node"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
478 p.add(new JLabel(wayText, ImageProvider.get("data", "way"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
479 p.add(new JLabel(relationText, ImageProvider.get("data", "relation"), JLabel.HORIZONTAL), GBC.eop().insets(15,0,0,0));
480 p.add(new JLabel(tr("API version: {0}", (data.getVersion() != null) ? data.getVersion() : tr("unset"))), GBC.eop().insets(15,0,0,0));
481 if (isUploadDiscouraged()) {
482 p.add(new JLabel(tr("Upload is discouraged")), GBC.eop().insets(15,0,0,0));
483 }
484
485 return p;
486 }
487
488 @Override public Action[] getMenuEntries() {
489 if (Main.applet)
490 return new Action[]{
491 LayerListDialog.getInstance().createActivateLayerAction(this),
492 LayerListDialog.getInstance().createShowHideLayerAction(),
493 LayerListDialog.getInstance().createDeleteLayerAction(),
494 SeparatorLayerAction.INSTANCE,
495 LayerListDialog.getInstance().createMergeLayerAction(this),
496 SeparatorLayerAction.INSTANCE,
497 new RenameLayerAction(getAssociatedFile(), this),
498 new ConsistencyTestAction(),
499 SeparatorLayerAction.INSTANCE,
500 new LayerListPopup.InfoAction(this)};
501 ArrayList<Action> actions = new ArrayList<Action>();
502 actions.addAll(Arrays.asList(new Action[]{
503 LayerListDialog.getInstance().createActivateLayerAction(this),
504 LayerListDialog.getInstance().createShowHideLayerAction(),
505 LayerListDialog.getInstance().createDeleteLayerAction(),
506 SeparatorLayerAction.INSTANCE,
507 LayerListDialog.getInstance().createMergeLayerAction(this),
508 new LayerSaveAction(this),
509 new LayerSaveAsAction(this),
510 new LayerGpxExportAction(this),
511 new ConvertToGpxLayerAction(),
512 SeparatorLayerAction.INSTANCE,
513 new RenameLayerAction(getAssociatedFile(), this)}));
514 if (ExpertToggleAction.isExpert() && Main.pref.getBoolean("data.layer.upload_discouragement.menu_item", false)) {
515 actions.add(new ToggleUploadDiscouragedLayerAction(this));
516 }
517 actions.addAll(Arrays.asList(new Action[]{
518 new ConsistencyTestAction(),
519 SeparatorLayerAction.INSTANCE,
520 new LayerListPopup.InfoAction(this)}));
521 return actions.toArray(new Action[0]);
522 }
523
524 public static GpxData toGpxData(DataSet data, File file) {
525 GpxData gpxData = new GpxData();
526 gpxData.storageFile = file;
527 HashSet<Node> doneNodes = new HashSet<Node>();
528 for (Way w : data.getWays()) {
529 if (!w.isUsable()) {
530 continue;
531 }
532 Collection<Collection<WayPoint>> trk = new ArrayList<Collection<WayPoint>>();
533 Map<String, Object> trkAttr = new HashMap<String, Object>();
534
535 if (w.get("name") != null) {
536 trkAttr.put("name", w.get("name"));
537 }
538
539 List<WayPoint> trkseg = null;
540 for (Node n : w.getNodes()) {
541 if (!n.isUsable()) {
542 trkseg = null;
543 continue;
544 }
545 if (trkseg == null) {
546 trkseg = new ArrayList<WayPoint>();
547 trk.add(trkseg);
548 }
549 if (!n.isTagged()) {
550 doneNodes.add(n);
551 }
552 WayPoint wpt = new WayPoint(n.getCoor());
553 if (!n.isTimestampEmpty()) {
554 wpt.attr.put("time", DateUtils.fromDate(n.getTimestamp()));
555 wpt.setTime();
556 }
557 trkseg.add(wpt);
558 }
559
560 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
561 }
562
563 for (Node n : data.getNodes()) {
564 if (n.isIncomplete() || n.isDeleted() || doneNodes.contains(n)) {
565 continue;
566 }
567 String name = n.get("name");
568 if (name == null) {
569 continue;
570 }
571 WayPoint wpt = new WayPoint(n.getCoor());
572 wpt.attr.put("name", name);
573 if (!n.isTimestampEmpty()) {
574 wpt.attr.put("time", DateUtils.fromDate(n.getTimestamp()));
575 wpt.setTime();
576 }
577 String desc = n.get("description");
578 if (desc != null) {
579 wpt.attr.put("desc", desc);
580 }
581
582 gpxData.waypoints.add(wpt);
583 }
584 return gpxData;
585 }
586
587 public GpxData toGpxData() {
588 return toGpxData(data, getAssociatedFile());
589 }
590
591 public class ConvertToGpxLayerAction extends AbstractAction {
592 public ConvertToGpxLayerAction() {
593 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
594 putValue("help", ht("/Action/ConvertToGpxLayer"));
595 }
596 public void actionPerformed(ActionEvent e) {
597 Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName())));
598 Main.main.removeLayer(OsmDataLayer.this);
599 }
600 }
601
602 public boolean containsPoint(LatLon coor) {
603 // we'll assume that if this has no data sources
604 // that it also has no borders
605 if (this.data.dataSources.isEmpty())
606 return true;
607
608 boolean layer_bounds_point = false;
609 for (DataSource src : this.data.dataSources) {
610 if (src.bounds.contains(coor)) {
611 layer_bounds_point = true;
612 break;
613 }
614 }
615 return layer_bounds_point;
616 }
617
618 /**
619 * replies the set of conflicts currently managed in this layer
620 *
621 * @return the set of conflicts currently managed in this layer
622 */
623 public ConflictCollection getConflicts() {
624 return conflicts;
625 }
626
627 /**
628 * Replies true if the data managed by this layer needs to be uploaded to
629 * the server because it contains at least one modified primitive.
630 *
631 * @return true if the data managed by this layer needs to be uploaded to
632 * the server because it contains at least one modified primitive; false,
633 * otherwise
634 */
635 public boolean requiresUploadToServer() {
636 return requiresUploadToServer;
637 }
638
639 /**
640 * Replies true if the data managed by this layer needs to be saved to
641 * a file. Only replies true if a file is assigned to this layer and
642 * if the data managed by this layer has been modified since the last
643 * save operation to the file.
644 *
645 * @return true if the data managed by this layer needs to be saved to
646 * a file
647 */
648 public boolean requiresSaveToFile() {
649 return getAssociatedFile() != null && requiresSaveToFile;
650 }
651
652 @Override
653 public void onPostLoadFromFile() {
654 setRequiresSaveToFile(false);
655 setRequiresUploadToServer(data.isModified());
656 }
657
658 public void onPostDownloadFromServer() {
659 setRequiresSaveToFile(true);
660 setRequiresUploadToServer(data.isModified());
661 }
662
663 @Override
664 public boolean isChanged() {
665 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
666 }
667
668 /**
669 * Initializes the layer after a successful save of OSM data to a file
670 *
671 */
672 public void onPostSaveToFile() {
673 setRequiresSaveToFile(false);
674 setRequiresUploadToServer(data.isModified());
675 }
676
677 /**
678 * Initializes the layer after a successful upload to the server
679 *
680 */
681 public void onPostUploadToServer() {
682 setRequiresUploadToServer(data.isModified());
683 // keep requiresSaveToDisk unchanged
684 }
685
686 private class ConsistencyTestAction extends AbstractAction {
687
688 public ConsistencyTestAction() {
689 super(tr("Dataset consistency test"));
690 }
691
692 public void actionPerformed(ActionEvent e) {
693 String result = DatasetConsistencyTest.runTests(data);
694 if (result.length() == 0) {
695 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
696 } else {
697 JPanel p = new JPanel(new GridBagLayout());
698 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
699 JTextArea info = new JTextArea(result, 20, 60);
700 info.setCaretPosition(0);
701 info.setEditable(false);
702 p.add(new JScrollPane(info), GBC.eop());
703
704 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
705 }
706 }
707 }
708
709 @Override
710 public void destroy() {
711 DataSet.removeSelectionListener(this);
712 }
713
714 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
715 isChanged = true;
716 setRequiresSaveToFile(true);
717 setRequiresUploadToServer(true);
718 }
719
720 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
721 isChanged = true;
722 }
723
724 @Override
725 public void projectionChanged(Projection oldValue, Projection newValue) {
726 /*
727 * No reprojection required. The dataset itself is registered as projection
728 * change listener and already got notified.
729 */
730 }
731
732 public final boolean isUploadDiscouraged() {
733 return data.isUploadDiscouraged();
734 }
735
736 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
737 if (uploadDiscouraged ^ isUploadDiscouraged()) {
738 data.setUploadDiscouraged(uploadDiscouraged);
739 for (LayerStateChangeListener l : layerStateChangeListeners) {
740 l.uploadDiscouragedChanged(this, uploadDiscouraged);
741 }
742 }
743 }
744
745 @Override
746 public boolean isSavable() {
747 return true; // With OsmExporter
748 }
749
750 @Override
751 public boolean checkSaveConditions() {
752 if (isDataSetEmpty()) {
753 ExtendedDialog dialog = new ExtendedDialog(
754 Main.parent,
755 tr("Empty document"),
756 new String[] {tr("Save anyway"), tr("Cancel")}
757 );
758 dialog.setContent(tr("The document contains no data."));
759 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
760 dialog.showDialog();
761 if (dialog.getValue() != 1) return false;
762 }
763
764 ConflictCollection conflicts = getConflicts();
765 if (conflicts != null && !conflicts.isEmpty()) {
766 ExtendedDialog dialog = new ExtendedDialog(
767 Main.parent,
768 /* I18N: Display title of the window showing conflicts */
769 tr("Conflicts"),
770 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
771 );
772 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
773 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
774 dialog.showDialog();
775 if (dialog.getValue() != 1) return false;
776 }
777 return true;
778 }
779
780 /**
781 * Check the data set if it would be empty on save. It is empty, if it contains
782 * no objects (after all objects that are created and deleted without being
783 * transferred to the server have been removed).
784 *
785 * @return <code>true</code>, if a save result in an empty data set.
786 */
787 private boolean isDataSetEmpty() {
788 if (data != null) {
789 for (OsmPrimitive osm : data.allNonDeletedPrimitives())
790 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
791 return false;
792 }
793 return true;
794 }
795
796 @Override
797 public File createAndOpenSaveFileChooser() {
798 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
799 }
800}
Note: See TracBrowser for help on using the repository browser.