Пример #1
0
 @Override
 protected void finish() {
   if (canceled) return;
   if (lastException != null) {
     ExceptionDialogUtil.explainException(lastException);
     return;
   }
   GuiHelper.runInEDTAndWait(
       () -> {
         layer.mergeFrom(ds);
         if (zoom && Main.map != null) AutoScaleAction.zoomTo(ds.allPrimitives());
         layer.onPostDownloadFromServer();
       });
 }
Пример #2
0
  private OsmDataLayer makeLayer(
      String name, FilePlacement placement, OsmBuilder.Mode mode, ProgressMonitor monitor) {
    monitor.beginTask(tr("Building JOSM layer"), 100);
    OsmBuilder builder = new OsmBuilder(placement);
    DataSet data =
        builder.build(this.data.getLayers(), mode, monitor.createSubTaskMonitor(50, false));
    monitor.setTicks(50);
    monitor.setCustomText(tr("Postprocessing layer"));
    OsmDataLayer result = new OsmDataLayer(data, name, null);
    result.onPostLoadFromFile();

    monitor.finishTask();
    return result;
  }
Пример #3
0
 /**
  * Sets the title of the JOSM main window, adding a star if there are dirty layers.
  *
  * @see Main#parent
  */
 protected void refreshTitle() {
   if (Main.parent != null) {
     layerLock.readLock().lock();
     try {
       boolean dirty =
           editLayer != null
               && (editLayer.requiresSaveToFile()
                   || (editLayer.requiresUploadToServer() && !editLayer.isUploadDiscouraged()));
       ((JFrame) Main.parent).setTitle((dirty ? "* " : "") + tr("Java OpenStreetMap Editor"));
       ((JFrame) Main.parent).getRootPane().putClientProperty("Window.documentModified", dirty);
     } finally {
       layerLock.readLock().unlock();
     }
   }
 }
 void addConflicts(OsmPrimitive o) {
   Conflict<?> c = layer.getConflicts().getConflictForMy(o);
   if (c != null) {
     add(tr("In conflict with: "));
     addNameAndId(c.getTheir());
   }
 }
Пример #5
0
  private static boolean doInternalSave(Layer layer, File file) {
    if (file == null) return false;

    try {
      boolean exported = false;
      for (FileExporter exporter : ExtensionFileFilter.exporters) {
        if (exporter.acceptFile(file, layer)) {
          exporter.exportData(file, layer);
          exported = true;
          break;
        }
      }
      if (!exported) {
        JOptionPane.showMessageDialog(
            Main.parent,
            tr("No Exporter found! Nothing saved."),
            tr("Warning"),
            JOptionPane.WARNING_MESSAGE);
        return false;
      }
      layer.setName(file.getName());
      layer.setAssociatedFile(file);
      if (layer instanceof OsmDataLayer) {
        ((OsmDataLayer) layer).onPostSaveToFile();
      }
      Main.parent.repaint();
    } catch (IOException e) {
      e.printStackTrace();
      return false;
    }
    return true;
  }
Пример #6
0
  @Override
  public Element export(ExportSupport support) throws IOException {
    Element layerEl = support.createElement("layer");
    layerEl.setAttribute("type", "osm-data");
    layerEl.setAttribute("version", "0.1");

    Element file = support.createElement("file");
    layerEl.appendChild(file);

    if (requiresZip()) {
      String zipPath = "layers/" + String.format("%02d", support.getLayerIndex()) + "/data.osm";
      file.appendChild(support.createTextNode(zipPath));
      addDataFile(support.getOutputStreamZip(zipPath));
    } else {
      URI uri = layer.getAssociatedFile().toURI();
      URL url = null;
      try {
        url = uri.toURL();
      } catch (MalformedURLException e) {
        throw new IOException(e);
      }
      file.appendChild(support.createTextNode(url.toString()));
    }
    return layerEl;
  }
Пример #7
0
 /**
  * Replies true if the active data layer (edit layer) is visible.
  *
  * @return true if the active data layer (edit layer) is visible, false otherwise
  */
 public boolean isActiveLayerVisible() {
   layerLock.readLock().lock();
   try {
     return isActiveLayerDrawable() && editLayer.isVisible();
   } finally {
     layerLock.readLock().unlock();
   }
 }
Пример #8
0
 @Override
 public int hashCode() {
   final int prime = 31;
   int result = 1;
   result = prime * result + ((cloneMap == null) ? 0 : cloneMap.hashCode());
   result = prime * result + ((layer == null) ? 0 : layer.hashCode());
   return result;
 }
Пример #9
0
  private void save(File file, OsmDataLayer layer, boolean noBackup) {
    File tmpFile = null;
    try {
      // use a tmp file because if something errors out in the
      // process of writing the file, we might just end up with
      // a truncated file.  That can destroy lots of work.
      if (file.exists()) {
        tmpFile = new File(file.getPath() + "~");
        copy(file, tmpFile);
      }

      // create outputstream and wrap it with gzip or bzip, if necessary
      OutputStream out = getOutputStream(file);
      Writer writer = new OutputStreamWriter(out, "UTF-8");

      OsmWriter w =
          OsmWriterFactory.createOsmWriter(new PrintWriter(writer), false, layer.data.getVersion());
      layer.data.getReadLock().lock();
      try {
        w.writeLayer(layer);
        w.close();
      } finally {
        layer.data.getReadLock().unlock();
      }
      // FIXME - how to close?
      if (noBackup || !Main.pref.getBoolean("save.keepbackup", false)) {
        if (tmpFile != null) {
          tmpFile.delete();
        }
      }
      layer.onPostSaveToFile();
    } catch (IOException e) {
      e.printStackTrace();
      JOptionPane.showMessageDialog(
          Main.parent,
          tr("<html>An error occurred while saving.<br>Error is:<br>{0}</html>", e.getMessage()),
          tr("Error"),
          JOptionPane.ERROR_MESSAGE);

      try {
        // if the file save failed, then the tempfile will not
        // be deleted.  So, restore the backup if we made one.
        if (tmpFile != null && tmpFile.exists()) {
          copy(tmpFile, file);
        }
      } catch (IOException e2) {
        e2.printStackTrace();
        JOptionPane.showMessageDialog(
            Main.parent,
            tr(
                "<html>An error occurred while restoring backup file.<br>Error is:<br>{0}</html>",
                e2.getMessage()),
            tr("Error"),
            JOptionPane.ERROR_MESSAGE);
      }
    }
  }
Пример #10
0
  protected void cleanupAfterUpload() {
    // we always clean up the data, even in case of errors. It's possible the data was
    // partially uploaded. Better run on EDT.
    Runnable r =
        () -> {
          layer.cleanupAfterUpload(processedPrimitives);
          layer.onPostUploadToServer();
          ChangesetCache.getInstance().update(changeset);
        };

    try {
      SwingUtilities.invokeAndWait(r);
    } catch (InterruptedException e) {
      Main.trace(e);
      lastException = e;
    } catch (InvocationTargetException e) {
      Main.trace(e);
      lastException = new OsmTransferException(e.getCause());
    }
  }
 /**
  * Populates the turn restriction editor model with a turn restriction. {@code turnRestriction} is
  * an arbitrary relation. A tag type=restriction isn't required. If it is missing, it is added
  * here. {@code turnRestriction} must not be null and it must belong to a dataset.
  *
  * @param turnRestriction the turn restriction
  * @throws IllegalArgumentException thrown if turnRestriction is null
  * @throws IllegalArgumentException thrown if turnRestriction doesn't belong to a dataset
  */
 public void populate(Relation turnRestriction) {
   CheckParameterUtil.ensureParameterNotNull(turnRestriction, "turnRestriction");
   if (turnRestriction.getDataSet() != null && turnRestriction.getDataSet() != layer.data) {
     throw new IllegalArgumentException(
         // don't translate - it's a technical message
         MessageFormat.format(
             "turnRestriction {0} must not belong to a different dataset than the dataset of layer ''{1}''",
             turnRestriction.getId(), layer.getName()));
   }
   initFromTurnRestriction(turnRestriction);
 }
Пример #12
0
  /**
   * Add a layer to the current MapView. The layer will be added at topmost position.
   *
   * @param layer The layer to add
   */
  public void addLayer(Layer layer) {
    boolean isOsmDataLayer = layer instanceof OsmDataLayer;
    layerLock.writeLock().lock();
    layerLock.readLock().lock();
    EnumSet<LayerListenerType> listenersToFire = EnumSet.noneOf(LayerListenerType.class);
    Layer oldActiveLayer = activeLayer;
    OsmDataLayer oldEditLayer = editLayer;
    try {
      try {
        if (layer instanceof MarkerLayer && playHeadMarker == null) {
          playHeadMarker = PlayHeadMarker.create();
        }

        if (layer instanceof GpxLayer) {
          addGpxLayer((GpxLayer) layer);
        } else if (layers.isEmpty()) {
          layers.add(layer);
        } else if (layer.isBackgroundLayer()) {
          int i = 0;
          for (; i < layers.size(); i++) {
            if (layers.get(i).isBackgroundLayer()) {
              break;
            }
          }
          layers.add(i, layer);
        } else {
          layers.add(0, layer);
        }

        if (isOsmDataLayer || oldActiveLayer == null) {
          // autoselect the new layer
          listenersToFire.addAll(setActiveLayer(layer, true));
        }
      } finally {
        layerLock.writeLock().unlock();
      }

      fireLayerAdded(layer);
      if (isOsmDataLayer) {
        ((OsmDataLayer) layer).addLayerStateChangeListener(this);
      }
      onActiveEditLayerChanged(oldActiveLayer, oldEditLayer, listenersToFire);
      layer.addPropertyChangeListener(this);
      Main.addProjectionChangeListener(layer);
      AudioPlayer.reset();
    } finally {
      layerLock.readLock().unlock();
    }
    if (!listenersToFire.isEmpty()) {
      repaint();
    }
  }
Пример #13
0
 @Override
 public boolean equals(Object obj) {
   if (this == obj) return true;
   if (obj == null) return false;
   if (getClass() != obj.getClass()) return false;
   Command other = (Command) obj;
   if (cloneMap == null) {
     if (other.cloneMap != null) return false;
   } else if (!cloneMap.equals(other.cloneMap)) return false;
   if (layer == null) {
     if (other.layer != null) return false;
   } else if (!layer.equals(other.layer)) return false;
   return true;
 }
Пример #14
0
 /**
  * Creates the task
  *
  * @param strategy the upload strategy. Must not be null.
  * @param layer the OSM data layer for which data is uploaded. Must not be null.
  * @param toUpload the collection of primitives to upload. Set to the empty collection if null.
  * @param changeset the changeset to use for uploading. Must not be null. changeset.getId() can be
  *     0 in which case the upload task creates a new changeset
  * @throws IllegalArgumentException thrown if layer is null
  * @throws IllegalArgumentException thrown if toUpload is null
  * @throws IllegalArgumentException thrown if strategy is null
  * @throws IllegalArgumentException thrown if changeset is null
  */
 public UploadPrimitivesTask(
     UploadStrategySpecification strategy,
     OsmDataLayer layer,
     APIDataSet toUpload,
     Changeset changeset) {
   super(
       tr("Uploading data for layer ''{0}''", layer.getName()),
       false /* don't ignore exceptions */);
   ensureParameterNotNull(layer, "layer");
   ensureParameterNotNull(strategy, "strategy");
   ensureParameterNotNull(changeset, "changeset");
   this.toUpload = toUpload;
   this.layer = layer;
   this.changeset = changeset;
   this.strategy = strategy;
   this.processedPrimitives = new HashSet<OsmPrimitive>();
 }
  /**
   * Sets the way participating in the turn restriction in a given role.
   *
   * @param role the role. Must not be null.
   * @param wayId the id of the way to set
   * @exception IllegalArgumentException thrown if role is null
   * @exception IllegalArgumentException thrown if wayId != null isn't the id of a way
   * @exception IllegalStateException thrown the no way with this id was found in the dataset
   */
  public void setTurnRestrictionLeg(TurnRestrictionLegRole role, PrimitiveId wayId) {
    CheckParameterUtil.ensureParameterNotNull(role, "role");
    if (wayId == null) {
      setTurnRestrictionLeg(role, (Way) null);
      return;
    }
    if (!wayId.getType().equals(OsmPrimitiveType.WAY)) {
      throw new IllegalArgumentException(
          MessageFormat.format(
              "parameter ''wayId'' of type {0} expected, got {1}",
              OsmPrimitiveType.WAY, wayId.getType()));
    }

    OsmPrimitive p = layer.data.getPrimitiveById(wayId);
    if (p == null) {
      throw new IllegalStateException(
          MessageFormat.format(
              "didn''t find way with id {0} in layer ''{1}''", wayId, layer.getName()));
    }
    setTurnRestrictionLeg(role, (Way) p);
  }
Пример #16
0
  /**
   * Remove the layer from the mapview. If the layer was in the list before, an LayerChange event is
   * fired.
   *
   * @param layer The layer to remove
   */
  public void removeLayer(Layer layer) {
    layerLock.writeLock().lock();
    layerLock.readLock().lock();

    EnumSet<LayerListenerType> listenersToFire = EnumSet.noneOf(LayerListenerType.class);
    Layer oldActiveLayer = activeLayer;
    OsmDataLayer oldEditLayer = editLayer;
    try {
      try {
        List<Layer> layersList = new ArrayList<>(layers);

        if (!layersList.remove(layer)) return;

        listenersToFire = setEditLayer(layersList);

        if (layer == activeLayer) {
          listenersToFire.addAll(setActiveLayer(determineNextActiveLayer(layersList), false));
        }

        if (layer instanceof OsmDataLayer) {
          ((OsmDataLayer) layer).removeLayerPropertyChangeListener(this);
        }

        layers.remove(layer);
        Main.removeProjectionChangeListener(layer);

      } finally {
        layerLock.writeLock().unlock();
      }
      onActiveEditLayerChanged(oldActiveLayer, oldEditLayer, listenersToFire);
      fireLayerRemoved(layer);
      layer.removePropertyChangeListener(this);
      layer.destroy();
      AudioPlayer.reset();
    } finally {
      layerLock.readLock().unlock();
    }
    repaint();
  }
Пример #17
0
 protected OsmDataLayer createNewLayer(String layerName) {
   if (layerName == null || layerName.isEmpty()) {
     layerName = OsmDataLayer.createNewName();
   }
   return new OsmDataLayer(dataSet, layerName, null);
 }
Пример #18
0
  @Override
  public JPanel getExportPanel() {
    final JPanel p = new JPanel(new GridBagLayout());
    JPanel topRow = new JPanel(new GridBagLayout());
    export = new JCheckBox();
    export.setSelected(true);
    final JLabel lbl = new JLabel(layer.getName(), layer.getIcon(), SwingConstants.LEFT);
    lbl.setToolTipText(layer.getToolTipText());

    JLabel lblData = new JLabel(tr("Data:"));
    /* I18n: Refer to a OSM data file in session file */ link = new JRadioButton(tr("local file"));
    link.putClientProperty("actionname", "link");
    link.setToolTipText(tr("Link to a OSM data file on your local disk."));
    /* I18n: Include OSM data in session file */ include = new JRadioButton(tr("include"));
    include.setToolTipText(tr("Include OSM data in the .joz session file."));
    include.putClientProperty("actionname", "include");
    ButtonGroup group = new ButtonGroup();
    group.add(link);
    group.add(include);

    JPanel cardLink = new JPanel(new GridBagLayout());
    final File file = layer.getAssociatedFile();
    final LayerSaveAction saveAction = new LayerSaveAction();
    final JButton save = new JButton(saveAction);
    if (file != null) {
      JosmTextField tf = new JosmTextField();
      tf.setText(file.getPath());
      tf.setEditable(false);
      cardLink.add(tf, GBC.std());
      save.setMargin(new Insets(0, 0, 0, 0));
      cardLink.add(save, GBC.eol().insets(2, 0, 0, 0));
    } else {
      cardLink.add(new JLabel(tr("No file association")), GBC.eol());
    }

    JPanel cardInclude = new JPanel(new GridBagLayout());
    JLabel lblIncl = new JLabel(tr("OSM data will be included in the session file."));
    lblIncl.setFont(lblIncl.getFont().deriveFont(Font.PLAIN));
    cardInclude.add(lblIncl, GBC.eol().fill(GBC.HORIZONTAL));

    final CardLayout cl = new CardLayout();
    final JPanel cards = new JPanel(cl);
    cards.add(cardLink, "link");
    cards.add(cardInclude, "include");

    if (file != null) {
      link.setSelected(true);
    } else {
      link.setEnabled(false);
      link.setToolTipText(tr("No file association"));
      include.setSelected(true);
      cl.show(cards, "include");
    }

    link.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            cl.show(cards, "link");
          }
        });
    include.addActionListener(
        new ActionListener() {
          public void actionPerformed(ActionEvent e) {
            cl.show(cards, "include");
          }
        });

    topRow.add(export, GBC.std());
    topRow.add(lbl, GBC.std());
    topRow.add(GBC.glue(1, 0), GBC.std().fill(GBC.HORIZONTAL));
    p.add(topRow, GBC.eol().fill(GBC.HORIZONTAL));
    p.add(lblData, GBC.std().insets(10, 0, 0, 0));
    p.add(link, GBC.std());
    p.add(include, GBC.eol());
    p.add(cards, GBC.eol().insets(15, 0, 3, 3));

    export.addItemListener(
        new ItemListener() {
          public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.DESELECTED) {
              GuiHelper.setEnabledRec(p, false);
              export.setEnabled(true);
            } else {
              GuiHelper.setEnabledRec(p, true);
              save.setEnabled(saveAction.isEnabled());
              link.setEnabled(file != null);
            }
          }
        });
    return p;
  }