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

Last change on this file since 7026 was 7026, checked in by stoecker, 10 years ago

fix #3142 - drop applet code finally

  • Property svn:eol-style set to native
File size: 28.6 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 List<Action> actions = new ArrayList<>();
493 actions.addAll(Arrays.asList(new Action[]{
494 LayerListDialog.getInstance().createActivateLayerAction(this),
495 LayerListDialog.getInstance().createShowHideLayerAction(),
496 LayerListDialog.getInstance().createDeleteLayerAction(),
497 SeparatorLayerAction.INSTANCE,
498 LayerListDialog.getInstance().createMergeLayerAction(this),
499 new LayerSaveAction(this),
500 new LayerSaveAsAction(this),
501 }));
502 if (ExpertToggleAction.isExpert()) {
503 actions.addAll(Arrays.asList(new Action[]{
504 new LayerGpxExportAction(this),
505 new ConvertToGpxLayerAction()}));
506 }
507 actions.addAll(Arrays.asList(new Action[]{
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[actions.size()]);
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<>();
524 for (Way w : data.getWays()) {
525 if (!w.isUsable()) {
526 continue;
527 }
528 Collection<Collection<WayPoint>> trk = new ArrayList<>();
529 Map<String, Object> trkAttr = new HashMap<>();
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<>();
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 WayPoint wpt = new WayPoint(n.getCoor());
564 String name = n.get("name");
565 if (name != null) {
566 wpt.attr.put("name", name);
567 }
568 if (!n.isTimestampEmpty()) {
569 wpt.attr.put("time", DateUtils.fromDate(n.getTimestamp()));
570 wpt.setTime();
571 }
572 String desc = n.get("description");
573 if (desc != null) {
574 wpt.attr.put("desc", desc);
575 }
576
577 gpxData.waypoints.add(wpt);
578 }
579 return gpxData;
580 }
581
582 public GpxData toGpxData() {
583 return toGpxData(data, getAssociatedFile());
584 }
585
586 public class ConvertToGpxLayerAction extends AbstractAction {
587 public ConvertToGpxLayerAction() {
588 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
589 putValue("help", ht("/Action/ConvertToGpxLayer"));
590 }
591 @Override
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 @Override
689 public void actionPerformed(ActionEvent e) {
690 String result = DatasetConsistencyTest.runTests(data);
691 if (result.length() == 0) {
692 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
693 } else {
694 JPanel p = new JPanel(new GridBagLayout());
695 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
696 JosmTextArea info = new JosmTextArea(result, 20, 60);
697 info.setCaretPosition(0);
698 info.setEditable(false);
699 p.add(new JScrollPane(info), GBC.eop());
700
701 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
702 }
703 }
704 }
705
706 @Override
707 public void destroy() {
708 DataSet.removeSelectionListener(this);
709 }
710
711 @Override
712 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
713 isChanged = true;
714 setRequiresSaveToFile(true);
715 setRequiresUploadToServer(true);
716 }
717
718 @Override
719 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
720 isChanged = true;
721 }
722
723 @Override
724 public void projectionChanged(Projection oldValue, Projection newValue) {
725 /*
726 * No reprojection required. The dataset itself is registered as projection
727 * change listener and already got notified.
728 */
729 }
730
731 public final boolean isUploadDiscouraged() {
732 return data.isUploadDiscouraged();
733 }
734
735 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
736 if (uploadDiscouraged ^ isUploadDiscouraged()) {
737 data.setUploadDiscouraged(uploadDiscouraged);
738 for (LayerStateChangeListener l : layerStateChangeListeners) {
739 l.uploadDiscouragedChanged(this, uploadDiscouraged);
740 }
741 }
742 }
743
744 @Override
745 public boolean isSavable() {
746 return true; // With OsmExporter
747 }
748
749 @Override
750 public boolean checkSaveConditions() {
751 if (isDataSetEmpty()) {
752 ExtendedDialog dialog = new ExtendedDialog(
753 Main.parent,
754 tr("Empty document"),
755 new String[] {tr("Save anyway"), tr("Cancel")}
756 );
757 dialog.setContent(tr("The document contains no data."));
758 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
759 dialog.showDialog();
760 if (dialog.getValue() != 1) return false;
761 }
762
763 ConflictCollection conflicts = getConflicts();
764 if (conflicts != null && !conflicts.isEmpty()) {
765 ExtendedDialog dialog = new ExtendedDialog(
766 Main.parent,
767 /* I18N: Display title of the window showing conflicts */
768 tr("Conflicts"),
769 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
770 );
771 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
772 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
773 dialog.showDialog();
774 if (dialog.getValue() != 1) return false;
775 }
776 return true;
777 }
778
779 /**
780 * Check the data set if it would be empty on save. It is empty, if it contains
781 * no objects (after all objects that are created and deleted without being
782 * transferred to the server have been removed).
783 *
784 * @return <code>true</code>, if a save result in an empty data set.
785 */
786 private boolean isDataSetEmpty() {
787 if (data != null) {
788 for (OsmPrimitive osm : data.allNonDeletedPrimitives())
789 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
790 return false;
791 }
792 return true;
793 }
794
795 @Override
796 public File createAndOpenSaveFileChooser() {
797 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
798 }
799}
Note: See TracBrowser for help on using the repository browser.