/**
   * Salva la tabla de color al fichero rmf.
   *
   * @param fName
   * @throws IOException
   */
  private void saveToRmf(String fileName) {
    RasterDataset rds = null;
    int limitNumberOfRequests = 20;
    while (rds == null && limitNumberOfRequests > 0) {
      try {
        rds = rasterSE.getDataSource().getDataset(0)[0];
      } catch (IndexOutOfBoundsException e) {
        // En ocasiones, sobre todo con servicios remotos al pedir un
        // datasource da una excepción de este tipo
        // se supone que es porque hay un refresco en el mismo momento
        // de la petición por lo que como es más lento de
        // gestionar pilla a la capa sin datasources asociados ya que
        // está reasignandolo. Si volvemos a pedirlo debe
        // haberlo cargado ya.
        try {
          Thread.sleep(200);
        } catch (InterruptedException e1) {
        }
      }
      limitNumberOfRequests--;
    }

    if (rds == null) {
      // RasterToolsUtil.messageBoxError("error_load_layer", this, new
      // Exception("Error writing RMF. limitNumberOfRequests=" +
      // limitNumberOfRequests));
      return;
    }

    RasterFilterList rasterFilterList = rasterSE.getRenderFilterList();

    // Guardamos en el RMF el valor NoData
    if (Configuration.getValue("nodata_transparency_enabled", Boolean.FALSE).booleanValue()) {
      try {
        RasterDataset.saveObjectToRmfFile(
            fileName,
            NoData.class,
            new NoData(
                rasterSE.getNoDataValue(), rasterSE.getNoDataType(), rasterSE.getDataType()[0]));
      } catch (RmfSerializerException e) {
        RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
      }
    }

    // Guardamos en el RMF la tabla de color
    ColorTableFilter colorTableFilter =
        (ColorTableFilter) rasterFilterList.getByName(ColorTableFilter.names[0]);
    if (colorTableFilter != null) {
      GridPalette gridPalette =
          new GridPalette((ColorTable) colorTableFilter.getColorTable().clone());
      try {
        RasterDataset.saveObjectToRmfFile(fileName, ColorTable.class, (ColorTable) gridPalette);
      } catch (RmfSerializerException e) {
        RasterToolsUtil.messageBoxError("error_salvando_rmf", this, e);
      }
    }
  }
Example #2
0
 /** Método de finalización del proceso. */
 private void tasseledCapFinalize(String fileName) {
   if (!new File(fileName).exists()) return;
   try {
     RasterToolsUtil.loadLayer(viewName, fileName, null);
   } catch (RasterNotLoadException e) {
     RasterToolsUtil.messageBoxError("error_load_layer", this, e);
   }
   if (externalActions != null) {
     externalActions.end(fileName);
   }
 }
  /**
   * Acciones que se realizan al finalizar de crear los recortes de imagen. Este método es llamado
   * por el thread TailRasterProcess al finalizar.
   */
  public void loadLayerInToc(String fileName) {
    if (!getFilterPanel().getNewLayerPanel().isNewLayerSelected()) return;
    if (!new File(fileName).exists()) return;
    try {
      RasterToolsUtil.loadLayer(getFilterPanel().getViewName(), fileName, null);
    } catch (RasterNotLoadException e) {
      RasterToolsUtil.messageBoxError("error_cargar_capa", this, e);
    }

    if (filterPanel != null) filterPanel.updateNewLayerText();
  }
Example #4
0
  /**
   * Obtiene la lista de parámetros de los filtros añadidos
   *
   * @param lyr Capa raster
   * @return ArrayList
   */
  public ArrayList getParamStruct(
      FLyrRasterSE lyr, StretchPreviewRender prevRender, StretchData data) {
    RasterFilterList filterList = new RasterFilterList();
    filterList.setInitDataType(lyr.getDataType()[0]);
    RasterFilterListManager filterManager = new RasterFilterListManager(filterList);

    try {
      prevRender.addPosterization(filterManager, lyr);
    } catch (FilterTypeException e1) {
      RasterToolsUtil.messageBoxError(RasterToolsUtil.getText(null, "noposterization"), null, e1);
    }

    return getParams(filterList);
  }
  /**
   * Método donde se ejecutará el Thread. Este hará las acciones globales para cualquier tarea y
   * llamará al método execute especifico de una tarea.
   */
  public void run() {
    long t1 = new java.util.Date().getTime();

    try {
      rasterTask = new RasterTask(this);
      RasterTaskQueue.register(rasterTask);
      execute();
    } catch (InterruptedException e) {
      if (externalActions != null) externalActions.interrupted();
      Thread.currentThread().interrupt();
    } catch (Exception e) {
      if (progressActive) {
        if (incrementableTask != null) {
          getIncrementableTask().processFinalize();
          incrementableTask = null;
        }
      }
      RasterToolsUtil.messageBoxError("error_processing", this, e);
      queueActions = null;
    } finally {
      RasterTaskQueue.remove(rasterTask);
      if (progressActive) {
        if (incrementableTask != null) getIncrementableTask().processFinalize();
      }
      if (queueActions != null) queueActions.end(this);
      time = new java.util.Date().getTime() - t1;
    }
  }
  /**
   * Acciones posibles cuando la proyección de la capa es distinta de la de la vista.
   *
   * @param action Valor de la acción. Está representado en RasterProjectionActionsPanel
   */
  private void layerActions(int action, FLyrRasterSE lyr) {
    // Cambia la proyección de la vista y carga la capa
    if (action == CHANGE_VIEW_PROJECTION) {
      if (lyr != null) {
        getMapControl().setCrs(lyr.readProjection());
        lyr.setVisible(true);
        getMapControl().getMapContext().getLayers().addLayer(lyr);
      }
    }

    // Ignora la proyección de la capa y la carga
    if (action == IGNORE) {
      if (lyr != null) {
        lyr.setVisible(true);
        getMapControl().getMapContext().getLayers().addLayer(lyr);
      }
    }

    // Reproyectando
    if (action == REPROJECT) {
      LayerReprojectPanel reprojectPanel =
          new LayerReprojectPanel((FLyrRasterSE) lyr, Boolean.FALSE);
      RasterToolsUtil.addWindow(reprojectPanel);
    }

    // No carga
    if (action == NOTLOAD) {}
  }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.gvsig.gui.beans.imagenavigator.IClientImageNavigator#drawImage(java
   * .awt.Graphics2D, double, double, double, double, double, int, int)
   */
  public void drawImage(IRasterRendering rendering) {
    rendering.getRenderFilterList().clear();

    if (getFilterPanel().getCBShowFilters().isSelected()) {
      RasterFilterList filterList = rendering.getRenderFilterList();
      RasterFilterListManager stackManager = new RasterFilterListManager(filterList);

      ArrayList listFilterUsed = applyFilters(rendering);
      ArrayList exc = new ArrayList();
      for (int i = 0; i < listFilterUsed.size(); i++) {
        IRasterFilterListManager filterManager =
            stackManager.getManagerByFilterClass(
                ((ParamStruct) listFilterUsed.get(i)).getFilterClass());
        try {
          filterManager.addFilter(
              ((ParamStruct) listFilterUsed.get(i)).getFilterClass(),
              ((ParamStruct) listFilterUsed.get(i)).getFilterParam());
        } catch (FilterTypeException e) {
          exc.add(e);
        }
      }
      if (exc.size() != 0) {
        RasterToolsUtil.messageBoxError(
            PluginServices.getText(this, "error_adding_filters"), this, exc);
        exc.clear();
      }
    }
  }
Example #8
0
 /**
  * Obtiene la barra deslizadora con el radio del filtro de paso alto
  *
  * @return CheckSliderTextContainer
  */
 public CheckSliderTextContainer getRadio() {
   if (radio == null)
     radio =
         new CheckSliderTextContainer(
             0, 255, 127, false, RasterToolsUtil.getText(this, "radio"), true, false, false);
   return radio;
 }
 /** Aplica las acciones */
 public void apply() {
   try {
     process.grayScaleProcess(previewRender, data);
   } catch (FilterTypeException e) {
     RasterToolsUtil.messageBoxError("error_filtering", null, e);
   }
   // refreshPreview();
 }
Example #10
0
  public void setBuffer() {

    IRasterDataSource dsetCopy = null;
    dsetCopy = rasterSE.getDataSource().newDataset();
    BufferFactory bufferFactory = new BufferFactory(dsetCopy);
    if (!RasterBuffer.loadInMemory(dsetCopy)) bufferFactory.setReadOnly(true);
    try {
      bufferFactory.setDrawableBands(this.bands);
      bufferFactory.setAreaOfInterest();
      buffer = bufferFactory.getRasterBuf();
    } catch (RasterDriverException e) {
      RasterToolsUtil.messageBoxError(
          PluginServices.getText(this, "raster_buffer_invalid_extension"), this, e);
    } catch (InterruptedException e) {
      RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_preview_stop"), this, e);
    }
  }
  /*
   * (non-Javadoc)
   *
   * @see org.gvsig.raster.gui.wizards.IFileOpen#execute(java.io.File[])
   */
  public Rectangle2D createLayer(File file, MapControl mapControl, CoordinateReferenceSystem crs) {
    this.mapControl = mapControl;
    FLyrRasterSE lyr = null;

    String layerName = RasterToolsUtil.getLayerNameFromFile(file);
    int nLayer = -1;

    // Si hay capas en la lista la buscamos allí
    if (lyrsRaster.size() != 0) {
      for (int i = 0; i < lyrsRaster.size(); i++) {
        if (((FLyrRasterSE) lyrsRaster.get(i)).getName().equals(layerName)) {
          lyr = (FLyrRasterSE) lyrsRaster.get(i);
          lyr.setCrs(crs);
          nLayer = i;
        }
      }
    }

    // Si no hay capa la cargamos
    if (lyr == null) {
      try {
        lyr = FLyrRasterSE.createLayer(layerName, file, crs);
        layerActions(defaultActionLayer, lyr);
      } catch (LoadLayerException e) {
        RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
      }
    }

    if (lyr != null) {
      boolean actionsAdded = false;
      if ((nLayer >= 0) && (nLayer < actionList.size())) {
        Object obj = actionList.get(nLayer);
        if (obj != null && obj instanceof Integer) {
          actionsAdded = true;
          layerActions(((Integer) obj).intValue(), lyr);
        }
      }
      if (!actionsAdded) layerActions(defaultActionLayer, lyr);
      return lyr.getFullExtent();
    }

    return null;
  }
  /**
   * Acciones que se realizan al finalizar de crear los recortes de imagen. Este método es llamado
   * por el thread TailRasterProcess al finalizar.
   */
  private void cutFinalize(String fileName, long milis) {
    if (!new File(fileName).exists()) return;

    if (viewName != null) {
      if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {

        try {
          FLayer lyr = RasterToolsUtil.loadLayer(viewName, fileName, null);
          if (lyr != null && lyr instanceof FLyrRasterSE)
            ((FLyrRasterSE) lyr).setRois(rasterSE.getRois());
        } catch (RasterNotLoadException e) {
          RasterToolsUtil.messageBoxError("error_load_layer", this, e);
        }
      }
    }

    if (showEndDialog && externalActions != null)
      externalActions.end(new Object[] {fileName, new Long(milis)});
  }
Example #13
0
  /**
   * Parámetros obligatorios al proceso:
   *
   * <UL>
   *   <LI>filename: Nombre del fichero de salida
   *   <LI>datawriter: Escritor de datos
   *   <LI>viewname: Nombre de la vista sobre la que se carga la capa al acabar el proceso
   *   <LI>layer: Capa de entrada para la transformación
   *   <LI>type: Tipo de transformación
   * </UL>
   */
  public void init() {
    // Se toman los parametros del proceso
    fileName = getStringParam("filename");
    writerBufferServer = (WriterBufferServer) getParam("datawriter");
    viewName = getStringParam("viewname");
    bands = (int[]) getParam("bands");
    rasterSE = getLayerParam("layer");
    type = getIntParam("type");

    // Obtenido el tipo se determina la matriz de coeficientes asociada
    switch (type) {
      case 0:
        matrixParams = LandSatMS;
        transformType = PluginServices.getText(this, "landsatMS");
        if (bands.length != 4) {
          this.incrementableTask.processFinalize();
          RasterToolsUtil.messageBoxError(PluginServices.getText(this, "transformMS_error"), this);
          exec = false;
        }
        break;
      case 1:
        matrixParams = LandSatTM;
        transformType = PluginServices.getText(this, "landsatTM");
        if (bands.length != 6) {
          this.incrementableTask.processFinalize();
          RasterToolsUtil.messageBoxError(PluginServices.getText(this, "transformTM_error"), this);
          exec = false;
        }
        break;
      case 2:
        matrixParams = LandSatETM;
        transformType = PluginServices.getText(this, "landsatETM");
        if (bands.length != 6) {
          this.incrementableTask.processFinalize();
          RasterToolsUtil.messageBoxError(PluginServices.getText(this, "transformETM_error"), this);
          exec = false;
        }
        break;
    }
    aTransform = rasterSE.getAffineTransform();
  }
Example #14
0
 /**
  * Obtiene el desplegable con la lista de capas
  *
  * @return JComboBox
  */
 protected NewLayerPanel getNewLayerPanel() {
   if (newLayerPanel == null) {
     newLayerPanel = new NewLayerPanel(lyr);
     newLayerPanel.setOnlyReprojectables(true);
     newLayerPanel
         .getJPanel()
         .setBorder(BorderFactory.createTitledBorder(RasterToolsUtil.getText(this, "capa")));
     newLayerPanel.getRadioOpenMemory().setEnabled(!isInTOC.booleanValue());
     if (isInTOC.booleanValue()) newLayerPanel.getRadioFileGenerate().setSelected(true);
   }
   return newLayerPanel;
 }
Example #15
0
 /*
  * (non-Javadoc)
  * @see org.gvsig.raster.IProcessActions#end(java.lang.Object)
  */
 public void end(Object param) {
   FLyrRasterSE grayConv = null;
   try {
     if (param instanceof String)
       grayConv =
           FLyrRasterSE.createLayer(
               RasterLibrary.getOnlyLayerName(), (String) param, sourceLayer.getProjection());
   } catch (LoadLayerException e) {
     RasterToolsUtil.messageBoxError("error_generating_layer", null, e);
   }
   if (endActions != null) endActions.end(new Object[] {this, grayConv});
 }
Example #16
0
  /**
   * Obtiene el panel de destino de fichero y nombre de capa
   *
   * @return JPanel
   */
  private JPanel getFilePanel() {
    if (filePanel == null) {
      filePanel = new JPanel();
      filePanel.setBorder(
          BorderFactory.createTitledBorder(RasterToolsUtil.getText(this, "dest_file")));
      filePanel.setLayout(new GridBagLayout());

      GridBagConstraints gbc = new GridBagConstraints();
      gbc.gridx = 0;
      gbc.gridy = 0;
      gbc.weightx = 1D;
      gbc.fill = GridBagConstraints.HORIZONTAL;
      gbc.anchor = GridBagConstraints.WEST;
      gbc.insets = new Insets(0, 0, 0, 5);
      filePanel.add(getNameFilePanel(), gbc);
    }
    return filePanel;
  }
Example #17
0
  /**
   * Función de pintado del canvas. Pintamos un marco a la imagen para saber donde la movemos.
   *
   * <p>Para dibujar el marco alrededor del raster hacemos lo mismo que para pintar el raster
   * rotado. En realidad dibujamos un cuadrado y luego le aplicamos las transformaciones necesarias
   * para que se vea con la misma forma del raster al que representa.
   */
  public void paintComponent(Graphics g) {
    if (isMoveable && lyr != null && ptoFin != null && ptoIni != null) {
      try {
        ViewPort vp = grBehavior.getMapControl().getMapContext().getViewPort();
        AffineTransform at = (AffineTransform) lyr.getAffineTransform().clone();
        at.preConcatenate(vp.getAffineTransform());
        Extent ext = lyr.getFullRasterExtent();

        Point2D pt = new Point2D.Double(ext.getULX(), ext.getULY());
        vp.getAffineTransform().transform(pt, pt);
        at.inverseTransform(pt, pt);

        Point2D size = new Point2D.Double(ext.getLRX(), ext.getLRY());
        vp.getAffineTransform().transform(size, size);
        at.inverseTransform(size, size);

        double distX = ptoFin.getX() - ptoIni.getX();
        double distY = ptoFin.getY() - ptoIni.getY();
        Point2D d = new Point2D.Double(ext.getULX() + distX, ext.getULY() + distY);
        vp.getAffineTransform().transform(d, d);
        at.inverseTransform(d, d);

        // Giramos el graphics se dibuja y se vuelve a dejar como estaba
        ((Graphics2D) g).transform(at);
        g.setColor(rectangleColor);
        AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.1f);
        ((Graphics2D) g).setComposite(alpha);
        g.fillRect(
            (int) pt.getX() + (int) d.getX(),
            (int) pt.getY() + (int) d.getY(),
            (int) size.getX(),
            (int) size.getY());
        ((Graphics2D) g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
        g.drawRect(
            (int) pt.getX() + (int) d.getX(),
            (int) pt.getY() + (int) d.getY(),
            (int) size.getX(),
            (int) size.getY());
        ((Graphics2D) g).transform(at.createInverse());
      } catch (NoninvertibleTransformException e1) {
        RasterToolsUtil.messageBoxError("error_transformacion1", this, e1);
      }
    }
  }
Example #18
0
  /** Coloca el cursor del ratón con el icono adecuado cuando entra dentro de la imagen. */
  public boolean mouseMoved(MouseEvent e) throws BehaviorException {

    ViewPort vp = grBehavior.getMapControl().getMapContext().getViewPort();

    try {
      lyr = grBehavior.getLayer();
      if (lyr == null) {
        setActiveTool(false);
        return false;
      }

      Point2D pto = vp.toMapPoint(e.getX(), e.getY());

      try {
        if (lyr.isInside(pto)) {
          grBehavior
              .getMapControl()
              .setCursor(
                  Toolkit.getDefaultToolkit()
                      .createCustomCursor(handCursor, new Point(16, 16), ""));
          defaultCursorActive = false;
          setActiveTool(true);
          return true;
        } else {
          if (!defaultCursorActive) {
            grBehavior.getMapControl().setCursor(defaultCursor);
            defaultCursorActive = true;
            setActiveTool(false);
            return false;
          }
        }
      } catch (HeadlessException e1) {
        e1.printStackTrace();
      } catch (IndexOutOfBoundsException e1) {
        e1.printStackTrace();
      }
    } catch (ClassCastException exc) {
      RasterToolsUtil.messageBoxError("error_capa_puntos", this, exc);
    }
    setActiveTool(false);
    return false;
  }
  /**
   * Cambiar el panel de propiedades central por el nuevo panel, segun el filtro seleccionado que se
   * pasa por parámetro.
   *
   * @param filter
   */
  public void changePanel(String filter) {
    int posParam = getParamSelected(filter);

    RefreshDataProperties();
    actualParam = posParam;

    PropertiesComponent propertiesComponent = new PropertiesComponent();

    if (posParam != -1) {
      Params params = ((ParamStruct) paramsList.get(actualParam)).getFilterParam();
      if (params != null) {
        Param paramPanel = params.getParamById("Panel");
        if (paramPanel != null && paramPanel.defaultValue instanceof RegistrableFilterListener)
          ((RegistrableFilterListener) paramPanel.defaultValue).addFilterUIListener(this);
        RasterToolsUtil.loadPropertiesFromWriterParams(
            propertiesComponent, params, new String[] {"FilterName"});
      }
    }
    getFilterPanel().setNewPropertiesComponent(propertiesComponent, filter);
  }
Example #20
0
  /**
   * Obtiene el bot�n que lanza el panel de selecci�n de proyecciones.
   *
   * @return
   */
  private CRSSelectPanel getProjectionDstSelector() {
    if (projectionDstSelector == null) {
      projectionDstSelector = CRSSelectPanel.getPanel(projDst);
      // projectionDstSelector.setTransPanelActive(true);
      projectionDstSelector.setPreferredSize(null);
      projectionDstSelector.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              if (projectionDstSelector.isOkPressed()) {
                projDst = projectionDstSelector.getCurProj();
              }
            }
          });
      projectionDstSelector.setBorder(
          BorderFactory.createTitledBorder(RasterToolsUtil.getText(this, "dest_proj")));

      if (!isInTOC.booleanValue()) StatusComponent.setDisabled(projectionDstSelector);
    }
    return projectionDstSelector;
  }
  /** Que acciones se ejecutaran al haber presionado el botón aceptar o aplicar */
  public void accept() {
    IRasterDataSource raster = ((FLyrRasterSE) getFilterPanel().getLayer()).getDataSource();
    if (raster == null) return;

    String path = null;
    if (!getFilterPanel().getNewLayerPanel().isOnlyViewSelected()) {
      path = getFilterPanel().getNewLayerPanel().getFileSelected();
      if (path == null) return;
    }

    // Rendering rendering = ((FLyrRasterSE)
    // getFilterPanel().getLayer()).getRender();
    IRasterRendering rendering = (IRasterRendering) getFilterPanel().getLayer();

    // Array para guardar los filtros que se van a usar en forma de
    // ParamStruct
    ArrayList listFilterUsed = applyFilters(rendering);

    if (filterPanel.getNewLayerPanel().isOnlyViewSelected()) {
      try {
        FilterProcess.addSelectedFilters(rendering.getRenderFilterList(), listFilterUsed);
        ((FLyrRasterSE) getFilterPanel().getLayer())
            .setRenderFilterList(rendering.getRenderFilterList());
        getFilterPanel().getLayer().getMapContext().invalidate();
      } catch (FilterTypeException e) {
        RasterToolsUtil.messageBoxError(
            PluginServices.getText(this, "error_adding_filters"), this, e);
      }
    } else {
      FilterProcess filterProcess = new FilterProcess();
      filterProcess.setActions(this);
      filterProcess.addParam("rendering", rendering);
      filterProcess.addParam("filename", path);
      filterProcess.addParam("rasterdatasource", raster);
      filterProcess.addParam("layer", ((FLyrRasterSE) getFilterPanel().getLayer()));
      filterProcess.addParam("listfilterused", listFilterUsed);
      filterProcess.start();
    }
  }
Example #22
0
  /** Inicialización de los componentes gráficos */
  protected void init() {
    setLayout(new GridBagLayout());
    setBorder(
        BorderFactory.createTitledBorder(
            null,
            RasterToolsUtil.getText(this, "highpassfilter"),
            javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION,
            javax.swing.border.TitledBorder.DEFAULT_POSITION,
            null,
            null));
    GridBagConstraints gbc = new GridBagConstraints();
    gbc.fill = GridBagConstraints.BOTH;
    gbc.weightx = 1;
    gbc.insets = new Insets(0, 0, 0, 0);

    add(getActive(), gbc);

    gbc.gridy = 1;
    add(getRadio(), gbc);

    getActive().addActionListener(this);
    setComponentEnabled(false);
  }
Example #23
0
  /**
   * Obtiene el bot�n que lanza el panel de selecci�n de proyecciones.
   *
   * @return
   */
  private CRSSelectPanel getProjectionSrcSelector() {
    if (projectionSrcSelector == null) {

      IProjection projectionAux = null;
      IWindow activeWindow = PluginServices.getMDIManager().getActiveWindow();
      if (activeWindow instanceof BaseView) {
        BaseView activeView = (BaseView) activeWindow;
        projectionAux = activeView.getProjection();
        activeView.setProjection(projSrc);
      }

      projectionSrcSelector = CRSSelectPanel.getPanel(projSrc);

      if (activeWindow instanceof BaseView) {
        BaseView activeView = (BaseView) activeWindow;
        activeView.setProjection(projectionAux);
      }

      // projectionSrcSelector.setTransPanelActive(true);
      projectionSrcSelector.setPreferredSize(null);
      projectionSrcSelector.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              if (projectionSrcSelector.isOkPressed()) {
                projSrc = projectionSrcSelector.getCurProj();
              }
            }
          });
      projectionSrcSelector.setBorder(
          BorderFactory.createTitledBorder(RasterToolsUtil.getText(this, "src_proj")));

      if (isInTOC.booleanValue() && this.lyr.readProjection() != null)
        StatusComponent.setDisabled(projectionSrcSelector);
    }
    return projectionSrcSelector;
  }
Example #24
0
  /** Proceso de calculo de la transformación tasseeledCap */
  public void process() throws InterruptedException {
    if (!exec) return;
    setBuffer();
    GridExtent layerExtent = new GridExtent(rasterSE.getFullRasterExtent(), rasterSE.getCellSize());

    // TODO: Tipo salida float
    rasterResult =
        RasterBuffer.getBuffer(
            IBuffer.TYPE_FLOAT,
            layerExtent.getNX(),
            layerExtent.getNY(),
            matrixParams.length,
            true);

    // Algoritmo TasseledCap. Trasformacion
    double valor = 0;
    int iNX = layerExtent.getNX();
    int iNY = layerExtent.getNY();

    //			 BUFFER TYPE_BYTE
    if (buffer.getDataType() == IBuffer.TYPE_BYTE) {
      for (int i = 0; i < iNY; i++) {
        for (int j = 0; j < iNX; j++) {
          for (int k = 0; k < matrixParams.length; k++) {
            for (int s = 0; s < matrixParams[0].length; s++) {
              valor += (double) (buffer.getElemByte(i, j, s) & 0xff) * matrixParams[k][s];
            }
            rasterResult.setElem(i, j, k, (float) valor);
            valor = 0;
          }
        }
        percent = (int) (i * 100 / iNY);
      }
    }

    //			 BUFFER TYPE_SHORT
    if (buffer.getDataType() == IBuffer.TYPE_SHORT) {
      for (int i = 0; i < iNY; i++) {
        for (int j = 0; j < iNX; j++) {
          for (int k = 0; k < matrixParams.length; k++) {
            for (int s = 0; s < matrixParams[0].length; s++) {
              valor += (double) buffer.getElemShort(i, j, s) * matrixParams[k][s];
            }
            rasterResult.setElem(i, j, k, (float) valor);
            valor = 0;
          }
        }
        percent = (int) (i * 100 / iNY);
      }
    }

    //			BUFFER TYPE INT
    if (buffer.getDataType() == IBuffer.TYPE_INT) {
      for (int i = 0; i < iNY; i++) {
        for (int j = 0; j < iNX; j++) {
          for (int k = 0; k < matrixParams.length; k++) {
            for (int s = 0; s < matrixParams[0].length; s++) {
              valor += (double) buffer.getElemInt(i, j, s) * matrixParams[k][s];
            }
            rasterResult.setElem(i, j, k, (float) valor);
            valor = 0;
          }
        }
        percent = (int) (i * 100 / iNY);
      }
    }

    //			BUFFER TYPE FLOAT
    if (buffer.getDataType() == IBuffer.TYPE_FLOAT) {
      for (int i = 0; i < iNY; i++) {
        for (int j = 0; j < iNX; j++) {
          for (int k = 0; k < matrixParams.length; k++) {
            for (int s = 0; s < matrixParams[0].length; s++) {
              valor += (double) buffer.getElemFloat(i, j, s) * matrixParams[k][s];
            }
            rasterResult.setElem(i, j, k, (float) valor);
            valor = 0;
          }
        }
        percent = (int) (i * 100 / iNY);
      }
    }

    //			BUFFER TYPE DOUBLE
    if (buffer.getDataType() == IBuffer.TYPE_DOUBLE) {
      for (int i = 0; i < iNY; i++) {
        for (int j = 0; j < iNX; j++) {
          for (int k = 0; k < matrixParams.length; k++) {
            for (int s = 0; s < matrixParams[0].length; s++) {
              valor += (double) buffer.getElemDouble(i, j, s) * matrixParams[k][s];
            }
            rasterResult.setElem(i, j, k, (float) valor);
            valor = 0;
          }
        }
        percent = (int) (i * 100 / iNY);
      }
    }

    // Escritura del resultado en disco
    GeoRasterWriter grw = null;
    writerBufferServer = new WriterBufferServer(rasterResult);

    if (fileName == null) return;

    int endIndex = fileName.lastIndexOf(".");
    if (endIndex < 0) endIndex = fileName.length();

    try {
      grw =
          GeoRasterWriter.getWriter(
              writerBufferServer,
              fileName,
              rasterResult.getBandCount(),
              aTransform,
              rasterResult.getWidth(),
              rasterResult.getHeight(),
              rasterResult.getDataType(),
              GeoRasterWriter.getWriter(fileName).getParams(),
              null);
      grw.dataWrite();
      grw.setWkt(rasterSE.getWktProjection());
      grw.writeClose();
      rasterResult.free();
      tasseledCapFinalize(fileName);
    } catch (NotSupportedExtensionException e1) {
      RasterToolsUtil.messageBoxError(
          PluginServices.getText(this, "error_writer_notsupportedextension"), this, e1);
    } catch (RasterDriverException e1) {
      e1.printStackTrace();
    } catch (IOException e) {
      RasterToolsUtil.messageBoxError(PluginServices.getText(this, "error_writer"), this, e);
    } catch (InterruptedException e) {
      Thread.currentThread().interrupt();
    }
  }
  /** Tarea de recorte */
  public void process() throws InterruptedException {
    IRasterDataSource dsetCopy = null;
    if (rasterSE != null) rasterSE.setReadingData(Thread.currentThread().toString());

    try {
      long t2;
      long t1 = new java.util.Date().getTime();

      insertLineLog(RasterToolsUtil.getText(this, "leyendo_raster"));

      dsetCopy = rasterSE.getDataSource().newDataset();
      BufferFactory bufferFactory = new BufferFactory(dsetCopy);
      bufferFactory.setDrawableBands(drawableBands);

      if (interpolationMethod != BufferInterpolation.INTERPOLATION_Undefined) {
        try {
          if (pValues != null) {
            if (RasterBuffer.isBufferTooBig(
                new double[] {pValues[0], pValues[3], pValues[2], pValues[1]},
                drawableBands.length)) bufferFactory.setReadOnly(true);
            bufferFactory.setAreaOfInterest(
                pValues[0], pValues[3], pValues[2] - pValues[0], pValues[1] - pValues[3]);
          } else if (wcValues != null) {
            // if (RasterBuffer.isBufferTooBig(new double[] {
            // wcValues[0], wcValues[3], wcValues[2], wcValues[1] },
            // rasterSE.getCellSize(), drawableBands.length))
            if (!rasterSE.isActionEnabled(IRasterLayerActions.REMOTE_ACTIONS))
              bufferFactory.setReadOnly(true);
            bufferFactory.setAreaOfInterest(
                wcValues[0],
                wcValues[1],
                Math.abs(wcValues[0] - wcValues[2]),
                Math.abs(wcValues[1] - wcValues[3]));
          }
        } catch (InvalidSetViewException e) {
          RasterToolsUtil.messageBoxError(
              "No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
        }
        buffer = bufferFactory.getRasterBuf();

        insertLineLog(RasterToolsUtil.getText(this, "interpolando"));

        if (buffer != null)
          buffer =
              ((RasterBuffer) buffer)
                  .getAdjustedWindow(resolutionWidth, resolutionHeight, interpolationMethod);
        else {
          RasterToolsUtil.messageBoxError(
              "El proceso de recorte ha fallado porque el buffer no contenía datos.",
              this,
              new NullPointerException());
          return;
        }
      } else {
        try {
          if (RasterBuffer.isBufferTooBig(
              new double[] {0, 0, resolutionWidth, resolutionHeight}, drawableBands.length))
            bufferFactory.setReadOnly(true);
          if (pValues != null)
            bufferFactory.setAreaOfInterest(
                pValues[0],
                pValues[3],
                Math.abs(pValues[2] - pValues[0]) + 1,
                Math.abs(pValues[1] - pValues[3]) + 1,
                resolutionWidth,
                resolutionHeight);
          else if (wcValues != null)
            bufferFactory.setAreaOfInterest(
                wcValues[0],
                wcValues[1],
                wcValues[2],
                wcValues[3],
                resolutionWidth,
                resolutionHeight);
          buffer = bufferFactory.getRasterBuf();
          if (buffer == null) {
            RasterToolsUtil.messageBoxError(
                "El proceso de recorte ha fallado porque el buffer no contenía datos.",
                this,
                new NullPointerException());
            return;
          }
        } catch (InvalidSetViewException e) {
          RasterToolsUtil.messageBoxError(
              "No se ha podido asignar la vista al inicial el proceso de recorte.", this, e);
        }
      }
      // TODO: FUNCIONALIDAD: Poner los getWriter con la proyección del
      // fichero fuente

      if ((selectedRois != null) && (!bufferFactory.isReadOnly())) {
        if (selectedRois.size() > 0) {
          int despX = 0;
          int despY = 0;
          if (pValues != null) {
            despX = pValues[0];
            despY = pValues[1];
          } else if (wcValues != null) {
            despX =
                (int) dsetCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getX();
            despY =
                (int) dsetCopy.worldToRaster(new Point2D.Double(wcValues[0], wcValues[1])).getY();
          }
          drawOnlyROIs(buffer, selectedRois, despX, despY);
        }
      }

      insertLineLog(RasterToolsUtil.getText(this, "salvando_imagen"));

      String finalFileName = "";
      if (oneLayerPerBand) {
        long[] milis = new long[drawableBands.length];
        String[] fileNames = new String[drawableBands.length];
        for (int i = 0; i < drawableBands.length; i++) {
          fileNames[i] = fileName + "_B" + drawableBands[i] + ".tif";
          writerBufferServer.setBuffer(buffer, i);
          Params p = null;
          if (params == null) p = GeoRasterWriter.getWriter(fileNames[i]).getParams();
          else p = params;
          grw =
              GeoRasterWriter.getWriter(
                  writerBufferServer,
                  fileNames[i],
                  1,
                  affineTransform,
                  buffer.getWidth(),
                  buffer.getHeight(),
                  buffer.getDataType(),
                  p,
                  null);
          grw.setColorBandsInterpretation(new String[] {DatasetColorInterpretation.GRAY_BAND});
          grw.setWkt(dsetCopy.getWktProjection());
          grw.setCancellableRasterDriver(cancellableObj);
          grw.dataWrite();
          grw.writeClose();
          saveToRmf(fileNames[i]);
          t2 = new java.util.Date().getTime();
          milis[i] = (t2 - t1);
          t1 = new java.util.Date().getTime();
        }
        if (incrementableTask != null) {
          incrementableTask.processFinalize();
          incrementableTask = null;
        }
        if (viewName != null) {
          if (RasterToolsUtil.messageBoxYesOrNot("cargar_toc", this)) {
            try {
              for (int i = 0; i < drawableBands.length; i++) {
                FLayer lyr = RasterToolsUtil.loadLayer(viewName, fileNames[i], null);
                if (lyr != null && lyr instanceof FLyrRasterSE)
                  ((FLyrRasterSE) lyr).setRois(rasterSE.getRois());
              }
            } catch (RasterNotLoadException e) {
              RasterToolsUtil.messageBoxError("error_load_layer", this, e);
            }
          }
        }
        for (int i = 0; i < drawableBands.length; i++) {
          if (externalActions != null)
            externalActions.end(
                new Object[] {fileName + "_B" + drawableBands[i] + ".tif", new Long(milis[i])});
        }
      } else {
        if (isUsingFile(fileName)) {
          incrementableTask.hideWindow();
          RasterToolsUtil.messageBoxError("error_opened_file", this);
          return;
        }
        File f = new File(fileName);
        if (f.exists()) {
          f.delete();
        }
        f = null;
        writerBufferServer.setBuffer(buffer, -1);
        if (params == null) {
          finalFileName = fileName + ".tif";
          params = GeoRasterWriter.getWriter(finalFileName).getParams();
        } else finalFileName = fileName;
        grw =
            GeoRasterWriter.getWriter(
                writerBufferServer,
                finalFileName,
                buffer.getBandCount(),
                affineTransform,
                buffer.getWidth(),
                buffer.getHeight(),
                buffer.getDataType(),
                params,
                null);
        if (colorInterp != null) grw.setColorBandsInterpretation(colorInterp.getValues());
        grw.setWkt(dsetCopy.getWktProjection());
        grw.setCancellableRasterDriver(cancellableObj);
        grw.dataWrite();
        grw.writeClose();
        saveToRmf(finalFileName);
        t2 = new java.util.Date().getTime();
        if (incrementableTask != null) {
          incrementableTask.processFinalize();
          incrementableTask = null;
        }
        // Damos tiempo a parar el Thread del incrementable para que no
        // se cuelgue la ventana
        // El tiempo es como mínimo el de un bucle del run de la tarea
        // incrementable
        Thread.sleep(600);
        cutFinalize(finalFileName, (t2 - t1));
      }

    } catch (NotSupportedExtensionException e) {
      RasterToolsUtil.messageBoxError("error_not_suported_extension", this, e);
    } catch (RasterDriverException e) {
      RasterToolsUtil.messageBoxError("error_writer", this, e);
    } catch (IOException e) {
      RasterToolsUtil.messageBoxError("error_georasterwriter", this, e);
    } finally {
      if (rasterSE != null) rasterSE.setReadingData(null);
      if (dsetCopy != null) dsetCopy.close();
      buffer = null;
    }
  }
 /*
  * (non-Javadoc)
  *
  * @see org.gvsig.gui.beans.incrementabletask.IIncrementable#getTitle()
  */
 public String getTitle() {
   return RasterToolsUtil.getText(this, "incremento_recorte");
 }
  /**
   * Aqui se seleccionan que filtros se van a aplicar y se devuelven en forma de ArrayList tanto
   * para el dibujado como cuando aceptan o aplican el panel.
   *
   * @param rendering
   * @return
   */
  public ArrayList applyFilters(IRasterRendering rendering) {
    ArrayList listFilterUsed = new ArrayList();

    RasterFilterList filterList = new RasterFilterList();
    filterList.setEnv(rendering.getRenderFilterList().getEnv());
    RasterFilterListManager stackManager = new RasterFilterListManager(filterList);

    // Conservamos filtros no visibles ya existentes
    ArrayList filtersInit = getFilterPanel().getLayerVisualStatus().getLast().getFilterStatus();
    for (int i = 0; i < filtersInit.size(); i++) {
      // Si es visible no hacemos nada
      if (((RasterFilter) filtersInit.get(i)).isVisible()) continue;

      RasterFilter obj = null;
      for (int j = 0; j < stackManager.getRasterFilterList().size(); j++) {
        Class classFilter = (Class) stackManager.getRasterFilterList().get(j);
        try {
          obj = (RasterFilter) classFilter.newInstance();
          if (obj.getName().equals(((RasterFilter) filtersInit.get(i)).getName())) break;
        } catch (InstantiationException e) {
          RasterToolsUtil.messageBoxError("error_creando_filtro", this, e);
        } catch (IllegalAccessException e) {
          RasterToolsUtil.messageBoxError("error_creando_filtro", this, e);
        }
      }

      // Si no encontramos el filtro apropiado, nos olvidamos de el
      if (obj == null) continue;

      // Si no es visible tenemos que conservar el filtro
      try {
        Params params =
            (Params)
                ((RasterFilter) filtersInit.get(i))
                    .getUIParams(((RasterFilter) filtersInit.get(i)).getName())
                    .clone();
        // Añado el parametro RenderBands a los parametros del filtro
        String rgb =
            rendering.getRenderBands()[0]
                + " "
                + rendering.getRenderBands()[1]
                + " "
                + rendering.getRenderBands()[2];
        params.setParam("RenderBands", rgb, 0, null);
        params.setParam("alphaBand", new Integer(rendering.getAlphaBandNumber()), 0, null);

        ParamStruct newParam = new ParamStruct();
        newParam.setFilterClass(obj.getClass());
        newParam.setFilterName(((RasterFilter) filtersInit.get(i)).getName());
        newParam.setFilterParam(params);
        listFilterUsed.add(newParam);
      } catch (CloneNotSupportedException e) {
      }
    }

    // Metemos los filtros seleccionados en el panel
    ListModel list = getFilterPanel().getMainPanel().getTreeListContainer().getListModel();
    for (int i = 0; i < list.getSize(); i++) {
      Hashtable hastTable = getFilterPanel().getMainPanel().getTreeListContainer().getMap();
      for (int j = 0; j < paramsList.size(); j++) {
        boolean active = true;
        Param param = ((ParamStruct) paramsList.get(j)).getFilterParam().getParamById("enabled");
        if ((param != null)
            && param.defaultValue instanceof Boolean
            && ((((Boolean) param.defaultValue).booleanValue()) == false)) active = false;
        if (active) {
          if (((ParamStruct) paramsList.get(j))
              .getFilterName()
              .equals(hastTable.get(list.getElementAt(i)))) {
            try {
              Params params = (Params) ((ParamStruct) paramsList.get(j)).getFilterParam().clone();
              // Añado el parametro RenderBands a los parametros
              // del filtro
              String rgb =
                  rendering.getRenderBands()[0]
                      + " "
                      + rendering.getRenderBands()[1]
                      + " "
                      + rendering.getRenderBands()[2];
              params.setParam("RenderBands", rgb, 0, null);
              params.setParam("alphaBand", new Integer(rendering.getAlphaBandNumber()), 0, null);

              ParamStruct newParam = new ParamStruct();
              newParam.setFilterClass(((ParamStruct) paramsList.get(j)).getFilterClass());
              newParam.setFilterName(((ParamStruct) paramsList.get(j)).getFilterName());
              newParam.setFilterParam(params);
              listFilterUsed.add(newParam);
            } catch (CloneNotSupportedException e) {
            }
          }
        }
      }
    }
    return listFilterUsed;
  }
  /*
   * (non-Javadoc)
   *
   * @see org.gvsig.raster.gui.wizards.IFileOpen#post(java.io.File[])
   */
  public File post(File file) throws LoadLayerException {

    // Si el fichero es raw lanzamos el dialogo de parámetros de raw
    if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("raw")) {
      OpenRawFileDefaultView view = new OpenRawFileDefaultView(file.getAbsolutePath());
      file = view.getImageFile();
    }

    if (file == null || file.getAbsoluteFile() == null) return null;

    // Si el fichero es vrt chequeamos que sea correcto
    if (RasterUtilities.getExtensionFromFileName(file.getAbsolutePath()).equals("vrt")) {
      try {
        checkFileVRT(file);
      } catch (FileOpenVRTException e) {
        RasterToolsUtil.messageBoxError(
            PluginServices.getText(this, "error_abrir_fichero")
                + " "
                + file.getName()
                + "\n\n"
                + PluginServices.getText(this, "informacion_adicional")
                + ":\n\n  "
                + e.getMessage(),
            this,
            e);
        return null;
      }
    }

    try {
      FLyrRasterSE lyrRaster = null;

      String lyr_name = RasterToolsUtil.getLayerNameFromFile(file);
      lyrRaster = FLyrRasterSE.createLayer(lyr_name, file, null);

      // Si hay que generar las overviews por el panel de preferencias
      // if (Configuration.getValue("overviews_ask_before_loading",
      // Boolean.FALSE).booleanValue() == true) {
      // try {
      // boolean generate = false;
      // for (int i = 0; i < lyrRaster.getFileCount(); i++) {
      // if
      // (lyrRaster.getDataSource().getDataset(i)[0].getOverviewCount(0)
      // == 0) {
      // generate = true;
      // break;
      // }
      // }
      // if (generate) {
      // if (firstTaskOverview) {
      // execOverview =
      // RasterToolsUtil.messageBoxYesOrNot("generar_overviews", this);
      // firstTaskOverview = false;
      // }
      //
      // if (execOverview) {
      // RasterProcess process = new OverviewsProcess();
      // process.setCancelable(false);
      // process.addParam("layer", (FLyrRasterSE) lyrRaster);
      // UniqueProcessQueue.getSingleton().add(process);
      // }
      // }
      // } catch (Exception e) {
      // // Si no se puede generar la overview no hacemos nada
      // }
      // }

      // Mostramos el cuadro que pide la georreferenciación si la capa no
      // tiene y si la opción está activa en preferencias
      if (RasterModule.askCoordinates) {
        if (lyrRaster.getFullExtent().getMinX() == 0
            && lyrRaster.getFullExtent().getMinY() == 0
            && lyrRaster.getFullExtent().getMaxX() == ((FLyrRasterSE) lyrRaster).getPxWidth()
            && lyrRaster.getFullExtent().getMaxY() == ((FLyrRasterSE) lyrRaster).getPxHeight()) {
          if (RasterToolsUtil.messageBoxYesOrNot(
              lyrRaster.getName() + "\n" + PluginServices.getText(this, "layer_without_georref"),
              null)) {
            GeoLocationOpeningRasterDialog gld = new GeoLocationOpeningRasterDialog(lyrRaster);
            PluginServices.getMDIManager().addWindow(gld);
          }
        }
      }

      // Opciones de proyección
      boolean compareProj =
          Configuration.getValue("general_ask_projection", Boolean.valueOf(false)).booleanValue();
      if (compareProj) compareProjections(lyrRaster);
      else actionList.add(new Integer(defaultActionLayer));

      lyrsRaster.add(lyrRaster);
    } catch (LoadLayerException e) {
      RasterToolsUtil.messageBoxError("error_carga_capa", this, e);
      throw new LoadLayerException("error_carga_capa", e);
    }

    return super.post(file);
  }
Example #29
0
  /** Inicializaci�n de los componentes gr�ficos. */
  private void init() {
    GridBagConstraints gridBagConstraints;

    setLayout(new GridBagLayout());

    int posy = 0;

    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.BOTH;
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = posy;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.insets = new Insets(5, 0, 2, 0);
    JPanel panelFile = new JPanel();
    panelFile.setLayout(new BorderLayout());
    panelFile.setBorder(BorderFactory.createTitledBorder(RasterToolsUtil.getText(this, "origen")));
    JLabel label = new JLabel("<html><b>" + lyr.getName() + "</b></html>");
    panelFile.add(label, BorderLayout.CENTER);
    add(panelFile, gridBagConstraints);

    posy++;
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.BOTH;
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = posy;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.insets = new Insets(2, 0, 2, 0);
    add(getProjectionSrcSelector(), gridBagConstraints);

    posy++;
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.fill = GridBagConstraints.BOTH;
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = posy;
    gridBagConstraints.weightx = 1.0;
    gridBagConstraints.insets = new Insets(2, 0, 2, 0);
    add(getProjectionDstSelector(), gridBagConstraints);

    posy++;
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = posy;
    gridBagConstraints.fill = GridBagConstraints.BOTH;
    gridBagConstraints.insets = new Insets(2, 0, 2, 0);
    add(getNewLayerPanel().getJPanel(), gridBagConstraints);

    posy++;
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = posy;
    gridBagConstraints.fill = GridBagConstraints.BOTH;
    gridBagConstraints.insets = new Insets(2, 0, 0, 0);
    add(getFilePanel(), gridBagConstraints);

    // Insertamos un panel vacio
    posy++;
    gridBagConstraints = new GridBagConstraints();
    gridBagConstraints.gridx = 0;
    gridBagConstraints.gridy = posy;
    gridBagConstraints.weighty = 1.0;
    gridBagConstraints.insets = new Insets(0, 0, 0, 0);
    JPanel emptyPanel = new JPanel();
    add(emptyPanel, gridBagConstraints);
  }