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

Last change on this file since 6070 was 6070, checked in by stoecker, 11 years ago

see #8853 remove tabs, trailing spaces, windows line ends, strange characters

  • Property svn:eol-style set to native
File size: 29.4 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 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.accept(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 }));
511 if (ExpertToggleAction.isExpert()) {
512 actions.addAll(Arrays.asList(new Action[]{
513 new LayerGpxExportAction(this),
514 new ConvertToGpxLayerAction()}));
515 }
516 actions.addAll(Arrays.asList(new Action[]{
517 SeparatorLayerAction.INSTANCE,
518 new RenameLayerAction(getAssociatedFile(), this)}));
519 if (ExpertToggleAction.isExpert() && Main.pref.getBoolean("data.layer.upload_discouragement.menu_item", false)) {
520 actions.add(new ToggleUploadDiscouragedLayerAction(this));
521 }
522 actions.addAll(Arrays.asList(new Action[]{
523 new ConsistencyTestAction(),
524 SeparatorLayerAction.INSTANCE,
525 new LayerListPopup.InfoAction(this)}));
526 return actions.toArray(new Action[0]);
527 }
528
529 public static GpxData toGpxData(DataSet data, File file) {
530 GpxData gpxData = new GpxData();
531 gpxData.storageFile = file;
532 HashSet<Node> doneNodes = new HashSet<Node>();
533 for (Way w : data.getWays()) {
534 if (!w.isUsable()) {
535 continue;
536 }
537 Collection<Collection<WayPoint>> trk = new ArrayList<Collection<WayPoint>>();
538 Map<String, Object> trkAttr = new HashMap<String, Object>();
539
540 if (w.get("name") != null) {
541 trkAttr.put("name", w.get("name"));
542 }
543
544 List<WayPoint> trkseg = null;
545 for (Node n : w.getNodes()) {
546 if (!n.isUsable()) {
547 trkseg = null;
548 continue;
549 }
550 if (trkseg == null) {
551 trkseg = new ArrayList<WayPoint>();
552 trk.add(trkseg);
553 }
554 if (!n.isTagged()) {
555 doneNodes.add(n);
556 }
557 WayPoint wpt = new WayPoint(n.getCoor());
558 if (!n.isTimestampEmpty()) {
559 wpt.attr.put("time", DateUtils.fromDate(n.getTimestamp()));
560 wpt.setTime();
561 }
562 trkseg.add(wpt);
563 }
564
565 gpxData.tracks.add(new ImmutableGpxTrack(trk, trkAttr));
566 }
567
568 for (Node n : data.getNodes()) {
569 if (n.isIncomplete() || n.isDeleted() || doneNodes.contains(n)) {
570 continue;
571 }
572 WayPoint wpt = new WayPoint(n.getCoor());
573 String name = n.get("name");
574 if (name != null) {
575 wpt.attr.put("name", name);
576 }
577 if (!n.isTimestampEmpty()) {
578 wpt.attr.put("time", DateUtils.fromDate(n.getTimestamp()));
579 wpt.setTime();
580 }
581 String desc = n.get("description");
582 if (desc != null) {
583 wpt.attr.put("desc", desc);
584 }
585
586 gpxData.waypoints.add(wpt);
587 }
588 return gpxData;
589 }
590
591 public GpxData toGpxData() {
592 return toGpxData(data, getAssociatedFile());
593 }
594
595 public class ConvertToGpxLayerAction extends AbstractAction {
596 public ConvertToGpxLayerAction() {
597 super(tr("Convert to GPX layer"), ImageProvider.get("converttogpx"));
598 putValue("help", ht("/Action/ConvertToGpxLayer"));
599 }
600 public void actionPerformed(ActionEvent e) {
601 Main.main.addLayer(new GpxLayer(toGpxData(), tr("Converted from: {0}", getName())));
602 Main.main.removeLayer(OsmDataLayer.this);
603 }
604 }
605
606 public boolean containsPoint(LatLon coor) {
607 // we'll assume that if this has no data sources
608 // that it also has no borders
609 if (this.data.dataSources.isEmpty())
610 return true;
611
612 boolean layer_bounds_point = false;
613 for (DataSource src : this.data.dataSources) {
614 if (src.bounds.contains(coor)) {
615 layer_bounds_point = true;
616 break;
617 }
618 }
619 return layer_bounds_point;
620 }
621
622 /**
623 * replies the set of conflicts currently managed in this layer
624 *
625 * @return the set of conflicts currently managed in this layer
626 */
627 public ConflictCollection getConflicts() {
628 return conflicts;
629 }
630
631 /**
632 * Replies true if the data managed by this layer needs to be uploaded to
633 * the server because it contains at least one modified primitive.
634 *
635 * @return true if the data managed by this layer needs to be uploaded to
636 * the server because it contains at least one modified primitive; false,
637 * otherwise
638 */
639 public boolean requiresUploadToServer() {
640 return requiresUploadToServer;
641 }
642
643 /**
644 * Replies true if the data managed by this layer needs to be saved to
645 * a file. Only replies true if a file is assigned to this layer and
646 * if the data managed by this layer has been modified since the last
647 * save operation to the file.
648 *
649 * @return true if the data managed by this layer needs to be saved to
650 * a file
651 */
652 public boolean requiresSaveToFile() {
653 return getAssociatedFile() != null && requiresSaveToFile;
654 }
655
656 @Override
657 public void onPostLoadFromFile() {
658 setRequiresSaveToFile(false);
659 setRequiresUploadToServer(data.isModified());
660 }
661
662 public void onPostDownloadFromServer() {
663 setRequiresSaveToFile(true);
664 setRequiresUploadToServer(data.isModified());
665 }
666
667 @Override
668 public boolean isChanged() {
669 return isChanged || highlightUpdateCount != data.getHighlightUpdateCount();
670 }
671
672 /**
673 * Initializes the layer after a successful save of OSM data to a file
674 *
675 */
676 public void onPostSaveToFile() {
677 setRequiresSaveToFile(false);
678 setRequiresUploadToServer(data.isModified());
679 }
680
681 /**
682 * Initializes the layer after a successful upload to the server
683 *
684 */
685 public void onPostUploadToServer() {
686 setRequiresUploadToServer(data.isModified());
687 // keep requiresSaveToDisk unchanged
688 }
689
690 private class ConsistencyTestAction extends AbstractAction {
691
692 public ConsistencyTestAction() {
693 super(tr("Dataset consistency test"));
694 }
695
696 public void actionPerformed(ActionEvent e) {
697 String result = DatasetConsistencyTest.runTests(data);
698 if (result.length() == 0) {
699 JOptionPane.showMessageDialog(Main.parent, tr("No problems found"));
700 } else {
701 JPanel p = new JPanel(new GridBagLayout());
702 p.add(new JLabel(tr("Following problems found:")), GBC.eol());
703 JosmTextArea info = new JosmTextArea(result, 20, 60);
704 info.setCaretPosition(0);
705 info.setEditable(false);
706 p.add(new JScrollPane(info), GBC.eop());
707
708 JOptionPane.showMessageDialog(Main.parent, p, tr("Warning"), JOptionPane.WARNING_MESSAGE);
709 }
710 }
711 }
712
713 @Override
714 public void destroy() {
715 DataSet.removeSelectionListener(this);
716 }
717
718 public void processDatasetEvent(AbstractDatasetChangedEvent event) {
719 isChanged = true;
720 setRequiresSaveToFile(true);
721 setRequiresUploadToServer(true);
722 }
723
724 public void selectionChanged(Collection<? extends OsmPrimitive> newSelection) {
725 isChanged = true;
726 }
727
728 @Override
729 public void projectionChanged(Projection oldValue, Projection newValue) {
730 /*
731 * No reprojection required. The dataset itself is registered as projection
732 * change listener and already got notified.
733 */
734 }
735
736 public final boolean isUploadDiscouraged() {
737 return data.isUploadDiscouraged();
738 }
739
740 public final void setUploadDiscouraged(boolean uploadDiscouraged) {
741 if (uploadDiscouraged ^ isUploadDiscouraged()) {
742 data.setUploadDiscouraged(uploadDiscouraged);
743 for (LayerStateChangeListener l : layerStateChangeListeners) {
744 l.uploadDiscouragedChanged(this, uploadDiscouraged);
745 }
746 }
747 }
748
749 @Override
750 public boolean isSavable() {
751 return true; // With OsmExporter
752 }
753
754 @Override
755 public boolean checkSaveConditions() {
756 if (isDataSetEmpty()) {
757 ExtendedDialog dialog = new ExtendedDialog(
758 Main.parent,
759 tr("Empty document"),
760 new String[] {tr("Save anyway"), tr("Cancel")}
761 );
762 dialog.setContent(tr("The document contains no data."));
763 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
764 dialog.showDialog();
765 if (dialog.getValue() != 1) return false;
766 }
767
768 ConflictCollection conflicts = getConflicts();
769 if (conflicts != null && !conflicts.isEmpty()) {
770 ExtendedDialog dialog = new ExtendedDialog(
771 Main.parent,
772 /* I18N: Display title of the window showing conflicts */
773 tr("Conflicts"),
774 new String[] {tr("Reject Conflicts and Save"), tr("Cancel")}
775 );
776 dialog.setContent(tr("There are unresolved conflicts. Conflicts will not be saved and handled as if you rejected all. Continue?"));
777 dialog.setButtonIcons(new String[] {"save.png", "cancel.png"});
778 dialog.showDialog();
779 if (dialog.getValue() != 1) return false;
780 }
781 return true;
782 }
783
784 /**
785 * Check the data set if it would be empty on save. It is empty, if it contains
786 * no objects (after all objects that are created and deleted without being
787 * transferred to the server have been removed).
788 *
789 * @return <code>true</code>, if a save result in an empty data set.
790 */
791 private boolean isDataSetEmpty() {
792 if (data != null) {
793 for (OsmPrimitive osm : data.allNonDeletedPrimitives())
794 if (!osm.isDeleted() || !osm.isNewOrUndeleted())
795 return false;
796 }
797 return true;
798 }
799
800 @Override
801 public File createAndOpenSaveFileChooser() {
802 return SaveActionBase.createAndOpenSaveFileChooser(tr("Save OSM file"), "osm");
803 }
804}
Note: See TracBrowser for help on using the repository browser.