Esempio n. 1
0
  private void onActiveLayerChanged(final Layer old) {
    fireActiveLayerChanged(old, activeLayer);

    /* This only makes the buttons look disabled. Disabling the actions as well requires
     * the user to re-select the tool after i.e. moving a layer. While testing I found
     * that I switch layers and actions at the same time and it was annoying to mind the
     * order. This way it works as visual clue for new users */
    for (final AbstractButton b : Main.map.allMapModeButtons) {
      MapMode mode = (MapMode) b.getAction();
      final boolean activeLayerSupported = mode.layerIsSupported(activeLayer);
      if (activeLayerSupported) {
        Main.registerActionShortcut(mode, mode.getShortcut()); // fix #6876
      } else {
        Main.unregisterShortcut(mode.getShortcut());
      }
      GuiHelper.runInEDTAndWait(
          new Runnable() {
            @Override
            public void run() {
              b.setEnabled(activeLayerSupported);
            }
          });
    }
    AudioPlayer.reset();
    repaint();
  }
 /**
  * Returns the list of recent relations on active layer.
  *
  * @return the list of recent relations on active layer
  */
 public static List<Relation> getRecentRelationsOnActiveLayer() {
   if (!Main.isDisplayingMapView()) return Collections.emptyList();
   Layer activeLayer = Main.getLayerManager().getActiveLayer();
   if (!(activeLayer instanceof OsmDataLayer)) {
     return Collections.emptyList();
   } else {
     return ((OsmDataLayer) activeLayer).getRecentRelations();
   }
 }
Esempio n. 3
0
    protected void uploadLayers(List<SaveLayerInfo> toUpload) {
      for (final SaveLayerInfo layerInfo : toUpload) {
        AbstractModifiableLayer layer = layerInfo.getLayer();
        if (canceled) {
          model.setUploadState(layer, UploadOrSaveState.CANCELED);
          continue;
        }
        monitor.subTask(tr("Preparing layer ''{0}'' for upload ...", layerInfo.getName()));

        if (!UploadAction.checkPreUploadConditions(layer)) {
          model.setUploadState(layer, UploadOrSaveState.FAILED);
          continue;
        }

        AbstractUploadDialog dialog = layer.getUploadDialog();
        if (dialog != null) {
          dialog.setVisible(true);
          if (dialog.isCanceled()) {
            model.setUploadState(layer, UploadOrSaveState.CANCELED);
            continue;
          }
          dialog.rememberUserInput();
        }

        currentTask = layer.createUploadTask(monitor);
        if (currentTask == null) {
          model.setUploadState(layer, UploadOrSaveState.FAILED);
          continue;
        }
        currentFuture = worker.submit(currentTask);
        try {
          // wait for the asynchronous task to complete
          //
          currentFuture.get();
        } catch (CancellationException e) {
          Main.trace(e);
          model.setUploadState(layer, UploadOrSaveState.CANCELED);
        } catch (InterruptedException | ExecutionException e) {
          Main.error(e);
          model.setUploadState(layer, UploadOrSaveState.FAILED);
          ExceptionDialogUtil.explainException(e);
        }
        if (currentTask.isCanceled()) {
          model.setUploadState(layer, UploadOrSaveState.CANCELED);
        } else if (currentTask.isFailed()) {
          Main.error(currentTask.getLastException());
          ExceptionDialogUtil.explainException(currentTask.getLastException());
          model.setUploadState(layer, UploadOrSaveState.FAILED);
        } else {
          model.setUploadState(layer, UploadOrSaveState.OK);
        }
        currentTask = null;
        currentFuture = null;
      }
    }
Esempio n. 4
0
 /** Unit test of {@link WMSLayer#WMSLayer}. */
 @Test
 public void testWMSLayer() {
   WMSLayer wms = new WMSLayer(new ImageryInfo("test wms", "http://localhost"));
   Main.getLayerManager().addLayer(wms);
   try {
     assertEquals(ImageryType.WMS, wms.getInfo().getImageryType());
   } finally {
     // Ensure we clean the place before leaving, even if test fails.
     Main.getLayerManager().removeLayer(wms);
   }
 }
Esempio n. 5
0
 /** Lets other commands access the original version of the object. Usually for undoing. */
 public PrimitiveData getOrig(OsmPrimitive osm) {
   PrimitiveData o = cloneMap.get(osm);
   if (o != null) return o;
   Main.debug("unable to find osm with id: " + osm.getId() + " hashCode: " + osm.hashCode());
   for (OsmPrimitive t : cloneMap.keySet()) {
     PrimitiveData to = cloneMap.get(t);
     Main.debug("now: " + t.getId() + " hashCode: " + t.hashCode());
     Main.debug("orig: " + to.getUniqueId() + " hashCode: " + to.hashCode());
   }
   return o;
 }
  public void selectFeatures(int x, int y) {
    int pixelDelta = 2;
    LatLon clickUL = Main.map.mapView.getLatLon(x - pixelDelta, y - pixelDelta);
    LatLon clickLR = Main.map.mapView.getLatLon(x + pixelDelta, y + pixelDelta);

    Envelope envelope =
        new Envelope(
            Math.min(clickUL.lon(), clickLR.lon()),
            Math.max(clickUL.lon(), clickLR.lon()),
            Math.min(clickUL.lat(), clickLR.lat()),
            Math.max(clickUL.lat(), clickLR.lat()));

    ReferencedEnvelope mapArea = new ReferencedEnvelope(envelope, crsOSMI);

    Intersects filter = ff.intersects(ff.property("msGeometry"), ff.literal(mapArea));
    //
    // Select features in all layers
    //
    content.layers().clear();

    // Iterate through features and build a list that intersects the above
    // envelope
    for (int idx = 0; idx < arrFeatures.size(); ++idx) {
      OSMIFeatureTracker tracker = arrFeatures.get(idx);
      FeatureCollection<SimpleFeatureType, SimpleFeature> features = tracker.getFeatures();

      SimpleFeatureSource tempfs = DataUtilities.source(features);
      FeatureCollection<SimpleFeatureType, SimpleFeature> selectedFeatures;

      try {
        selectedFeatures = tempfs.getFeatures(filter);
        Set<FeatureId> IDs = new HashSet<>();

        try (FeatureIterator<SimpleFeature> iter = selectedFeatures.features()) {

          Main.info("Selected features " + selectedFeatures.size());

          while (iter.hasNext()) {
            SimpleFeature feature = iter.next();
            IDs.add(feature.getIdentifier());
          }
        }

        geometryType = selectGeomType.get(idx + layerOffset);
        Style style = createDefaultStyle(idx + layerOffset, IDs);
        content.addLayer(new FeatureLayer(features, style));
      } catch (IOException e) {
        Main.error(e);
      }
    }

    bIsChanged = true;
  }
Esempio n. 7
0
  @Test
  public void a_latlon2eastNorth_test() {
    {
      LatLon ll = new LatLon(46.518, 6.567);
      EastNorth en = Main.getProjection().latlon2eastNorth(ll);
      if (debug) {
        System.out.println(en);
      }
      assertTrue("Lausanne", Math.abs(en.east() - 533111.69) < 0.1);
      assertTrue("Lausanne", Math.abs(en.north() - 152227.85) < 0.1);
    }

    {
      LatLon ll = new LatLon(47.78, 8.58);
      EastNorth en = Main.getProjection().latlon2eastNorth(ll);
      if (debug) {
        System.out.println(en);
      }
      assertTrue("Schafouse", Math.abs(en.east() - 685544.16) < 0.1);
      assertTrue("Schafouse", Math.abs(en.north() - 292782.91) < 0.1);
    }

    {
      LatLon ll = new LatLon(46.58, 10.48);
      EastNorth en = Main.getProjection().latlon2eastNorth(ll);
      if (debug) {
        System.out.println(en);
      }
      assertTrue("Grinson", Math.abs(en.east() - 833068.04) < 0.1);
      assertTrue("Grinson", Math.abs(en.north() - 163265.39) < 0.1);
    }

    {
      LatLon ll =
          new LatLon(
              46.0 + 57.0 / 60 + 3.89813884505 / 3600, 7.0 + 26.0 / 60 + 19.076595154147 / 3600);
      EastNorth en = Main.getProjection().latlon2eastNorth(ll);
      if (debug) {
        System.out.println(en);
      }
      assertTrue("Berne", Math.abs(en.east() - 600000.0) < 0.1);
      assertTrue("Berne", Math.abs(en.north() - 200000.0) < 0.1);
    }
    {
      LatLon ll = new LatLon(46.0 + 2.0 / 60 + 38.87 / 3600, 8.0 + 43.0 / 60 + 49.79 / 3600);
      EastNorth en = Main.getProjection().latlon2eastNorth(ll);
      if (debug) {
        System.out.println(en);
      }
      assertTrue("Ref", Math.abs(en.east() - 700000.0) < 0.1);
      assertTrue("Ref", Math.abs(en.north() - 100000.0) < 0.1);
    }
  }
Esempio n. 8
0
  @Test
  public void b_eastNorth2latlon_test() {
    {
      EastNorth en = new EastNorth(533111.69, 152227.85);
      LatLon ll = Main.getProjection().eastNorth2latlon(en);
      if (debug) {
        System.out.println(ll);
      }
      assertTrue("Lausanne", Math.abs(ll.lat() - 46.518) < 0.00001);
      assertTrue("Lausanne", Math.abs(ll.lon() - 6.567) < 0.00001);
    }

    {
      EastNorth en = new EastNorth(685544.16, 292782.91);
      LatLon ll = Main.getProjection().eastNorth2latlon(en);
      if (debug) {
        System.out.println(ll);
      }
      assertTrue("Schafouse", Math.abs(ll.lat() - 47.78) < 0.00001);
      assertTrue("Schafouse", Math.abs(ll.lon() - 8.58) < 0.00001);
    }

    {
      EastNorth en = new EastNorth(833068.04, 163265.39);
      LatLon ll = Main.getProjection().eastNorth2latlon(en);
      if (debug) {
        System.out.println(ll);
      }
      assertTrue("Grinson", Math.abs(ll.lat() - 46.58) < 0.00001);
      assertTrue("Grinson", Math.abs(ll.lon() - 10.48) < 0.00001);
    }

    {
      EastNorth en = new EastNorth(600000.0, 200000.0);
      LatLon ll = Main.getProjection().eastNorth2latlon(en);
      if (debug) {
        System.out.println(ll);
      }
      assertTrue("Berne", Math.abs(ll.lat() - (46.0 + 57.0 / 60 + 3.89813884505 / 3600)) < 0.00001);
      assertTrue(
          "Berne", Math.abs(ll.lon() - (7.0 + 26.0 / 60 + 19.076595154147 / 3600)) < 0.00001);
    }

    {
      EastNorth en = new EastNorth(700000.0, 100000.0);
      LatLon ll = Main.getProjection().eastNorth2latlon(en);
      if (debug) {
        System.out.println(ll);
      }
      assertTrue("Ref", Math.abs(ll.lat() - (46.0 + 2.0 / 60 + 38.87 / 3600)) < 0.00001);
      assertTrue("Ref", Math.abs(ll.lon() - (8.0 + 43.0 / 60 + 49.79 / 3600)) < 0.00001);
    }
  }
Esempio n. 9
0
 private static Class<?> loadRendererClass(String className) {
   for (ClassLoader cl : PluginHandler.getResourceClassLoaders()) {
     try {
       return Class.forName(className, true, cl);
     } catch (final NoClassDefFoundError | ClassNotFoundException e) {
       Main.trace(e.getMessage());
     }
   }
   Main.error(
       tr("Failed to load map renderer class ''{0}''. The class wasn''t found.", className));
   return null;
 }
Esempio n. 10
0
  private JButton addButtonAndShortcut(ActionDefinition action) {
    Action act = action.getParametrizedAction();
    JButton b = control.add(act);

    Shortcut sc = null;
    if (action.getAction() instanceof JosmAction) {
      sc = ((JosmAction) action.getAction()).getShortcut();
      if (sc.getAssignedKey() == KeyEvent.CHAR_UNDEFINED) {
        sc = null;
      }
    }

    long paramCode = 0;
    if (action.hasParameters()) {
      paramCode = action.parameters.hashCode();
    }

    String tt = action.getDisplayTooltip();
    if (tt == null) {
      tt = "";
    }

    if (sc == null || paramCode != 0) {
      String name = (String) action.getAction().getValue("toolbar");
      if (name == null) {
        name = action.getDisplayName();
      }
      if (paramCode != 0) {
        name = name + paramCode;
      }
      String desc =
          action.getDisplayName() + ((paramCode == 0) ? "" : action.parameters.toString());
      sc =
          Shortcut.registerShortcut(
              "toolbar:" + name, tr("Toolbar: {0}", desc), KeyEvent.CHAR_UNDEFINED, Shortcut.NONE);
      Main.unregisterShortcut(sc);
      Main.registerActionShortcut(act, sc);

      // add shortcut info to the tooltip if needed
      if (sc.getAssignedUser()) {
        if (tt.startsWith("<html>") && tt.endsWith("</html>")) {
          tt = tt.substring(6, tt.length() - 6);
        }
        tt = Main.platform.makeTooltip(tt, sc);
      }
    }

    if (!tt.isEmpty()) {
      b.setToolTipText(tt);
    }
    return b;
  }
Esempio n. 11
0
 /** Detect starting elements. */
 @Override
 public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
     throws SAXException {
   depth++;
   try {
     if ("searchresults".equals(qName)) {
       // do nothing
     } else if ("named".equals(qName) && (depth == 2)) {
       currentResult = new PlaceSelection.SearchResult();
       currentResult.name = atts.getValue("name");
       currentResult.info = atts.getValue("info");
       if (currentResult.info != null) {
         currentResult.info = tr(currentResult.info);
       }
       currentResult.lat = Double.parseDouble(atts.getValue("lat"));
       currentResult.lon = Double.parseDouble(atts.getValue("lon"));
       currentResult.zoom = Integer.parseInt(atts.getValue("zoom"));
       data.add(currentResult);
     } else if ("description".equals(qName) && (depth == 3)) {
       description = new StringBuilder();
     } else if ("named".equals(qName) && (depth == 4)) {
       // this is a "named" place in the nearest places list.
       String info = atts.getValue("info");
       if ("city".equals(info) || "town".equals(info) || "village".equals(info)) {
         currentResult.nearestPlace = atts.getValue("name");
       }
     } else if ("place".equals(qName) && atts.getValue("lat") != null) {
       currentResult = new PlaceSelection.SearchResult();
       currentResult.name = atts.getValue("display_name");
       currentResult.description = currentResult.name;
       currentResult.info = atts.getValue("class");
       if (currentResult.info != null) {
         currentResult.info = tr(currentResult.info);
       }
       currentResult.nearestPlace = tr(atts.getValue("type"));
       currentResult.lat = Double.parseDouble(atts.getValue("lat"));
       currentResult.lon = Double.parseDouble(atts.getValue("lon"));
       String[] bbox = atts.getValue("boundingbox").split(",");
       currentResult.bounds =
           new Bounds(
               Double.parseDouble(bbox[0]), Double.parseDouble(bbox[2]),
               Double.parseDouble(bbox[1]), Double.parseDouble(bbox[3]));
       data.add(currentResult);
     }
   } catch (NumberFormatException x) {
     Main.error(x); // SAXException does not chain correctly
     throw new SAXException(x.getMessage(), x);
   } catch (NullPointerException x) {
     Main.error(x); // SAXException does not chain correctly
     throw new SAXException(tr("Null pointer exception, possibly some missing tags."), x);
   }
 }
Esempio n. 12
0
 /**
  * Adds the specified GPX and marker layers to Map.main
  *
  * @param data The layers to add
  * @see #loadLayers
  */
 public static void addLayers(final GpxImporterData data) {
   // FIXME: remove UI stuff from the IO subsystem
   GuiHelper.runInEDT(
       () -> {
         if (data.markerLayer != null) {
           Main.getLayerManager().addLayer(data.markerLayer);
         }
         if (data.gpxLayer != null) {
           Main.getLayerManager().addLayer(data.gpxLayer);
         }
         data.postLayerTask.run();
       });
 }
  /**
   * @param wfsClient
   * @throws NoSuchAuthorityCodeException
   * @throws FactoryException
   * @throws IOException
   * @throws IndexOutOfBoundsException
   * @throws ParseException
   */
  public OsmInspectorLayer(GeoFabrikWFSClient wfsClient, ProgressMonitor monitor)
      throws NoSuchAuthorityCodeException, FactoryException, IOException, IndexOutOfBoundsException,
          ParseException {
    super("OsmInspector");

    arrFeatures = new ArrayList<>();
    osmiBugInfo = new LinkedHashMap<>();
    selectGeomType = new ArrayList<>();

    // Step 3 - discovery; enhance to iterate over all types with bounds

    String typeNames[] = wfsClient.getTypeNames();
    renderer = new StreamingRenderer();
    CRS.decode(Main.getProjection().toCode());
    crsOSMI = CRS.decode("EPSG:4326");
    content = new MapContent(crsOSMI);

    selectGeomType.add(GeomType.POINT);
    for (int idx = 1; idx < typeNames.length; ++idx) {
      String typeName = typeNames[idx];
      Set<FeatureId> selectedFeatures = new HashSet<>();

      FeatureCollection<SimpleFeatureType, SimpleFeature> features =
          wfsClient.getFeatures(typeName, monitor);
      setGeometry(selectGeomType, typeName);

      Main.info("Osm Inspector Features size: " + features.size());
      Style style = createDefaultStyle(idx, selectedFeatures);

      OSMIFeatureTracker tracker = new OSMIFeatureTracker(features);
      arrFeatures.add(tracker);
      FeatureIterator<SimpleFeature> it = tracker.getFeatures().features();

      while (it.hasNext()) {
        BugInfo theInfo = new BugInfo(it.next(), osmiBugInfo.size());
        osmiBugInfo.put(theInfo, theInfo.bugId);
      }

      content.addLayer(new FeatureLayer(tracker.getFeatures(), style));
    }

    osmiIndex = new BugIndex(osmiBugInfo);
    content.setTitle("Osm Inspector Errors");
    renderer.setMapContent(content);
    bIsChanged = true;

    // finally initialize the dialog
    dialog = new OsmInspectorDialog(this);
    this.updateView();
  }
 @Override
 public synchronized void loadingFinished(
     CacheEntry data, CacheEntryAttributes attributes, LoadResult result) {
   try {
     synchronized (this.getClass()) {
       this.queue.put(ImageIO.read(new ByteArrayInputStream(data.getContent())));
       this.queueImages.put(this.image);
     }
   } catch (InterruptedException e) {
     Main.error(e);
   } catch (IOException e) {
     Main.error(e);
   }
 }
  /**
   * find which gpx layer holds the trace to upload. layers are tried in this order:
   *
   * <p>1. selected (*not* active - think "zoom to layer"), from first to last 2. not selectd - if
   * there is only one 3. active
   *
   * @return data of the selected gpx layer, or null if there is none
   */
  GpxData autoSelectTrace() {
    if (Main.map != null && Main.map.mapView != null) {
      MainLayerManager lm = Main.getLayerManager();
      //            List<Layer> allLayers = new ArrayList<Layer>(mv.getAllLayersAsList());  //
      // modifiable
      List<Layer> selectedLayers = LayerListDialog.getInstance().getModel().getSelectedLayers();
      List<GpxLayer> gpxLayersRemaining = lm.getLayersOfType(GpxLayer.class);
      gpxLayersRemaining.removeAll(selectedLayers);
      GpxLayer traceLayer = null;
      // find the first gpx layer inside selected layers
      for (Layer l : LayerListDialog.getInstance().getModel().getSelectedLayers()) {
        if (l instanceof GpxLayer) {
          traceLayer = (GpxLayer) l;
          break;
        }
      }
      if (traceLayer == null) {
        // if there is none, try the none selected gpx layers. if there is only one, use it.
        if (gpxLayersRemaining.size() == 1) {
          traceLayer = gpxLayersRemaining.get(0);
        }
        // active layer
        else if (lm.getActiveLayer() instanceof GpxLayer) {
          traceLayer = (GpxLayer) lm.getActiveLayer();
        }
      }

      if (traceLayer != null) {
        return traceLayer.data;
      }
    }

    return null;
  }
Esempio n. 16
0
  /**
   * This function handles all work related to updating the cursor and highlights
   *
   * @param e
   * @param modifiers
   */
  private void updateCursor(MouseEvent e, int modifiers) {
    if (!Main.isDisplayingMapView()) return;
    if (!Main.map.mapView.isActiveLayerVisible() || e == null) return;

    DeleteParameters parameters = getDeleteParameters(e, modifiers);
    Main.map.mapView.setNewCursor(parameters.mode.cursor(), this);
  }
Esempio n. 17
0
  private static Map<String, Integer> getCacheStats(
      CacheAccess<String, BufferedImageCacheEntry> cache) {
    Set<String> keySet = cache.getCacheControl().getKeySet();
    Map<String, int[]> temp =
        new ConcurrentHashMap<>(); // use int[] as a Object reference to int, gives better
                                   // performance
    for (String key : keySet) {
      String[] keyParts = key.split(":", 2);
      if (keyParts.length == 2) {
        int[] counter = temp.get(keyParts[0]);
        if (counter == null) {
          temp.put(keyParts[0], new int[] {1});
        } else {
          counter[0]++;
        }
      } else {
        Main.warn("Could not parse the key: {0}. No colon found", key);
      }
    }

    // convert to standard Map<String, Integer>
    Map<String, Integer> ret = new ConcurrentHashMap<>();
    for (Entry<String, int[]> e : temp.entrySet()) {
      ret.put(e.getKey(), e.getValue()[0]);
    }
    return ret;
  }
Esempio n. 18
0
    @Override
    protected void parse(HeaderBlock header) {

      for (String requiredFeature : header.getRequiredFeaturesList()) {
        switch (requiredFeature) {
          case "OsmSchema-V0.6":
            ds.setVersion("0.6");
            break;
          case "DenseNodes":
            break;
          default:
            throw new UnsupportedOperationException("Unsupported feature: " + requiredFeature);
        }
      }

      HeaderBBox bbox = header.getBbox();
      if (bbox != null) {
        double minlat = parseRawDegrees(bbox.getBottom());
        double minlon = parseRawDegrees(bbox.getLeft());
        double maxlat = parseRawDegrees(bbox.getTop());
        double maxlon = parseRawDegrees(bbox.getRight());
        Bounds b = new Bounds(minlat, minlon, maxlat, maxlon);
        if (!b.isCollapsed() && areCoordinatesValid(minlat, minlon, maxlat, maxlon)) {
          ds.dataSources.add(new DataSource(b, header.getSource()));
        } else {
          Main.error("Invalid Bounds: " + b);
        }
      }
    }
Esempio n. 19
0
  /** Unit test of method {@link ChangesetDataSet#getPrimitivesByModificationType}. */
  @Test
  public void testGetPrimitivesByModificationType() {
    final ChangesetDataSet cds = new ChangesetDataSet();
    // empty object, null parameter => IllegalArgumentException
    try {
      cds.getPrimitivesByModificationType(null);
      Assert.fail("Should have thrown an IllegalArgumentException as we gave a null argument.");
    } catch (IllegalArgumentException e) {
      Main.trace(e);
      // Was expected
    }

    // empty object, a modification type => empty list
    Assert.assertTrue(
        "Empty data set should produce an empty list.",
        cds.getPrimitivesByModificationType(ChangesetModificationType.CREATED).isEmpty());

    // object with various items and modification types, fetch for CREATED
    // => list containing only the CREATED item
    HistoryOsmPrimitive prim1 =
        new HistoryNode(1, 1, true, User.getAnonymous(), 1, new Date(), LatLon.ZERO);
    HistoryOsmPrimitive prim2 =
        new HistoryNode(2, 1, true, User.createLocalUser("test"), 1, new Date(), LatLon.NORTH_POLE);
    HistoryOsmPrimitive prim3 =
        new HistoryNode(3, 1, true, User.getAnonymous(), 1, new Date(), LatLon.SOUTH_POLE);
    cds.put(prim1, ChangesetModificationType.CREATED);
    cds.put(prim2, ChangesetModificationType.DELETED);
    cds.put(prim3, ChangesetModificationType.UPDATED);
    Set<HistoryOsmPrimitive> result =
        cds.getPrimitivesByModificationType(ChangesetModificationType.CREATED);
    Assert.assertEquals("We should have found only one item.", 1, result.size());
    Assert.assertTrue("The item found is prim1.", result.contains(prim1));
  }
 /**
  * Constructs a new <code>RecentRelationsAction</code>.
  *
  * @param editButton edit button
  */
 public RecentRelationsAction(SideButton editButton) {
   this.editButton = editButton;
   arrow = editButton.createArrow(this);
   arrow.setToolTipText(tr("List of recent relations"));
   Main.main.undoRedo.addCommandQueueListener(this);
   Main.getLayerManager().addLayerChangeListener(this);
   Main.getLayerManager().addActiveLayerChangeListener(this);
   enableArrow();
   shortcut =
       Shortcut.registerShortcut(
           "relationeditor:editrecentrelation",
           tr("Relation Editor: {0}", tr("Open recent relation")),
           KeyEvent.VK_ESCAPE,
           Shortcut.SHIFT);
   Main.registerActionShortcut(new LaunchEditorAction(), shortcut);
 }
 @Override
 public void enterMode() {
   super.enterMode();
   if (!hasImageryLayersToAdjust()) {
     warnNoImageryLayers();
     return;
   }
   List<ImageryLayer> layers = Main.getLayerManager().getLayersOfType(ImageryLayer.class);
   if (layers.size() == 1) {
     adjustingLayer = layers.get(0);
   } else {
     adjustingLayer = (ImageryLayer) askAdjustLayer(getVisibleLayers());
   }
   if (adjustingLayer == null) return;
   if (!adjustingLayer.isVisible()) {
     adjustingLayer.setVisible(true);
   }
   Main.map.mapView.addMouseListener(this);
   Main.map.mapView.addMouseMotionListener(this);
   listener =
       new TimedKeyReleaseListener() {
         @Override
         protected void doKeyReleaseEvent(KeyEvent evt) {
           if (releaseEvent.getKeyCode() == getShortcut().getKeyStroke().getKeyCode()) {
             if (oldMapMode != null && !(oldMapMode instanceof ImageryAdjustMapMode))
               Main.map.selectMapMode(oldMapMode);
           }
         }
       };
 }
Esempio n. 22
0
 /**
  * Adds an edit layer change listener
  *
  * @param listener the listener. Ignored if null or already registered.
  * @param initialFire fire an edit-layer-changed-event right after adding the listener in case
  *     there is an edit layer present
  */
 public static void addEditLayerChangeListener(
     EditLayerChangeListener listener, boolean initialFire) {
   addEditLayerChangeListener(listener);
   if (initialFire && Main.isDisplayingMapView() && Main.map.mapView.getEditLayer() != null) {
     listener.editLayerChanged(null, Main.map.mapView.getEditLayer());
   }
 }
Esempio n. 23
0
 private synchronized void waitNotification() {
   try {
     wait();
   } catch (InterruptedException e) {
     Main.error(e);
   }
 }
Esempio n. 24
0
 @Override
 public void realRun() throws IOException, SAXException, OsmTransferException {
   try {
     if (isCanceled()) {
       return;
     }
     dataSet = parseDataSet();
   } catch (Exception e) {
     if (isCanceled()) {
       Main.info(
           tr(
               "Ignoring exception because download has been canceled. Exception was: {0}",
               e.toString()));
       return;
     }
     if (e instanceof OsmTransferCanceledException) {
       setCanceled(true);
       return;
     } else if (e instanceof OsmTransferException) {
       rememberException(e);
     } else {
       rememberException(new OsmTransferException(e));
     }
     DownloadOsmTask.this.setFailed(true);
   }
 }
Esempio n. 25
0
 /**
  * Retries to recover the upload operation from an exception which was thrown because an uploaded
  * primitive was already deleted on the server.
  *
  * @param e the exception throw by the API
  * @param monitor a progress monitor
  * @throws OsmTransferException if we can't recover from the exception
  */
 protected void recoverFromGoneOnServer(OsmApiPrimitiveGoneException e, ProgressMonitor monitor)
     throws OsmTransferException {
   if (!e.isKnownPrimitive()) throw e;
   OsmPrimitive p = layer.data.getPrimitiveById(e.getPrimitiveId(), e.getPrimitiveType());
   if (p == null) throw e;
   if (p.isDeleted()) {
     // we tried to delete an already deleted primitive.
     final String msg;
     final String displayName = p.getDisplayName(DefaultNameFormatter.getInstance());
     if (p instanceof Node) {
       msg = tr("Node ''{0}'' is already deleted. Skipping object in upload.", displayName);
     } else if (p instanceof Way) {
       msg = tr("Way ''{0}'' is already deleted. Skipping object in upload.", displayName);
     } else if (p instanceof Relation) {
       msg = tr("Relation ''{0}'' is already deleted. Skipping object in upload.", displayName);
     } else {
       msg = tr("Object ''{0}'' is already deleted. Skipping object in upload.", displayName);
     }
     monitor.appendLogMessage(msg);
     Main.warn(msg);
     processedPrimitives.addAll(writer.getProcessedPrimitives());
     processedPrimitives.add(p);
     toUpload.removeProcessed(processedPrimitives);
     return;
   }
   // exception was thrown because we tried to *update* an already deleted
   // primitive. We can't resolve this automatically. Re-throw exception,
   // a conflict is going to be created later.
   throw e;
 }
Esempio n. 26
0
 public static WindowGeometry mainWindow(String preferenceKey, String arg, boolean maximize) {
   Rectangle screenDimension = getScreenInfo("gui.geometry");
   if (arg != null) {
     final Matcher m = Pattern.compile("(\\d+)x(\\d+)(([+-])(\\d+)([+-])(\\d+))?").matcher(arg);
     if (m.matches()) {
       int w = Integer.valueOf(m.group(1));
       int h = Integer.valueOf(m.group(2));
       int x = screenDimension.x, y = screenDimension.y;
       if (m.group(3) != null) {
         x = Integer.valueOf(m.group(5));
         y = Integer.valueOf(m.group(7));
         if (m.group(4).equals("-")) {
           x = screenDimension.x + screenDimension.width - x - w;
         }
         if (m.group(6).equals("-")) {
           y = screenDimension.y + screenDimension.height - y - h;
         }
       }
       return new WindowGeometry(new Point(x, y), new Dimension(w, h));
     } else {
       Main.warn(tr("Ignoring malformed geometry: {0}", arg));
     }
   }
   WindowGeometry def;
   if (maximize) {
     def = new WindowGeometry(screenDimension);
   } else {
     Point p = screenDimension.getLocation();
     p.x += (screenDimension.width - 1000) / 2;
     p.y += (screenDimension.height - 740) / 2;
     def = new WindowGeometry(p, new Dimension(1000, 740));
   }
   return new WindowGeometry(preferenceKey, def);
 }
Esempio n. 27
0
  /**
   * Match a list of photos to a gpx track with a given offset. All images need a exifTime attribute
   * and the List must be sorted according to these times.
   *
   * @param images images to match
   * @param selectedGpx selected GPX data
   * @param offset offset
   * @return number of matched points
   */
  static int matchGpxTrack(List<ImageEntry> images, GpxData selectedGpx, long offset) {
    int ret = 0;

    for (GpxTrack trk : selectedGpx.tracks) {
      for (GpxTrackSegment segment : trk.getSegments()) {

        long prevWpTime = 0;
        WayPoint prevWp = null;

        for (WayPoint curWp : segment.getWayPoints()) {
          try {
            final Date parsedTime = curWp.setTimeFromAttribute();
            if (parsedTime != null) {
              final long curWpTime = parsedTime.getTime() + offset;
              ret += matchPoints(images, prevWp, prevWpTime, curWp, curWpTime, offset);

              prevWp = curWp;
              prevWpTime = curWpTime;
              continue;
            }
          } catch (Exception e) {
            Main.warn(e);
          }
          prevWp = null;
          prevWpTime = 0;
        }
      }
    }
    return ret;
  }
Esempio n. 28
0
  /**
   * Builds and displays the window to the user.
   *
   * @param currentSortMode - The current sort mode which will be pre-selected in the list
   */
  public void showSortDialog(Comparator<Note> currentSortMode) {
    JLabel label = new JLabel(tr("Select note sorting method"));
    if (currentSortMode == NoteData.DEFAULT_COMPARATOR) {
      defaultSort.setSelected(true);
    } else if (currentSortMode == NoteData.DATE_COMPARATOR) {
      dateSort.setSelected(true);
    } else if (currentSortMode == NoteData.USER_COMPARATOR) {
      userSort.setSelected(true);
    } else if (currentSortMode == NoteData.LAST_ACTION_COMPARATOR) {
      lastActionSort.setSelected(true);
    } else {
      Main.warn("sort mode not recognized");
    }

    ButtonGroup bg = new ButtonGroup();
    bg.add(defaultSort);
    bg.add(userSort);
    bg.add(dateSort);
    bg.add(lastActionSort);

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
    panel.add(label);
    panel.add(defaultSort);
    panel.add(userSort);
    panel.add(dateSort);
    panel.add(lastActionSort);

    setContent(panel);

    showDialog();
  }
 /** Gets the elevation profile layer which decorates the current layer with some markers. */
 public static ElevationProfileLayer getCurrentLayer() {
   if (currentLayer == null) {
     currentLayer = new ElevationProfileLayer(tr("Elevation Profile"));
     Main.getLayerManager().addLayer(currentLayer);
   }
   return currentLayer;
 }
 protected Relation createRouteMaster(LineType line) {
   Relation r = createPtRelation(OSM_ROUTE_MASTER, line);
   switch (line.getTransportModeName()) {
     case BUS:
       r.put(OSM_ROUTE_MASTER, OSM_BUS);
       break;
     case AIR:
       r.put(OSM_ROUTE_MASTER, OSM_AERIALWAY);
       break;
     case FERRY:
       r.put(OSM_ROUTE_MASTER, OSM_FERRY);
       break;
     case METRO:
       r.put(OSM_ROUTE_MASTER, OSM_SUBWAY);
       break;
     case TRAIN:
       r.put(OSM_ROUTE_MASTER, OSM_TRAIN);
       break;
     case TRAMWAY:
       r.put(OSM_ROUTE_MASTER, OSM_TRAM);
       break;
     case TROLLEYBUS:
       r.put(OSM_ROUTE_MASTER, OSM_TROLLEYBUS);
       break;
     default:
       Main.warn("Unsupported transport mode: " + line.getTransportModeName());
   }
   r.put("ref", line.getNumber());
   r.put(
       "name",
       line.getTransportModeName().value() + " " + line.getNumber() + ": " + line.getName());
   return r;
 }