@Override
 public CoordinateReferenceSystem getCrs() {
   ILayer processingRegionMapGraphic = OmsBoxPlugin.getDefault().getProcessingRegionMapGraphic();
   if (processingRegionMapGraphic != null) {
     processingRegionMapGraphic.getCRS();
   }
   return null;
 }
  /**
   * This example shows how to obtain a color.
   *
   * @param g
   * @param monitor
   * @throws RenderException
   */
  public void render(Graphics2D g, IProgressMonitor monitor) throws RenderException {
    if (monitor == null) monitor = new NullProgressMonitor();

    CsvReader reader = null;
    try {
      ILayer layer = getContext().getLayer();
      IGeoResource resource = layer.findGeoResource(CSV.class);
      if (resource == null) return;
      ReferencedEnvelope bounds = getRenderBounds();
      monitor.subTask("connecting");
      CSV csv = resource.resolve(CSV.class, null);
      // LOOK UP STYLE
      IStyleBlackboard style = layer.getStyleBlackboard();
      Color color = (Color) style.get(ColorStyle.ID);

      // DATA TO WORLD
      CoordinateReferenceSystem dataCRS = layer.getCRS();
      CoordinateReferenceSystem worldCRS = context.getCRS();
      MathTransform dataToWorld = CRS.findMathTransform(dataCRS, worldCRS, false);

      // DRAW FILE
      monitor.beginTask("csv render", csv.getSize());
      reader = csv.reader();
      reader.readHeaders();
      int nameIndex = reader.getIndex("name");
      Coordinate worldLocation = new Coordinate();
      while (reader.readRecord()) {
        Point point = CSV.getPoint(reader);
        Coordinate dataLocation = point.getCoordinate();
        try {
          JTS.transform(dataLocation, worldLocation, dataToWorld);
        } catch (TransformException e) {
          continue;
        }
        if (bounds != null && !bounds.contains(worldLocation)) {
          continue; // optimize!
        }
        java.awt.Point p = getContext().worldToPixel(worldLocation);

        g.setColor(color);
        g.fillRect(p.x - 2, p.y - 2, 6, 6);

        g.setColor(Color.BLACK);
        String name = reader.get(nameIndex);
        g.drawString(name, p.x + 15, p.y + 15);
        monitor.worked(1);
        if (monitor.isCanceled()) break;
      }
    } catch (IOException e) {
      throw new RenderException(e); // rethrow any exceptions encountered
    } catch (FactoryException e) {
      throw new RenderException(e); // rethrow any exceptions encountered
    } finally {
      if (reader != null) reader.close();
      monitor.done();
    }
  }
 private boolean mismatch(ILayer graticule, GraticuleStyle style) {
   String code;
   try {
     code = "EPSG:" + CRS.lookupEpsgCode(graticule.getCRS(), false); // $NON-NLS-1$
     return !code.equals(style.getCRS());
   } catch (FactoryException ex) {
     MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
   }
   return true;
 }
  private MathTransform createMathTransform(ILayer sourceLayer, ILayer targetLayer) {
    MathTransform temp;
    try {
      CoordinateReferenceSystem targetCRS = targetLayer.getCRS();
      CoordinateReferenceSystem sourceCRS = sourceLayer.getCRS();
      if (targetCRS.equals(sourceCRS)) temp = null;
      else temp = CRS.findMathTransform(sourceCRS, targetCRS, true);
      if (temp == null || temp.isIdentity()) temp = null;
    } catch (FactoryException e1) {
      ProjectPlugin.log("", e1); // $NON-NLS-1$
      temp = null;
    }

    if (temp == null) {
      try {
        return CRS.findMathTransform(DefaultGeographicCRS.WGS84, DefaultGeographicCRS.WGS84);
      } catch (Exception e) {
        ProjectPlugin.log("", e); // $NON-NLS-1$
        return null;
      }
    }
    return temp;
  }
  public void run(IProgressMonitor monitor) throws Exception {

    final ILayer editLayer = handler.getEditLayer();
    final Point mouseLocation = position;

    final EditBlackboard layerBlackboard = handler.getEditBlackboard(editLayer);
    final boolean includeSegmentsInCurrent = true;
    final SnapBehaviour snapBehaviour = SnapBehaviour.CURRENT_LAYER;

    final CoordinateReferenceSystem mapCrs = handler.getContext().getCRS();
    final int snappingRadius = PreferenceUtil.instance().getSnappingRadius();

    final SnapSegmentFinder segmentFinder = new SnapSegmentFinder(mapCrs);
    List<LineSegment> linesList = new ArrayList<LineSegment>();
    LineSegment closestSnapSegment;
    closestSnapSegment =
        segmentFinder.getClosestSnapSegment(
            handler,
            layerBlackboard,
            mouseLocation,
            includeSegmentsInCurrent,
            snapBehaviour,
            snappingRadius);

    if (closestSnapSegment != null) {
      CoordinateReferenceSystem layerCrs = editLayer.getCRS();
      closestSnapSegment = GeoToolsUtils.reproject(closestSnapSegment, mapCrs, layerCrs);
    }
    linesList.add(closestSnapSegment);
    if (this.mapMouseEvent.isShiftDown()) {
      this.segmentCopyContext.addSegments(linesList);
    } else {
      this.segmentCopyContext.setReferenceLineSegment(closestSnapSegment);
    }
    this.segmentCopyContext.setMode(PrecisionToolsMode.WAITING);

    System.out.println("\nSegment: " + closestSnapSegment.toString());
  }
  @Override
  public void draw(MapGraphicContext context) {

    // Initialize
    ILayer graticule = context.getLayer();
    GraticuleStyle style = GraticuleStyle.getStyle(graticule);

    // Ensure CRS?
    if (graticule instanceof Layer) {
      // Initialize CRS?
      if (style.isInitCRS()) {
        // Only initialize once
        style.setInitCRS(false);
        // Apply CRS from context
        GraticuleCRSConfigurator.apply((Layer) graticule, context.getCRS());
      } else if (mismatch(graticule, style)) {
        // Apply CRS from
        GraticuleCRSConfigurator.apply((Layer) graticule, style.getCRS());
      }
    }

    // Sanity checks
    if (MAX_SCALE < context.getMap().getViewportModel().getScaleDenominator()) {
      graticule.setStatus(ILayer.ERROR);
      graticule.setStatusMessage(Messages.GraticuleGraphic_Maximum_Scale + MAX_SCALE);
      return;
    }
    Unit<?> unit = CRSUtilities.getUnit(graticule.getCRS().getCoordinateSystem());
    if (!SI.METER.equals(unit)) {
      graticule.setStatus(ILayer.ERROR);
      graticule.setStatusMessage(Messages.GraticuleGraphic_Illegal_CRS);
      return;
    }
    final IWorkbench workbench = PlatformUI.getWorkbench();
    if (workbench == null) return;

    // Start working on layer
    graticule.setStatus(ILayer.WORKING);
    graticule.setStatusMessage(null);

    // Get display to work on
    final Display display = workbench.getDisplay();

    // Set styles
    Font plain = GraticuleStyle.getFontStyle(context).getFont();
    Font bold = plain.deriveFont(Font.BOLD);

    // Initialize the graphics handle
    ViewportGraphics g = context.getGraphics();

    // Set font size
    g.setFont(bold);

    // Get bounds of viewport
    ReferencedEnvelope bounds = context.getViewportModel().getBounds();

    try {

      // Get square size limited to minimum size of 100 pixels
      double size = size(context, unit, 100);

      // Sanity check
      if (size < 100) return;

      // Convert square size to pixels
      int sx = (int) (size / context.getViewportModel().getPixelSize().x);
      int sy = (int) (size / context.getViewportModel().getPixelSize().y);

      // Make transform from Graticule to map CRS
      MathTransform transform = CRS.findMathTransform(graticule.getCRS(), context.getCRS(), false);

      // Transform bounds into Graticule CRS
      bounds = bounds.transform(graticule.getCRS(), true);

      // Get squares inside bounds
      SimpleFeatureIterator it = squares(bounds, size);

      // Draw one squares at the time (only top and left lines are drawn)
      while (it.hasNext()) {

        // Initialize states
        int i = 0;
        Point current = null;

        // Initialize lines
        List<Line> lines = new ArrayList<Line>(2);
        List<Label> labels = new ArrayList<Label>(2);

        // Get next geometry
        Geometry geom = (Geometry) it.next().getDefaultGeometry();

        // Get coordinates in graticule CRS
        Coordinate[] coords = geom.getCoordinates();

        // Get x-coordinate label from upper left corner
        String tx = getLabel(coords[0].x, size, unit, style);

        // Get y-coordinate label from lower left corner
        String ty = getLabel(coords[2].y, size, unit, style);

        // Insert gap with label?
        boolean vgap = isGap(tx, unit, style);
        boolean hgap = isGap(ty, unit, style);

        // Transform coordinates into Map CRS
        coords = JTS.transform(geom, transform).getCoordinates();

        // Create lines and labels for this square
        for (Coordinate c : coords) {

          // Build paths
          switch (i) {
            case 1:

              // -----------------------
              // Vertical line
              // -----------------------

              // Create line path
              current =
                  vert(
                      display,
                      g,
                      sy,
                      style.getLineWidth(),
                      current,
                      context.worldToPixel(c),
                      hgap,
                      vgap,
                      lines);

              // Add xx label?
              if (hgap) {
                labels.add(new Label(current, tx, vgap ? bold : plain));
                current = context.worldToPixel(c);
              }

              break;
            case 2:

              // -----------------------
              // Horizontal line
              // -----------------------

              // Create line path
              current =
                  horz(
                      display,
                      g,
                      sx,
                      style.getLineWidth(),
                      current,
                      context.worldToPixel(c),
                      vgap,
                      hgap,
                      lines);

              // Add yy label?
              if (vgap) {
                labels.add(new Label(current, ty, hgap ? bold : plain));
                current = context.worldToPixel(c);
              }

              break;

            default:
              current = context.worldToPixel(c);
              break;
          }
          i++;
        }

        // Draw lines
        for (Line line : lines) line.draw(g, style);

        // Draw labels?
        if (style.isShowLabels()) for (Label label : labels) label.draw(g, style);
      }

      // // Get lower left corner coordinates
      // int x = llc.x;
      // int y = llc.y;
      //
      // // Print borders
      // g.setColor(lc);
      // g.setStroke(ViewportGraphics.LINE_SOLID, 5);
      //
      // // Inner rectangle
      // g.drawRect(x + d + l, y + d + l, w - 2 * (d + l), h - 2 * (d + l));
      //
      // // Make white border
      // g.setColor(Color.WHITE);
      //
      // // Left
      // g.drawRect(x, y, d, h);
      // g.fillRect(x, y, d, h);
      //
      // // Bottom
      // g.drawRect(x, y, w, d);
      // g.fillRect(x, y, w, d);
      //
      // // Right
      // g.drawRect(x + w - d, y, d, h);
      // g.fillRect(x + w - d, y, d, h);
      //
      // // Top
      // g.drawRect(x, y + h - d, w, d);
      // g.fillRect(x, y + h - d, w, d);

    } catch (IOException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    } catch (FactoryException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    } catch (MismatchedDimensionException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    } catch (TransformException ex) {
      MapGraphicPlugin.log(Messages.GraticuleGraphic_Error, ex);
    }

    // Finished working on layer
    graticule.setStatus(ILayer.DONE);
  }