file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
ArrowInfo.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/ArrowInfo.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind;
import gov.nasa.worldwindx.examples.util.DirectedPath;
/**
*/
public class ArrowInfo {
public DirectedPath theDirectedPath = null;
public double theAvgIncAngle;
public double theAvgWindSpeed;
public double theAvgWindDir;
public double theArrowLength;
public ArrowInfo(DirectedPath directedPath, double avgIncAngle, double avgWindSpeed, double avgWindDir, double arrowLength_deg) {
super();
theDirectedPath = directedPath;
theAvgIncAngle = avgIncAngle;
theAvgWindSpeed = avgWindSpeed;
theAvgWindDir = avgWindDir;
theArrowLength = arrowLength_deg;
}
}
| 1,387 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultWWLayerDescriptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/layers/DefaultWWLayerDescriptor.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.layers;
import com.bc.ceres.core.Assert;
/**
* Provides a standard implementation for {@link WWLayerDescriptor}.
*/
public class DefaultWWLayerDescriptor implements WWLayerDescriptor {
private String id;
private boolean showInWorldMapToolView;
private boolean showIn3DToolView;
private Class<? extends WWLayer> WWLayerClass;
public DefaultWWLayerDescriptor(final String id,
final boolean showInWorldMapToolView, final boolean showIn3DToolView,
final Class<? extends WWLayer> WWLayerClass) {
this.id = id;
this.showInWorldMapToolView = showInWorldMapToolView;
this.showIn3DToolView = showIn3DToolView;
this.WWLayerClass = WWLayerClass;
}
public String getId() {
return id;
}
public boolean showInWorldMapToolView() {
return showInWorldMapToolView;
}
public boolean showIn3DToolView() {
return showIn3DToolView;
}
public WWLayer createWWLayer() {
Assert.state(WWLayerClass != null, "WWLayerClass != null");
Object object;
try {
object = WWLayerClass.newInstance();
} catch (Throwable e) {
throw new IllegalStateException("WWLayerClass.newInstance()", e);
}
Assert.state(object instanceof WWLayer, "object instanceof WWLayer");
return (WWLayer) object;
}
}
| 2,181 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BaseLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/layers/BaseLayer.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.layers;
import gov.nasa.worldwind.layers.RenderableLayer;
import org.esa.snap.core.datamodel.Product;
/**
* Base layer class
*/
public abstract class BaseLayer extends RenderableLayer {
protected Product selectedProduct = null;
public void setSelectedProduct(final Product product) {
selectedProduct = product;
}
public Product getSelectedProduct() {
return selectedProduct;
}
}
| 1,175 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultProductLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/layers/DefaultProductLayer.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.layers;
import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.awt.WorldWindowGLCanvas;
import gov.nasa.worldwind.event.SelectEvent;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Sector;
import gov.nasa.worldwind.render.Offset;
import gov.nasa.worldwind.render.PointPlacemark;
import gov.nasa.worldwind.render.PointPlacemarkAttributes;
import gov.nasa.worldwind.render.Polyline;
import gov.nasa.worldwind.render.SurfaceImage;
import org.esa.snap.core.dataio.ProductSubsetDef;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.engine_utilities.datamodel.AbstractMetadata;
import org.esa.snap.engine_utilities.eo.Constants;
import org.esa.snap.engine_utilities.eo.GeoUtils;
import org.esa.snap.engine_utilities.gpf.InputProductValidator;
import org.esa.snap.rcp.util.Dialogs;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingWorker;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.geom.GeneralPath;
import java.awt.geom.PathIterator;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
/**
* Default Product Layer draws product outline
*/
public class DefaultProductLayer extends BaseLayer implements WWLayer {
private boolean enableSurfaceImages;
private final ConcurrentHashMap<String, Polyline[]> outlineTable = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, SurfaceImage> imageTable = new ConcurrentHashMap<>();
private final ConcurrentHashMap<String, PointPlacemark> labelTable = new ConcurrentHashMap<>();
public WorldWindowGLCanvas theWWD = null;
public DefaultProductLayer() {
this.setName("Products");
}
public void setEnableSurfaceImages(final boolean enableSurfaceImages) {
this.enableSurfaceImages = enableSurfaceImages;
}
public String[] getProductNames() {
final List<String> list = new ArrayList<>(outlineTable.keySet());
Collections.sort(list);
return list.toArray(new String[outlineTable.size()]);
}
private static String getUniqueName(final Product product) {
return product.getProductRefString() + product.getName();
}
@Override
public void setOpacity(double opacity) {
super.setOpacity(opacity);
for (Map.Entry<String, SurfaceImage> entry : this.imageTable.entrySet()) {
entry.getValue().setOpacity(opacity);
}
}
public void setOpacity(String name, double opacity) {
final SurfaceImage img = imageTable.get(name);
if (img != null)
img.setOpacity(opacity);
}
public double getOpacity(String name) {
final SurfaceImage img = imageTable.get(name);
if (img != null)
return img.getOpacity();
else {
final Polyline[] lineList = outlineTable.get(name);
return lineList != null ? 1 : 0;
}
}
public void updateInfoAnnotation(final SelectEvent event) {
}
@Override
public void setSelectedProduct(final Product product) {
super.setSelectedProduct(product);
if (selectedProduct != null) {
final String selName = getUniqueName(selectedProduct);
for (String name : outlineTable.keySet()) {
final Polyline[] lineList = outlineTable.get(name);
final boolean highlight = name.equals(selName);
for (Polyline line : lineList) {
line.setHighlighted(highlight);
line.setHighlightColor(Color.RED);
}
}
}
}
public void addProduct(final Product product, WorldWindowGLCanvas wwd) {
theWWD = wwd;
final String name = getUniqueName(product);
if (this.outlineTable.get(name) != null)
return;
final GeoCoding geoCoding = product.getSceneGeoCoding();
if (geoCoding == null) {
final String productType = product.getProductType();
if (productType.equals("ASA_WVW_2P") || productType.equals("ASA_WVS_1P") || productType.equals("ASA_WVI_1P")) {
addWaveProduct(product);
}
} else {
if (enableSurfaceImages) {
if (InputProductValidator.isMapProjected(product) && product.getSceneGeoCoding() != null) {
addSurfaceImage(product);
}
}
// add outline
addOutline(product);
}
}
private void addSurfaceImage(final Product product) {
final String name = getUniqueName(product);
final SwingWorker worker = new SwingWorker() {
@Override
protected SurfaceImage doInBackground() throws Exception {
try {
final Product newProduct = createSubsampledProduct(product);
final Band band = newProduct.getBandAt(0);
final BufferedImage image = ProductUtils.createRgbImage(new RasterDataNode[]{band},
band.getImageInfo(com.bc.ceres.core.ProgressMonitor.NULL),
com.bc.ceres.core.ProgressMonitor.NULL);
final GeoPos geoPos1 = product.getSceneGeoCoding().getGeoPos(new PixelPos(0, 0), null);
final GeoPos geoPos2 = product.getSceneGeoCoding().getGeoPos(new PixelPos(product.getSceneRasterWidth() - 1,
product.getSceneRasterHeight() - 1),
null
);
final Sector sector = new Sector(Angle.fromDegreesLatitude(geoPos1.getLat()),
Angle.fromDegreesLatitude(geoPos2.getLat()),
Angle.fromDegreesLongitude(geoPos1.getLon()),
Angle.fromDegreesLongitude(geoPos2.getLon()));
final SurfaceImage si = new SurfaceImage(image, sector);
si.setOpacity(getOpacity());
return si;
} catch (Exception e) {
//e.printStackTrace();
}
return null;
}
@Override
public void done() {
try {
if (imageTable.contains(name))
removeImage(name);
final SurfaceImage si = (SurfaceImage) get();
if (si != null) {
addRenderable(si);
imageTable.put(name, si);
}
} catch (Exception e) {
Dialogs.showError(e.getMessage());
}
}
};
worker.execute();
}
private void addOutline(final Product product) {
final int step = Math.max(16, (product.getSceneRasterWidth() + product.getSceneRasterHeight()) / 250);
final GeneralPath[] boundaryPaths = org.esa.snap.core.util.GeoUtils.createGeoBoundaryPaths(product, null, step, true);
final Polyline[] polyLineList = new Polyline[boundaryPaths.length];
int i = 0;
int numPoints = 0;
float centreLat = 0;
float centreLon = 0;
for (GeneralPath boundaryPath : boundaryPaths) {
final PathIterator it = boundaryPath.getPathIterator(null);
final float[] floats = new float[2];
final List<Position> positions = new ArrayList<>(4);
it.currentSegment(floats);
final Position firstPosition = new Position(Angle.fromDegreesLatitude(floats[1]),
Angle.fromDegreesLongitude(floats[0]), 0.0);
positions.add(firstPosition);
centreLat += floats[1];
centreLon += floats[0];
it.next();
numPoints++;
while (!it.isDone()) {
it.currentSegment(floats);
positions.add(new Position(Angle.fromDegreesLatitude(floats[1]),
Angle.fromDegreesLongitude(floats[0]), 0.0));
centreLat += floats[1];
centreLon += floats[0];
it.next();
numPoints++;
}
// close the loop
positions.add(firstPosition);
centreLat = centreLat / numPoints;
centreLon = centreLon / numPoints;
polyLineList[i] = new Polyline();
polyLineList[i].setFollowTerrain(true);
polyLineList[i].setPositions(positions);
// ADDED
//polyLineList[i].setColor(new Color(1f, 0f, 0f, 0.99f));
//polyLineList[i].setLineWidth(10);
addRenderable(polyLineList[i]);
++i;
}
Position centrePos = new Position(Angle.fromDegreesLatitude(centreLat), Angle.fromDegreesLongitude(centreLon), 0.0);
PointPlacemark ppm = getLabelPlacemark(centrePos, String.valueOf(product.getRefNo()));
ppm.setAltitudeMode(WorldWind.CLAMP_TO_GROUND);
ppm.setEnableDecluttering(true);
addRenderable(ppm);
outlineTable.put(getUniqueName(product), polyLineList);
labelTable.put(getUniqueName(product), ppm);
}
private void addWaveProduct(final Product product) {
final MetadataElement root = AbstractMetadata.getOriginalProductMetadata(product);
final MetadataElement ggADS = root.getElement("GEOLOCATION_GRID_ADS");
if (ggADS == null) return;
final MetadataElement[] geoElemList = ggADS.getElements();
final Polyline[] lineList = new Polyline[geoElemList.length];
int cnt = 0;
int numPoints = 0;
float centreLat = 0;
float centreLon = 0;
for (MetadataElement geoElem : geoElemList) {
final double lat = geoElem.getAttributeDouble("center_lat", 0.0) / Constants.oneMillion;
final double lon = geoElem.getAttributeDouble("center_long", 0.0) / Constants.oneMillion;
final double heading = geoElem.getAttributeDouble("heading", 0.0);
final GeoUtils.LatLonHeading r1 = GeoUtils.vincenty_direct(new GeoPos(lat, lon), 5000, heading);
final GeoUtils.LatLonHeading corner1 = GeoUtils.vincenty_direct(new GeoPos(r1.lat, r1.lon), 2500, heading - 90.0);
final GeoUtils.LatLonHeading corner2 = GeoUtils.vincenty_direct(new GeoPos(r1.lat, r1.lon), 2500, heading + 90.0);
final GeoUtils.LatLonHeading r2 = GeoUtils.vincenty_direct(new GeoPos(lat, lon), 5000, heading + 180.0);
final GeoUtils.LatLonHeading corner3 = GeoUtils.vincenty_direct(new GeoPos(r2.lat, r2.lon), 2500, heading - 90.0);
final GeoUtils.LatLonHeading corner4 = GeoUtils.vincenty_direct(new GeoPos(r2.lat, r2.lon), 2500, heading + 90.0);
final List<Position> positions = new ArrayList<>(4);
positions.add(new Position(Angle.fromDegreesLatitude(corner1.lat), Angle.fromDegreesLongitude(corner1.lon), 0.0));
positions.add(new Position(Angle.fromDegreesLatitude(corner2.lat), Angle.fromDegreesLongitude(corner2.lon), 0.0));
positions.add(new Position(Angle.fromDegreesLatitude(corner4.lat), Angle.fromDegreesLongitude(corner4.lon), 0.0));
positions.add(new Position(Angle.fromDegreesLatitude(corner3.lat), Angle.fromDegreesLongitude(corner3.lon), 0.0));
positions.add(new Position(Angle.fromDegreesLatitude(corner1.lat), Angle.fromDegreesLongitude(corner1.lon), 0.0));
centreLat += corner1.lat;
centreLon += corner1.lon;
centreLat += corner2.lat;
centreLon += corner2.lon;
centreLat += corner3.lat;
centreLon += corner3.lon;
centreLat += corner4.lat;
centreLon += corner4.lon;
numPoints += 4;
final Polyline line = new Polyline();
line.setFollowTerrain(true);
line.setPositions(positions);
addRenderable(line);
lineList[cnt++] = line;
}
centreLat = centreLat / numPoints;
centreLon = centreLon / numPoints;
Position centrePos = new Position(Angle.fromDegreesLatitude(centreLat), Angle.fromDegreesLongitude(centreLon), 0.0);
PointPlacemark ppm = getLabelPlacemark(centrePos, String.valueOf(product.getRefNo()));
ppm.setAltitudeMode(WorldWind.CLAMP_TO_GROUND);
ppm.setEnableDecluttering(true);
addRenderable(ppm);
outlineTable.put(getUniqueName(product), lineList);
labelTable.put(getUniqueName(product), ppm);
}
private PointPlacemark getLabelPlacemark(Position pos, String label) {
PointPlacemarkAttributes ppmAtttrs = new PointPlacemarkAttributes();
ppmAtttrs.setLabelOffset(new Offset(0.0, 0.0, AVKey.PIXELS, AVKey.PIXELS));
ppmAtttrs.setScale(0.0);
PointPlacemark ppm = new PointPlacemark(pos);
ppm.setAttributes(ppmAtttrs);
ppm.setLabelText(label);
return ppm;
}
public void removeProduct(final Product product) {
removeOutline(getUniqueName(product));
removeImage(getUniqueName(product));
removeLabel(getUniqueName(product));
}
private void removeOutline(String imagePath) {
final Polyline[] lineList = this.outlineTable.get(imagePath);
if (lineList != null) {
for (Polyline line : lineList) {
this.removeRenderable(line);
}
this.outlineTable.remove(imagePath);
}
}
private void removeImage(String imagePath) {
final SurfaceImage si = this.imageTable.get(imagePath);
if (si != null) {
this.removeRenderable(si);
this.imageTable.remove(imagePath);
}
}
private void removeLabel(String imagePath) {
final PointPlacemark ppm = this.labelTable.get(imagePath);
if (ppm != null) {
this.removeRenderable(ppm);
this.labelTable.remove(ppm);
}
}
private static Product createSubsampledProduct(final Product product) throws IOException {
final String quicklookBandName = ProductUtils.findSuitableQuicklookBandName(product);
final ProductSubsetDef productSubsetDef = new ProductSubsetDef("subset");
int scaleFactor = product.getSceneRasterWidth() / 1000;
if (scaleFactor < 1) {
scaleFactor = 1;
}
productSubsetDef.setSubSampling(scaleFactor, scaleFactor);
productSubsetDef.setTreatVirtualBandsAsRealBands(true);
productSubsetDef.setNodeNames(new String[]{quicklookBandName});
Product productSubset = product.createSubset(productSubsetDef, quicklookBandName, null);
if (!InputProductValidator.isMapProjected(product) && productSubset.getSceneGeoCoding() != null) {
try {
final Map<String, Object> projParameters = new HashMap<>();
Map<String, Product> projProducts = new HashMap<>();
projProducts.put("source", productSubset);
projParameters.put("crs", "WGS84(DD)");
productSubset = GPF.createProduct("Reproject", projParameters, projProducts);
} catch (Exception e) {
e.printStackTrace();
}
}
return productSubset;
}
public JPanel getControlPanel(final WorldWindowGLCanvas wwd) {
final JSlider opacitySlider = new JSlider();
opacitySlider.setMaximum(100);
opacitySlider.setValue((int) (getOpacity() * 100));
opacitySlider.setEnabled(true);
opacitySlider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent e) {
int value = opacitySlider.getValue();
setOpacity(value / 100d);
wwd.repaint();
}
});
//theSelectedObjectLabel = new JLabel("Selected: ");
final JPanel opacityPanel = new JPanel(new BorderLayout(5, 5));
opacityPanel.add(new JLabel("Opacity"), BorderLayout.WEST);
opacityPanel.add(opacitySlider, BorderLayout.CENTER);
return opacityPanel;
}
}
| 17,949 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WWLayerDescriptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/layers/WWLayerDescriptor.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.layers;
/**
* Descriptor interface
*/
public interface WWLayerDescriptor {
String getId();
WWLayer createWWLayer();
boolean showInWorldMapToolView();
boolean showIn3DToolView();
}
| 956 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FixingPlaceNameLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/layers/FixingPlaceNameLayer.java | /*
* Copyright (c) 2021. Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*
*
*/
package org.esa.snap.worldwind.layers;
import gov.nasa.worldwind.layers.Earth.NASAWFSPlaceNameLayer;
import gov.nasa.worldwind.render.DeclutteringTextRenderer;
import gov.nasa.worldwind.render.DrawContext;
import gov.nasa.worldwind.render.DrawContextImpl;
import gov.nasa.worldwind.render.GeographicText;
import org.esa.snap.runtime.Engine;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author Marco Peters
* @since 8.0.6
*/
public class FixingPlaceNameLayer extends NASAWFSPlaceNameLayer {
private static final Logger LOGGER = Engine.getInstance().getLogger();
private final DeclutteringTextRenderer fixedTxtRenderer;
private final Field rendererField;
public FixingPlaceNameLayer() {
super();
rendererField = getTextRendererField();
final HashMap<String, String> nameMap = new HashMap<>();
nameMap.put("Sea of Japan", "Sea of Japan/East Sea");
fixedTxtRenderer = new NamesFixingTextRenderer(nameMap);
}
@Override
public void render(DrawContext dc) {
if (rendererField != null) {
fixedTextRendering(dc, rendererField, fixedTxtRenderer);
} else {
super.render(dc);
}
}
private void fixedTextRendering(DrawContext dc, Field field, DeclutteringTextRenderer fixedDtr) {
DeclutteringTextRenderer origRenderer = dc.getDeclutteringTextRenderer();
try {
exchangeRenderer(dc, field, fixedDtr);
super.render(dc);
} finally {
exchangeRenderer(dc, field, origRenderer);
}
}
private void exchangeRenderer(DrawContext dc, Field field, DeclutteringTextRenderer fixedDtr) {
try {
field.setAccessible(true);
field.set(dc, fixedDtr);
} catch (IllegalAccessException e) {
LOGGER.warning("Could not change text renderer. Labels in WordWind view might not be correct.");
} finally {
field.setAccessible(false);
}
}
private static Field getTextRendererField() {
Field field = null;
try {
field = DrawContextImpl.class.getDeclaredField("declutteringTextRenderer");
} catch (NoSuchFieldException e) {
LOGGER.warning("Could not retrieve declutteringTextRenderer. Labels in WordWind view are not corrected.");
}
return field;
}
private static class NamesFixingTextRenderer extends DeclutteringTextRenderer {
private final Map<String, String> nameMap;
public NamesFixingTextRenderer(Map<String, String> nameMap) {
this.nameMap = nameMap;
}
@Override
public void render(DrawContext dc, Iterable<? extends GeographicText> textIterable) {
final Iterator<? extends GeographicText> iterator = textIterable.iterator();
List<GeographicText> geoTextList = new ArrayList<>();
while (iterator.hasNext()) {
GeographicText geoText = iterator.next();
final String currentName = geoText.getText().toString();
if (nameMap.containsKey(currentName)) {
geoText.setText(nameMap.get(currentName));
}
geoTextList.add(geoText);
}
super.render(dc, geoTextList);
}
}
}
| 4,200 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WWLayerRegistry.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/layers/WWLayerRegistry.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.layers;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.util.SystemUtils;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.modules.ModuleInfo;
import org.openide.util.Lookup;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A <code>WWLayerRegistry</code> provides access to WorldWind Layers as described by their WWLayerDescriptor.
*/
public class WWLayerRegistry {
private static WWLayerRegistry instance = null;
private final Map<String, WWLayerDescriptor> wwLayerDescriptors = new HashMap<>();
public WWLayerRegistry() {
registerWWLayers();
}
public static WWLayerRegistry getInstance() {
if (instance == null) {
instance = new WWLayerRegistry();
}
return instance;
}
public WWLayerDescriptor[] getWWLayerDescriptors() {
return wwLayerDescriptors.values().toArray(new WWLayerDescriptor[wwLayerDescriptors.values().size()]);
}
private void registerWWLayers() {
final FileObject fileObj = FileUtil.getConfigFile("WorldWindLayers");
if (fileObj == null) {
SystemUtils.LOG.warning("No World Wind layers found.");
return;
}
final FileObject[] files = fileObj.getChildren();
final List<FileObject> orderedFiles = FileUtil.getOrder(Arrays.asList(files), true);
for (FileObject file : orderedFiles) {
WWLayerDescriptor WWLayerDescriptor = null;
try {
WWLayerDescriptor = createWWLayerDescriptor(file);
} catch (Exception e) {
SystemUtils.LOG.severe(String.format("Failed to create WWLayerDescriptor from layer.xml path '%s'", file.getPath()));
}
if (WWLayerDescriptor != null) {
final WWLayerDescriptor existingDescriptor = wwLayerDescriptors.get(WWLayerDescriptor.getId());
if (existingDescriptor != null) {
SystemUtils.LOG.warning(String.format("WWLayer [%s] has been redeclared!\n",
WWLayerDescriptor.getId()));
}
wwLayerDescriptors.put(WWLayerDescriptor.getId(), WWLayerDescriptor);
SystemUtils.LOG.fine(String.format("New WWLayer added from layer.xml path '%s': %s",
file.getPath(), WWLayerDescriptor.getId()));
}
}
}
public static WWLayerDescriptor createWWLayerDescriptor(final FileObject fileObject) {
final String id = fileObject.getName();
final String showInWorldMapToolView = (String) fileObject.getAttribute("showInWorldMapToolView");
final String showIn3DToolView = (String) fileObject.getAttribute("showIn3DToolView");
final Class<? extends WWLayer> WWLayerClass = getClassAttribute(fileObject, "WWLayerClass", WWLayer.class, false);
Assert.argument(showInWorldMapToolView != null &&
(showInWorldMapToolView.equalsIgnoreCase("true") || showInWorldMapToolView.equalsIgnoreCase("false")),
"Missing attribute 'showInWorldMapToolView'");
Assert.argument(showIn3DToolView != null &&
(showIn3DToolView.equalsIgnoreCase("true") || showIn3DToolView.equalsIgnoreCase("false")),
"Missing attribute 'showIn3DToolView'");
Assert.argument(WWLayerClass != null, "Attribute 'class' must be provided");
return new DefaultWWLayerDescriptor(id, Boolean.parseBoolean(showInWorldMapToolView),
Boolean.parseBoolean(showIn3DToolView), WWLayerClass);
}
public static <T> Class<T> getClassAttribute(final FileObject fileObject,
final String attributeName,
final Class<T> expectedType,
final boolean required) {
final String className = (String) fileObject.getAttribute(attributeName);
if (className == null || className.isEmpty()) {
if (required) {
throw new IllegalArgumentException(String.format("Missing attribute '%s' of type %s",
attributeName, expectedType.getName()));
}
return null;
}
final Collection<? extends ModuleInfo> modules = Lookup.getDefault().lookupAll(ModuleInfo.class);
for (ModuleInfo module : modules) {
if (module.isEnabled()) {
try {
final Class<?> implClass = module.getClassLoader().loadClass(className);
if (expectedType.isAssignableFrom(implClass)) {
//noinspection unchecked
return (Class<T>) implClass;
} else {
throw new IllegalArgumentException(String.format("Value %s of attribute '%s' must be a %s",
implClass.getName(),
attributeName,
expectedType.getName()));
}
} catch (ClassNotFoundException e) {
// it's ok, continue
}
}
}
return null;
}
}
| 6,383 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WWLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/layers/WWLayer.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.layers;
import gov.nasa.worldwind.awt.WorldWindowGLCanvas;
import gov.nasa.worldwind.event.SelectEvent;
import gov.nasa.worldwind.layers.Layer;
import org.esa.snap.core.datamodel.Product;
import javax.swing.JPanel;
/**
* World Wind renderable layer
*/
public interface WWLayer extends Layer {
void addProduct(Product product, WorldWindowGLCanvas wwd);
void removeProduct(Product product);
JPanel getControlPanel(WorldWindowGLCanvas wwd);
void setSelectedProduct(final Product product);
Product getSelectedProduct();
void updateInfoAnnotation(final SelectEvent event);
} | 1,357 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldWindOptionsPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/preferences/WorldWindOptionsPanel.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.preferences;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.runtime.Config;
import org.esa.snap.worldwind.WWWorldViewToolView;
import org.openide.awt.Mnemonics;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
final class WorldWindOptionsPanel extends javax.swing.JPanel {
private javax.swing.JCheckBox useFlatEarthCheckBox;
WorldWindOptionsPanel(final WorldWindOptionsPanelController controller) {
initComponents();
// listen to changes in form fields and call controller.changed()
useFlatEarthCheckBox.addItemListener(e -> controller.changed());
}
private void initComponents() {
useFlatEarthCheckBox = new javax.swing.JCheckBox();
Mnemonics.setLocalizedText(useFlatEarthCheckBox, "Use flat Earth projection");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(useFlatEarthCheckBox)
.addGap(0, 512, Short.MAX_VALUE)
).addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(useFlatEarthCheckBox)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addContainerGap())
);
}
void load() {
useFlatEarthCheckBox.setSelected(
Config.instance().preferences().getBoolean(WWWorldViewToolView.useFlatEarth, false));
}
void store() {
final Preferences preferences = Config.instance().preferences();
preferences.putBoolean(WWWorldViewToolView.useFlatEarth, useFlatEarthCheckBox.isSelected());
try {
preferences.flush();
} catch (BackingStoreException e) {
SnapApp.getDefault().getLogger().severe(e.getMessage());
}
}
boolean valid() {
// Check whether form is consistent and complete
return true;
}
}
| 3,350 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldWindOptionsPanelController.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/preferences/WorldWindOptionsPanelController.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.worldwind.preferences;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.*;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
@OptionsPanelController.SubRegistration(location = "GeneralPreferences",
displayName = "#LBL_WorldWindOption_DisplayName",
keywords = "#LBL_WorldWindOption_Keywords",
keywordsCategory = "WorldWind",
id = "WorldWindOptionsPanelController",
position = 8
)
@org.openide.util.NbBundle.Messages({
"LBL_WorldWindOption_DisplayName=World View",
"LBL_WorldWindOption_Keywords=WorldWind,Globe,World,Map"
})
public class WorldWindOptionsPanelController extends OptionsPanelController {
private WorldWindOptionsPanel panel;
private final PropertyChangeSupport pcs = new PropertyChangeSupport(this);
private boolean changed;
public void update() {
getPanel().load();
changed = false;
}
public void applyChanges() {
SwingUtilities.invokeLater(() -> {
getPanel().store();
changed = false;
});
}
public void cancel() {
// need not do anything special, if no changes have been persisted yet
}
public boolean isValid() {
return getPanel().valid();
}
public boolean isChanged() {
return changed;
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx("WorldWind");
}
public JComponent getComponent(Lookup masterLookup) {
return getPanel();
}
public void addPropertyChangeListener(PropertyChangeListener l) {
pcs.addPropertyChangeListener(l);
}
public void removePropertyChangeListener(PropertyChangeListener l) {
pcs.removePropertyChangeListener(l);
}
private WorldWindOptionsPanel getPanel() {
if (panel == null) {
panel = new WorldWindOptionsPanel(this);
}
return panel;
}
void changed() {
if (!changed) {
changed = true;
pcs.firePropertyChange(OptionsPanelController.PROP_CHANGED, false, true);
}
pcs.firePropertyChange(OptionsPanelController.PROP_VALID, null, null);
}
}
| 3,026 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 1110) package org.esa.snap.worldwind.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 158 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PolygonMouseListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/PolygonMouseListener.java | package org.esa.snap.worldwind.productlibrary;
import java.awt.geom.Path2D;
import java.util.List;
/**
* The listener interface for receiving left mouse click events.
*
* Created by jcoravu on 11/9/2019.
*/
public interface PolygonMouseListener {
public void leftMouseButtonClicked(List<Path2D.Double> polygonPaths);
}
| 330 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PolygonsLayerModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/PolygonsLayerModel.java | package org.esa.snap.worldwind.productlibrary;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
/**
* The layer containing the polygon coordinates of the repository products.
*
* Created by jcoravu on 10/9/2019.
*/
public class PolygonsLayerModel {
private final Collection<CustomPolyline> renderables;
public PolygonsLayerModel() {
this.renderables = new ArrayList<>();
}
public List<Path2D.Double> findPolygonsContainsPoint(double longitude, double latitude) {
List<Path2D.Double> polygonPaths = new ArrayList<>();
Iterator<CustomPolyline> it1 = this.renderables.iterator();
while (it1.hasNext()) {
CustomPolyline polyline = it1.next();
if (polyline.getPath().contains(longitude, latitude)) {
polygonPaths.add(polyline.getPath());
}
}
return polygonPaths;
}
public Collection<CustomPolyline> getRenderables() {
return renderables;
}
public void setPolygons(Path2D.Double[] polygonPaths) {
List<CustomPolyline> polygonsToRemove = new ArrayList<>();
Iterator<CustomPolyline> it1 = this.renderables.iterator();
while (it1.hasNext()) {
CustomPolyline polyline = it1.next();
boolean found = false;
for (int i=0; i<polygonPaths.length && !found; i++) {
if (polyline.getPath() == polygonPaths[i]) {
found = true;
}
}
if (!found) {
polygonsToRemove.add(polyline);
}
}
for (int i=0; i<polygonsToRemove.size(); i++) {
this.renderables.remove(polygonsToRemove.get(i));
}
for (int i=0; i<polygonPaths.length; i++) {
Iterator<CustomPolyline> it2 = this.renderables.iterator();
boolean found = false;
while (it2.hasNext() && !found) {
CustomPolyline polyline = it2.next();
if (polyline.getPath() == polygonPaths[i]) {
found = true;
}
}
if (!found) {
CustomPolyline polyline = new CustomPolyline(polygonPaths[i]);
polyline.setFollowTerrain(true);
polyline.setColor(WorldMapPanelWrapper.POLYGON_BORDER_COLOR);
polyline.setHighlightColor(WorldMapPanelWrapper.POLYGON_HIGHLIGHT_BORDER_COLOR);
polyline.setLineWidth(WorldMapPanelWrapper.POLYGON_LINE_WIDTH);
this.renderables.add(polyline);
}
}
}
public void highlightPolygons(Path2D.Double[] polygonPaths) {
Iterator<CustomPolyline> it1 = this.renderables.iterator();
while (it1.hasNext()) {
CustomPolyline polyline = it1.next();
boolean found = false;
for (int i=0; i<polygonPaths.length && !found; i++) {
if (polyline.getPath() == polygonPaths[i]) {
found = true;
}
}
if (!found) {
polyline.setHighlighted(false);
}
}
for (int i=0; i<polygonPaths.length; i++) {
highlightPolygon(polygonPaths[i]);
}
}
private boolean highlightPolygon(Path2D.Double polygonPath) {
Iterator<CustomPolyline> it = this.renderables.iterator();
while (it.hasNext()) {
CustomPolyline polyline = it.next();
if (polyline.getPath() == polygonPath) {
polyline.setHighlighted(true);
return true; // the polygon exists
}
}
return false;
}
}
| 3,752 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMapPanelWrapper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/WorldMapPanelWrapper.java | package org.esa.snap.worldwind.productlibrary;
import gov.nasa.worldwind.geom.Position;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.ui.loading.CircularProgressIndicatorLabel;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.util.List;
/**
* The panel containing the earth globe.
*/
public abstract class WorldMapPanelWrapper extends JPanel {
private static final String PREFERENCES_KEY_LAST_WORLD_MAP_PANEL = "last_world_map_panel";
private static final int WORLD_MAP_2D_FLAT_EARTH = 1;
private static final int WORLD_MAP_3D_FLAT_EARTH = 2;
private static final int WORLD_MAP_3D_GLOBE_EARTH = 3;
public static final float SELECTION_LINE_WIDTH = 1.5f;
public final static Color SELECTION_FILL_COLOR = new Color(255, 255, 0, 70);
public final static Color SELECTION_BORDER_COLOR = new Color(255, 255, 0, 255);
public static final float POLYGON_LINE_WIDTH = 1.0f;
public final static Color POLYGON_BORDER_COLOR = Color.WHITE;
public final static Color POLYGON_HIGHLIGHT_BORDER_COLOR = Color.RED;
public static final Cursor SELECTION_CURSOR = Cursor.getPredefinedCursor(1);
public static final Cursor DEFAULT_CURSOR = Cursor.getDefaultCursor();
protected final PolygonsLayerModel polygonsLayerModel;
private final WorldMap2DPanel worldMap2DPanel;
private WorldMap3DPanel worldMap3DPanel;
private WorldMap currentWorldMap;
private PolygonMouseListener mouseListener;
private final PropertyMap persistencePreferences;
protected WorldMapPanelWrapper(PolygonMouseListener mouseListener, Color backgroundColor, PropertyMap persistencePreferences) {
super(new GridBagLayout());
this.mouseListener = mouseListener;
this.persistencePreferences = persistencePreferences;
setBackground(backgroundColor);
setOpaque(true);
setBorder(SwingUtils.LINE_BORDER);
this.polygonsLayerModel = new PolygonsLayerModel();
this.worldMap2DPanel = new WorldMap2DPanel(this.polygonsLayerModel);
this.worldMap2DPanel.setOpaque(false);
CircularProgressIndicatorLabel circularProgressLabel = new CircularProgressIndicatorLabel();
circularProgressLabel.setOpaque(false);
circularProgressLabel.setRunning(true);
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, 0, 0);
add(circularProgressLabel, c);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
this.worldMap2DPanel.setEnabled(enabled);
if (this.worldMap3DPanel != null) {
this.worldMap3DPanel.setEnabled(enabled);
}
}
public abstract void addWorldMapPanelAsync(boolean flat3DEarth, boolean removeExtraLayers);
public void clearSelectedArea() {
if (this.currentWorldMap != null) {
this.currentWorldMap.disableSelection();
}
}
public void setSelectedArea(Rectangle2D selectedArea) {
if (this.currentWorldMap != null) {
this.currentWorldMap.setSelectedArea(selectedArea);
this.currentWorldMap.refresh();
}
}
public Rectangle2D getSelectedArea() {
if (this.currentWorldMap != null) {
return this.currentWorldMap.getSelectedArea();
}
return null;
}
public void setEyePosition(Path2D.Double polygonPath) {
if (this.currentWorldMap != null) {
if (this.currentWorldMap == this.worldMap3DPanel) {
Rectangle2D rectangleBounds = polygonPath.getBounds2D();
if (rectangleBounds == null) {
throw new NullPointerException("The rectangle bounds is null.");
}
Position eyePosition = this.worldMap3DPanel.getView().getEyePosition();
if (eyePosition == null) {
throw new NullPointerException("The eye position is null.");
}
Position position = Position.fromDegrees(rectangleBounds.getCenterY(), rectangleBounds.getCenterX(), eyePosition.getElevation());
this.worldMap3DPanel.getView().setEyePosition(position);
this.worldMap3DPanel.redrawNow();
} else if (this.currentWorldMap == this.worldMap2DPanel) {
// do nothing
} else {
throw new IllegalStateException("The world map type '"+this.currentWorldMap + "' is unknown.");
}
}
}
public void highlightPolygons(Path2D.Double[] polygonPaths) {
this.polygonsLayerModel.highlightPolygons(polygonPaths);
if (this.currentWorldMap != null) {
this.currentWorldMap.refresh();
}
}
public void setPolygons(Path2D.Double[] polygonPaths) {
this.polygonsLayerModel.setPolygons(polygonPaths);
if (this.currentWorldMap != null) {
this.currentWorldMap.refresh();
}
}
public void refresh(){
if (worldMap3DPanel != null) {
worldMap3DPanel.initializeBackend(false);
worldMap3DPanel.reshape(0, 0, 0, 0);
worldMap3DPanel.revalidate();
}
}
private void processLeftMouseClick(MouseEvent mouseEvent) {
Point.Double clickedPoint = this.currentWorldMap.convertPointToDegrees(mouseEvent.getPoint());
if (clickedPoint != null) {
List<Path2D.Double> polygonPaths = this.polygonsLayerModel.findPolygonsContainsPoint(clickedPoint.getX(), clickedPoint.getY());
this.mouseListener.leftMouseButtonClicked(polygonPaths);
}
}
private void processRightMouseClick(MouseEvent mouseEvent) {
WorldMap worldMap = (WorldMap)mouseEvent.getSource();
JMenuItem selectionMenuItem;
if (worldMap.getSelectedArea() != null) {
selectionMenuItem = new JMenuItem("Clear selection");
selectionMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
JMenuItem menuItem = (JMenuItem)actionEvent.getSource();
WorldMap inputWorldMap = (WorldMap)menuItem.getClientProperty(menuItem);
inputWorldMap.disableSelection();
}
});
} else {
selectionMenuItem = new JMenuItem("Start selection");
selectionMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
JMenuItem menuItem = (JMenuItem)actionEvent.getSource();
WorldMap inputWorldMap = (WorldMap)menuItem.getClientProperty(menuItem);
inputWorldMap.enableSelection();
}
});
}
selectionMenuItem.putClientProperty(selectionMenuItem, worldMap);
JMenu viewMenu = new JMenu("View");
if (worldMap == this.worldMap2DPanel) {
viewMenu.add(buildView3DGlobe());
viewMenu.add(buildView3DFlatEarth());
} else if (worldMap == this.worldMap3DPanel) {
if (this.worldMap3DPanel.isGlobeEarth()) {
viewMenu.add(buildView3DFlatEarth());
} else {
viewMenu.add(buildView3DGlobe());
}
JMenuItem viewFlatEarthMenuItem = new JMenuItem("2D Flat Earth");
viewFlatEarthMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
addWorldMapPanel(worldMap2DPanel, WORLD_MAP_2D_FLAT_EARTH);
}
});
viewMenu.add(viewFlatEarthMenuItem);
}
JPopupMenu popup = new JPopupMenu();
popup.add(selectionMenuItem);
popup.add(viewMenu);
popup.show((JPanel)worldMap, mouseEvent.getX(), mouseEvent.getY());
}
private JMenuItem buildView3DFlatEarth() {
JMenuItem viewFlatEarthMenuItem = new JMenuItem("3D Flat Earth");
viewFlatEarthMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
worldMap3DPanel.setFlatEarth();
addWorldMapPanel(worldMap3DPanel, WORLD_MAP_3D_FLAT_EARTH);
}
});
return viewFlatEarthMenuItem;
}
private JMenuItem buildView3DGlobe() {
JMenuItem viewGlobeMenuItem = new JMenuItem("3D Globe");
viewGlobeMenuItem.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent actionEvent) {
worldMap3DPanel.setGlobeEarth();
addWorldMapPanel(worldMap3DPanel, WORLD_MAP_3D_GLOBE_EARTH);
}
});
return viewGlobeMenuItem;
}
private void addWorldMapPanel(JPanel worldMapPanel, Integer worldMapPanelId) {
Rectangle2D selectedArea = null;
if (this.currentWorldMap != null) {
selectedArea = this.currentWorldMap.getSelectedArea();
}
this.currentWorldMap = (WorldMap)worldMapPanel;
this.currentWorldMap.setSelectedArea(selectedArea);
removeAll();
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 1, 1, 0, 0);
add(worldMapPanel, c);
Container parent = getParent();
if (parent != null) {
parent.revalidate();
parent.repaint();
}
refresh();
// save the world map panel to the preferences
if (worldMapPanelId != null) {
this.persistencePreferences.setPropertyInt(PREFERENCES_KEY_LAST_WORLD_MAP_PANEL, worldMapPanelId.intValue());
}
}
public void addWorldWindowPanel(WorldMap3DPanel worldMap3DPanel) {
MouseAdapter mouseAdapter = new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent mouseEvent) {
if (isEnabled()) {
if (SwingUtilities.isRightMouseButton(mouseEvent)) {
processRightMouseClick(mouseEvent);
} else if (SwingUtilities.isLeftMouseButton(mouseEvent)) {
processLeftMouseClick(mouseEvent);
}
}
}
};
this.worldMap2DPanel.addMouseListener(mouseAdapter);
JPanel worldMapPanel;
if (worldMap3DPanel == null) {
// the world map 3D panel has not been loaded
worldMapPanel = this.worldMap2DPanel;
} else {
// the world map 3d panel has been loaded
this.worldMap3DPanel = worldMap3DPanel;
this.worldMap3DPanel.setOpaque(false);
this.worldMap3DPanel.addMouseListener(mouseAdapter);
worldMapPanel = this.worldMap3DPanel;
}
Integer lastWorldMapPanelId = this.persistencePreferences.getPropertyInt(PREFERENCES_KEY_LAST_WORLD_MAP_PANEL, null);
if (lastWorldMapPanelId != null) {
if (lastWorldMapPanelId.intValue() == WORLD_MAP_2D_FLAT_EARTH) {
worldMapPanel = this.worldMap2DPanel;
} else if (lastWorldMapPanelId.intValue() == WORLD_MAP_3D_FLAT_EARTH) {
this.worldMap3DPanel.setFlatEarth();
worldMapPanel = this.worldMap3DPanel;
} else if (lastWorldMapPanelId.intValue() == WORLD_MAP_3D_GLOBE_EARTH) {
this.worldMap3DPanel.setGlobeEarth();
worldMapPanel = this.worldMap3DPanel;
}
}
addWorldMapPanel(worldMapPanel, null);
}
}
| 12,019 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMap3DPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/WorldMap3DPanel.java | package org.esa.snap.worldwind.productlibrary;
import gov.nasa.worldwind.Configuration;
import gov.nasa.worldwind.Model;
import gov.nasa.worldwind.SceneController;
import gov.nasa.worldwind.WorldWind;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.awt.WorldWindowGLJPanel;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.globes.Earth;
import gov.nasa.worldwind.globes.EarthFlat;
import gov.nasa.worldwind.layers.CompassLayer;
import gov.nasa.worldwind.layers.Earth.LandsatI3WMSLayer;
import gov.nasa.worldwind.layers.Layer;
import gov.nasa.worldwind.layers.LayerList;
import gov.nasa.worldwind.layers.SkyGradientLayer;
import gov.nasa.worldwind.layers.StarsLayer;
import gov.nasa.worldwind.layers.WorldMapLayer;
import gov.nasa.worldwind.pick.PickedObjectList;
import gov.nasa.worldwind.render.DrawContext;
import gov.nasa.worldwind.util.BasicGLCapabilitiesChooser;
import gov.nasa.worldwind.view.orbit.BasicOrbitView;
import gov.nasa.worldwind.view.orbit.FlatOrbitView;
import org.esa.snap.worldwind.layers.FixingPlaceNameLayer;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.geom.Rectangle2D;
import java.lang.reflect.Field;
/**
* The panel containing the 3D earth globe.
*
* Created by jcoravu on 2/9/2019.
*/
public class WorldMap3DPanel extends WorldWindowGLJPanel implements WorldMap {
private final Rectangle3DSelection selector;
public WorldMap3DPanel(boolean flatEarth, boolean removeExtraLayers, PolygonsLayerModel polygonsLayerModel) {
super(null, Configuration.getRequiredGLCapabilities(), new BasicGLCapabilitiesChooser());
// create the default model as described in the current world wind properties
Model model = (Model) WorldWind.createConfigurationComponent(AVKey.MODEL_CLASS_NAME);
setModel(model);
if (flatEarth) {
setFlatEarth();
} else {
setGlobeEarth();
}
this.selector = new Rectangle3DSelection(this.wwd) {
@Override
protected void setCursor(Cursor cursor) {
WorldMap3DPanel.this.setCursor((cursor == null) ? WorldMapPanelWrapper.DEFAULT_CURSOR : cursor);
}
};
this.selector.setInteriorColor(WorldMapPanelWrapper.SELECTION_FILL_COLOR);
this.selector.setBorderColor(WorldMapPanelWrapper.SELECTION_BORDER_COLOR);
this.selector.setBorderWidth(WorldMapPanelWrapper.SELECTION_LINE_WIDTH);
this.selector.getLayer().setEnabled(true);
LayerList layerList = this.wwd.getModel().getLayers();
if (removeExtraLayers) {
for (Layer layer : layerList) {
if (layer instanceof CompassLayer || layer instanceof WorldMapLayer || layer instanceof StarsLayer
|| layer instanceof LandsatI3WMSLayer || layer instanceof SkyGradientLayer) {
layerList.remove(layer);
}
}
}
// Instead of the default Place Name layer we use special implementation to replace
// wrong names in the original layer. https://senbox.atlassian.net/browse/SNAP-1476
final Layer placeNameLayer = layerList.getLayerByName("Place Names");
layerList.remove(placeNameLayer);
final FixingPlaceNameLayer fixingPlaceNameLayer = new FixingPlaceNameLayer();
layerList.add(fixingPlaceNameLayer);
fixingPlaceNameLayer.setEnabled(true);
layerList.add(this.selector.getLayer());
layerList.add(new Polygons3DLayer(polygonsLayerModel));
}
@Override
public void setSelectedArea(Rectangle2D selectedArea) {
this.selector.setSelectedArea(selectedArea);
}
@Override
public void refresh() {
redrawNow();
}
@Override
public void enableSelection() {
this.selector.enable();
}
@Override
public void disableSelection() {
this.selector.disable();
}
@Override
public Rectangle2D getSelectedArea() {
return this.selector.getSelectedArea();
}
@Override
public Point.Double convertPointToDegrees(Point point) {
SceneController sceneController = getSceneController();
Point pickPoint = sceneController.getPickPoint();
if (pickPoint != null && pickPoint.getX() == point.getX() && pickPoint.getY() == point.getY()) {
PickedObjectList pickedObjectList = sceneController.getPickedObjectList();
if (pickedObjectList != null && pickedObjectList.size() > 0) {
Position position = (Position) pickedObjectList.get(0).getObject();
return new Point.Double(position.getLongitude().getDegrees(), position.getLatitude().getDegrees());
}
}
return null;
}
public void setGlobeEarth() {
getModel().setGlobe(new Earth());
setView(new BasicOrbitView());
}
public void setFlatEarth() {
getModel().setGlobe(new EarthFlat());
setView(new FlatOrbitView());
}
public boolean isGlobeEarth() {
return (getModel().getGlobe() instanceof Earth);
}
void setBackgroundColor(Color backgroundColor) {
DrawContext drawContext = getSceneController().getDrawContext();
Color color = drawContext.getClearColor();
setValueByReflection(color, "value", backgroundColor.getRGB());
}
private static boolean setValueByReflection(Object object, String fieldName, Object fieldValue) {
Class<?> clazz = object.getClass();
while (clazz != null) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
return true;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
return false;
}
}
| 6,012 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomPolyline.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/CustomPolyline.java | package org.esa.snap.worldwind.productlibrary;
import gov.nasa.worldwind.geom.Angle;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.render.Polyline;
import java.awt.geom.Path2D;
import java.awt.geom.PathIterator;
import java.util.ArrayList;
import java.util.List;
/**
* The class stores the coordinate of a polyline.
*
* Created by jcoravu on 11/9/2019.
*/
public class CustomPolyline extends Polyline {
private final Path2D.Double path;
public CustomPolyline(Path2D.Double path) {
this.path = path;
List<Position> positions = new ArrayList<>();
double[] coordinates = new double[2];
PathIterator pathIterator = this.path.getPathIterator(null);
pathIterator.currentSegment(coordinates);
Position firstPosition = new Position(Angle.fromDegreesLatitude(coordinates[1]), Angle.fromDegreesLongitude(coordinates[0]), 0.0d);
positions.add(firstPosition);
pathIterator.next();
while (!pathIterator.isDone()) {
pathIterator.currentSegment(coordinates);
Position position = new Position(Angle.fromDegreesLatitude(coordinates[1]), Angle.fromDegreesLongitude(coordinates[0]), 0.0d);
positions.add(position);
pathIterator.next();
}
setPositions(positions);
}
public Path2D.Double getPath() {
return path;
}
}
| 1,397 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMap2DPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/WorldMap2DPanel.java | package org.esa.snap.worldwind.productlibrary;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.grender.Rendering;
import org.esa.snap.remote.products.repository.geometry.GeometryUtils;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
/**
* The panel containing the 2D earth globe.
*
* Created by jcoravu on 21/10/2019.
*/
public class WorldMap2DPanel extends LayerCanvas implements WorldMap {
private static final LayerType LAYER_TYPE = LayerTypeRegistry.getLayerType("org.esa.snap.worldmap.BlueMarbleLayerType");
private final Map2DMouseHandler map2DSelector;
public WorldMap2DPanel(PolygonsLayerModel polygonsLayerModel) {
super();
getModel().getViewport().setModelYAxisDown(false);
this.map2DSelector = new Map2DMouseHandler(this);
addMouseListener(this.map2DSelector);
addMouseMotionListener(this.map2DSelector);
addMouseWheelListener(this.map2DSelector);
addOverlay(new SelectionAreaOverlay());
addOverlay(new Polygons2DLayer(polygonsLayerModel));
Layer rootLayer = getLayer();
Layer worldMapLayer = LAYER_TYPE.createLayer(new WorldMapLayerContext(rootLayer), new PropertyContainer());
rootLayer.getChildren().add(worldMapLayer);
getViewport().zoom(worldMapLayer.getModelBounds());
}
@Override
public void setSelectedArea(Rectangle2D selectedArea) {
this.map2DSelector.setSelectedArea(selectedArea);
}
@Override
public void refresh() {
repaint();
}
@Override
public void enableSelection() {
this.map2DSelector.enable();
}
@Override
public void disableSelection() {
this.map2DSelector.disable();
}
@Override
public Rectangle2D getSelectedArea() {
return this.map2DSelector.getSelectedArea();
}
@Override
public Point.Double convertPointToDegrees(Point point) {
AffineTransform viewToModelTransform = getViewport().getViewToModelTransform();
Point.Double clickedPoint = new Point.Double();
viewToModelTransform.transform(point, clickedPoint);
return clickedPoint;
}
private static class WorldMapLayerContext implements LayerContext {
private final Layer rootLayer;
private WorldMapLayerContext(Layer rootLayer) {
this.rootLayer = rootLayer;
}
@Override
public Object getCoordinateReferenceSystem() {
return DefaultGeographicCRS.WGS84;
}
@Override
public Layer getRootLayer() {
return rootLayer;
}
}
private class SelectionAreaOverlay implements LayerCanvas.Overlay {
public SelectionAreaOverlay() {
}
@Override
public void paintOverlay(LayerCanvas canvas, Rendering rendering) {
Rectangle2D selectionArea = map2DSelector.getSelectedArea();
if (selectionArea != null) {
Graphics2D g2d = rendering.getGraphics();
AffineTransform transform = canvas.getViewport().getModelToViewTransform();
Path2D.Double path = GeometryUtils.buildPath(selectionArea);
path.transform(transform);
g2d.setColor(WorldMapPanelWrapper.SELECTION_FILL_COLOR);
g2d.fill(path);
g2d.setColor(WorldMapPanelWrapper.SELECTION_BORDER_COLOR);
g2d.setStroke(new BasicStroke(WorldMapPanelWrapper.SELECTION_LINE_WIDTH));
g2d.draw(path);
}
}
}
}
| 3,896 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Map2DMouseHandler.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/Map2DMouseHandler.java | package org.esa.snap.worldwind.productlibrary;
import com.bc.ceres.glayer.swing.LayerCanvas;
import org.apache.commons.math3.util.FastMath;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
/**
* Adapter class for receiving mouse events for 2D earth globe.
*
* Created by jcoravu on 21/10/2019.
*/
public class Map2DMouseHandler extends MouseAdapter {
private final LayerCanvas layerCanvas;
private Point mousePressedPosition;
private Point.Double selectionStart;
private Point.Double selectionEnd;
public Map2DMouseHandler(LayerCanvas layerCanvas) {
this.layerCanvas = layerCanvas;
setDefaultCursor();
}
@Override
public void mouseWheelMoved(MouseWheelEvent mouseWheelEvent) {
int wheelRotation = -mouseWheelEvent.getWheelRotation();
double newZoomFactor = this.layerCanvas.getViewport().getZoomFactor() * FastMath.pow(1.1, wheelRotation);
this.layerCanvas.getViewport().setZoomFactor(newZoomFactor);
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
if (SwingUtilities.isLeftMouseButton(mouseEvent)) {
if (isSelectionCursor()) {
AffineTransform viewToModelTransform = this.layerCanvas.getViewport().getViewToModelTransform();
this.selectionStart = new Point.Double();
this.selectionEnd = null;
viewToModelTransform.transform(mouseEvent.getPoint(), this.selectionStart);
this.layerCanvas.updateUI();
}
this.mousePressedPosition = mouseEvent.getPoint();
} else if (SwingUtilities.isRightMouseButton(mouseEvent)) {
this.mousePressedPosition = mouseEvent.getPoint();
}
}
@Override
public void mouseReleased(MouseEvent mouseEvent) {
this.mousePressedPosition = null;
setDefaultCursor();
}
@Override
public void mouseDragged(MouseEvent mouseEvent) {
if (this.mousePressedPosition != null) {
if (isSelectionCursor()) {
AffineTransform viewToModelTransform = this.layerCanvas.getViewport().getViewToModelTransform();
Point.Double selectionPoint = new Point.Double();
viewToModelTransform.transform(mouseEvent.getPoint(), selectionPoint);
if (selectionPoint.x >= -180.0d && selectionPoint.y <= 90.0d) {
if (selectionPoint.x <= 180.0d && selectionPoint.y >= -90.0d) {
this.selectionEnd = selectionPoint;
this.layerCanvas.updateUI();
}
}
} else {
Point newMouseDraggedPosition = mouseEvent.getPoint();
double dx = newMouseDraggedPosition.x - this.mousePressedPosition.x;
double dy = newMouseDraggedPosition.y - this.mousePressedPosition.y;
this.layerCanvas.getViewport().moveViewDelta(dx, dy);
this.mousePressedPosition = newMouseDraggedPosition;
}
}
}
public void setSelectedArea(Rectangle2D selectedArea) {
if (selectedArea == null) {
this.selectionStart = null;
this.selectionEnd = null;
} else {
this.selectionStart = new Point.Double(selectedArea.getX(), selectedArea.getY());
this.selectionEnd = new Point.Double(selectedArea.getX() + selectedArea.getWidth(), selectedArea.getY() + selectedArea.getHeight());
}
}
public Rectangle2D getSelectedArea() {
if (this.selectionStart != null && this.selectionEnd != null) {
if (this.selectionStart.x > this.selectionEnd.x || this.selectionStart.y > this.selectionEnd.y) {
double x = this.selectionEnd.x;
double y = this.selectionEnd.y;
double width = this.selectionStart.x - this.selectionEnd.x;
double height = this.selectionStart.y - this.selectionEnd.y;
return new Rectangle2D.Double(x, y, width, height);
}
double x = this.selectionStart.x;
double y = this.selectionStart.y;
double width = this.selectionEnd.x - this.selectionStart.x;
double height = this.selectionEnd.y - this.selectionStart.y;
return new Rectangle2D.Double(x, y, width, height);
}
return null;
}
public void enable() {
setSelectionCursor();
}
public void disable() {
setDefaultCursor();
this.selectionStart = null;
this.selectionEnd = null;
this.layerCanvas.updateUI();
}
private boolean isSelectionCursor() {
return (this.layerCanvas.getCursor() == WorldMapPanelWrapper.SELECTION_CURSOR);
}
private void setSelectionCursor() {
this.layerCanvas.setCursor(WorldMapPanelWrapper.SELECTION_CURSOR);
}
private void setDefaultCursor() {
this.layerCanvas.setCursor(WorldMapPanelWrapper.DEFAULT_CURSOR);
}
} | 5,176 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Polygons2DLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/Polygons2DLayer.java | package org.esa.snap.worldwind.productlibrary;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.grender.Rendering;
import java.awt.BasicStroke;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;
import java.util.Iterator;
/**
* The polygons layer for 3D earth globe.
*
* Created by jcoravu on 10/9/2019.
*/
public class Polygons2DLayer implements LayerCanvas.Overlay {
private final PolygonsLayerModel polygonsLayerModel;
public Polygons2DLayer(PolygonsLayerModel polygonsLayerModel) {
this.polygonsLayerModel = polygonsLayerModel;
}
@Override
public void paintOverlay(LayerCanvas canvas, Rendering rendering) {
Iterator<CustomPolyline> iterator = this.polygonsLayerModel.getRenderables().iterator();
Graphics2D g2d = rendering.getGraphics();
AffineTransform modelToViewTransform = canvas.getViewport().getModelToViewTransform();
while (iterator.hasNext()) {
CustomPolyline polygon = iterator.next();
Path2D.Double path = (Path2D.Double) polygon.getPath().clone();
path.transform(modelToViewTransform);
if (polygon.isHighlighted()) {
g2d.setColor(WorldMapPanelWrapper.POLYGON_HIGHLIGHT_BORDER_COLOR);
g2d.setStroke(new BasicStroke(WorldMapPanelWrapper.POLYGON_LINE_WIDTH * 2.0f));
g2d.draw(path);
}
g2d.setColor(WorldMapPanelWrapper.POLYGON_BORDER_COLOR);
g2d.setStroke(new BasicStroke(WorldMapPanelWrapper.POLYGON_LINE_WIDTH));
g2d.draw(path);
}
}
}
| 1,640 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMap.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/WorldMap.java | package org.esa.snap.worldwind.productlibrary;
import java.awt.*;
import java.awt.geom.Rectangle2D;
/**
* The interface contains method to access information from an world panel.
*
* Created by jcoravu on 22/10/2019.
*/
public interface WorldMap {
public Point.Double convertPointToDegrees(Point point);
public void setSelectedArea(Rectangle2D selectedArea);
public void refresh();
public void enableSelection();
public void disableSelection();
public Rectangle2D getSelectedArea();
}
| 521 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Polygons3DLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/Polygons3DLayer.java | package org.esa.snap.worldwind.productlibrary;
import gov.nasa.worldwind.layers.AbstractLayer;
import gov.nasa.worldwind.render.DrawContext;
import gov.nasa.worldwind.render.Renderable;
import java.util.Iterator;
/**
* The polygons layer for 3D earth globe.
*
* Created by jcoravu on 10/9/2019.
*/
public class Polygons3DLayer extends AbstractLayer {
private final PolygonsLayerModel polygonsLayerModel;
public Polygons3DLayer(PolygonsLayerModel polygonsLayerModel) {
this.polygonsLayerModel = polygonsLayerModel;
}
@Override
protected void doRender(DrawContext drawContext) {
Iterator<CustomPolyline> var3 = this.polygonsLayerModel.getRenderables().iterator();
while(var3.hasNext()) {
Renderable renderable = var3.next();
renderable.render(drawContext);
}
}
}
| 852 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Rectangle3DSelection.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/productlibrary/Rectangle3DSelection.java | package org.esa.snap.worldwind.productlibrary;
import gov.nasa.worldwind.WorldWindow;
import gov.nasa.worldwind.geom.Sector;
import gov.nasa.worldwind.layers.LayerList;
import gov.nasa.worldwindx.examples.util.SectorSelector;
import java.awt.geom.Rectangle2D;
/**
* The class stores the coordinates of the selected area for a 3D earth globe.
*
* Created by jcoravu on 22/10/2019.
*/
public class Rectangle3DSelection extends SectorSelector {
public Rectangle3DSelection(WorldWindow worldWindow) {
super(worldWindow);
}
public void setSelectedArea(Rectangle2D selectedArea) {
addSelectionLayerIfMissing();
Sector newSector;
if (selectedArea == null) {
newSector = Sector.EMPTY_SECTOR;
} else {
newSector = Sector.fromDegrees(selectedArea);
}
getShape().setSector(newSector);
}
public Rectangle2D getSelectedArea() {
Sector sector = getShape().getSector();
if (sector == Sector.EMPTY_SECTOR) {
return null; // no selected area
}
return sector.toRectangleDegrees();
}
@Override
public void enable() {
super.enable();
setCursor(WorldMapPanelWrapper.SELECTION_CURSOR);
}
@Override
public void disable() {
super.disable();
setCursor(WorldMapPanelWrapper.DEFAULT_CURSOR);
}
private void addSelectionLayerIfMissing() {
LayerList layers = this.getWwd().getModel().getLayers();
if(!layers.contains(this.getLayer())) {
layers.add(this.getLayer());
}
if(!this.getLayer().isEnabled()) {
this.getLayer().setEnabled(true);
}
}
}
| 1,705 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ModuleInstaller.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-sta-adapters/src/main/java/org/esa/snap/utils/ModuleInstaller.java | /*
*
* * Copyright (C) 2015 CS SI
* *
* * This program is free software; you can redistribute it and/or modify it
* * under the terms of the GNU General Public License as published by the Free
* * Software Foundation; either version 3 of the License, or (at your option)
* * any later version.
* * This program is distributed in the hope that it will be useful, but WITHOUT
* * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* * more details.
* *
* * You should have received a copy of the GNU General Public License along
* * with this program; if not, see http://www.gnu.org/licenses/
*
*/
package org.esa.snap.utils;
import org.esa.snap.core.gpf.descriptor.ToolAdapterOperatorDescriptor;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterIO;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterOpSpi;
import org.esa.snap.core.gpf.operators.tooladapter.ToolAdapterRegistry;
import org.esa.snap.modules.ModulePackager;
import org.esa.snap.ui.tooladapter.actions.ToolAdapterActionRegistrar;
import org.openide.modules.ModuleInstall;
import org.openide.modules.Places;
import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Logger;
/**
* Tool Adapter module installer class for NetBeans.
* and menu entries.
*
* @author Cosmin Cara
*/
public class ModuleInstaller extends ModuleInstall {
private final static String descriptionKeyName = "OpenIDE-Module-Short-Description";
private final static Attributes.Name typeKey = new Attributes.Name("OpenIDE-Module-Type");
private final static FilenameFilter jarFilter = (dir, name) -> name.endsWith("jar");
private final Logger logger = Logger.getGlobal();
private final Path nbUserModulesPath = Paths.get(Places.getUserDirectory().getAbsolutePath(), "modules");
private final File userModulePath = ToolAdapterIO.getUserAdapterPath();
@Override
public void restored() {
String jarFile = getCurrentJarPath();
if (jarFile != null) {
File unpackLocation = processJarFile(new File(jarFile));
if (unpackLocation != null) {
registerAdapterAction(ToolAdapterIO.registerAdapter(unpackLocation));
} else {
logger.warning(String.format("Jar %s could not be unpacked. See previous exception.", jarFile));
}
} else {
Map<String, File> jarAdapters = getJarAdapters(nbUserModulesPath.toFile());
jarAdapters.keySet().stream().forEach(key -> {
File destination = new File(userModulePath, key);
processJarFile(destination);
});
synchronized (ToolAdapterIO.class) {
Collection<ToolAdapterOpSpi> toolAdapterOpSpis = ToolAdapterIO.searchAndRegisterAdapters();
toolAdapterOpSpis.forEach(this::registerAdapterAction);
}
}
}
@Override
public void uninstalled() {
logger.info("Uninstalling module");
String jarFile = getCurrentJarPath();
if (jarFile != null) {
try {
logger.info("Jar file: " + jarFile);
String alias = ModulePackager.getAdapterAlias(new File(jarFile));
logger.info("Alias: " + alias);
ToolAdapterOpSpi spi = ToolAdapterRegistry.INSTANCE.getOperatorMap().values()
.stream()
.filter(d -> alias.equals(d.getOperatorAlias()))
.findFirst().get();
if (spi != null) {
final ToolAdapterOperatorDescriptor descriptor = (ToolAdapterOperatorDescriptor) spi.getOperatorDescriptor();
//ToolAdapterActionRegistrar.removeOperatorMenu(descriptor);
ToolAdapterIO.removeOperator(descriptor);
}
} catch (IOException e) {
logger.warning(e.getMessage());
}
} else {
logger.info("No jar found");
}
}
private Map<String, File> getJarAdapters(File fromPath) {
Map<String, File> output = new HashMap<>();
File[] files = fromPath.listFiles(jarFilter);
if (files != null) {
logger.info(String.format("Found %s packed user module" + (files.length > 1 ? "s" : ""), String.valueOf(files.length)));
try {
for (File file : files) {
JarFile jarFile = new JarFile(file);
Manifest manifest = jarFile.getManifest();
Attributes manifestEntries = manifest.getMainAttributes();
if (manifestEntries.containsKey(typeKey) &&
"STA".equals(manifestEntries.getValue(typeKey.toString()))) {
logger.info(String.format("Module %s was detected as a STA module", file.getName()));
output.put(manifestEntries.getValue(descriptionKeyName), file);
}
}
} catch (Exception e) {
logger.severe(e.getMessage());
}
}
return output;
}
private String getCurrentJarPath() {
String path = null;
try {
URL url = this.getClass().getProtectionDomain().getCodeSource().getLocation();
JarURLConnection connection = (JarURLConnection) url.openConnection();
JarFile jarFile = connection.getJarFile();
path = jarFile.getName();
} catch (IOException e) {
logger.severe(e.getMessage());
}
return path;
}
private File processJarFile(File jarFile) {
String unpackPath = jarFile.getName().replace(".jar", "");
try {
unpackPath = ModulePackager.getAdapterAlias(jarFile);
} catch (IOException e) {
logger.warning(e.getMessage());
}
File destination = new File(userModulePath, unpackPath);
try{
if (!destination.exists()) {
ModulePackager.unpackAdapterJar(jarFile, destination);
} else {
File versionFile = new File(destination, "version.txt");
if (versionFile.exists()) {
String versionText = new String(Files.readAllBytes(Paths.get(versionFile.toURI()))); //FileUtils.readText(versionFile);
String jarVersion = ModulePackager.getAdapterVersion(jarFile);
if (jarVersion != null && !versionText.equals(jarVersion)) {
ModulePackager.unpackAdapterJar(jarFile, destination);
logger.info(String.format("The adapter with the name %s and version %s was replaced by version %s", unpackPath, versionText, jarVersion));
} else {
logger.info(String.format("An adapter with the name %s and version %s already exists", unpackPath, versionText));
}
} else {
ModulePackager.unpackAdapterJar(jarFile, destination);
}
}
} catch (Exception e) {
logger.severe(e.getMessage());
}
return destination;
}
private void registerAdapterAction(ToolAdapterOpSpi opSpi) {
ToolAdapterOperatorDescriptor operatorDescriptor = (ToolAdapterOperatorDescriptor) opSpi.getOperatorDescriptor();
if (operatorDescriptor != null) {
ToolAdapterActionRegistrar.registerOperatorMenu(operatorDescriptor);
}
}
}
| 7,961 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractMoveLayerTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/AbstractMoveLayerTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.product.ProductSceneView;
import org.junit.Before;
import org.junit.Test;
import java.awt.Window;
import static junit.framework.Assert.*;
/**
* todo - add API doc
*
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
public class AbstractMoveLayerTest {
/*
TreeStructure:
layer0
|- layer1
|- layer2
|- layer3
|- layer4
|- layer5
|- layer6
|- layer7
*/
protected Layer layer0;
protected Layer layer1;
protected Layer layer2;
protected Layer layer3;
protected Layer layer4;
protected Layer layer5;
protected Layer layer6;
protected Layer layer7;
@Before
public void setupTreeModel() {
layer0 = createLayer("layer0");
layer1 = createLayer("layer1");
layer2 = createLayer("layer2");
layer3 = createLayer("layer3");
layer4 = createLayer("layer4");
layer5 = createLayer("layer5");
layer6 = createLayer("layer6");
layer7 = createLayer("layer7");
layer0.getChildren().add(layer1);
layer0.getChildren().add(layer2);
layer0.getChildren().add(layer3);
layer3.getChildren().add(layer4);
layer3.getChildren().add(layer5);
layer0.getChildren().add(layer6);
layer6.getChildren().add(layer7);
}
@Test
public void testDummy() {
assertEquals(true, true);
}
private static Layer createLayer(String id) {
final Layer layer = new CollectionLayer();
layer.setId(id);
layer.setName(id);
return layer;
}
static class DummyAppContext implements AppContext {
@Override
public String getApplicationName() {
return null;
}
@Override
public Window getApplicationWindow() {
return null;
}
@Override
public Product getSelectedProduct() {
return null;
}
@Override
public void handleError(String message, Throwable e) {
}
@Override
public PropertyMap getPreferences() {
return null;
}
@Override
public ProductManager getProductManager() {
return null;
}
@Override
public ProductSceneView getSelectedProductSceneView() {
return null;
}
}
}
| 3,537 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerRightActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/MoveLayerRightActionTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
public class MoveLayerRightActionTest extends AbstractMoveLayerTest {
/*
TreeStructure:
layer0
|- layer1
|- layer2
|- layer3
|- layer4
|- layer5
|- layer6
|- layer7
*/
private MoveLayerRightAction layerRightAction;
@Override
@Before
public void setupTreeModel() {
super.setupTreeModel();
layerRightAction = new MoveLayerRightAction();
}
@Test
public void testMoveLayer1Right() {
layerRightAction.moveRight(layer1); // Not possible; no place to move to
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
}
@Test
public void testMoveLayer2Right() {
layerRightAction.moveRight(layer2); // Not possible; no place to move to
Assert.assertEquals(3, layer0.getChildren().size());
Assert.assertEquals(0, layer1.getChildIndex("layer2"));
}
@Test
public void testMoveLayer3Right() {
layerRightAction.moveRight(layer3);
Assert.assertEquals(3, layer0.getChildren().size());
Assert.assertSame(layer1, layer0.getChildren().get(0));
Assert.assertSame(layer2, layer0.getChildren().get(1));
Assert.assertSame(layer6, layer0.getChildren().get(2));
Assert.assertEquals(1, layer2.getChildren().size());
Assert.assertSame(layer3, layer2.getChildren().get(0));
Assert.assertEquals(0, layer2.getChildIndex("layer3"));
Assert.assertSame(layer7, layer6.getChildren().get(0));
}
@Test
public void testMoveLayer4Right() {
layerRightAction.moveRight(layer4); // Not possible; no place to move to
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(2, layer3.getChildren().size());
Assert.assertEquals(2, layer0.getChildIndex("layer3"));
}
@Test
public void testMoveLayer6Right() {
layerRightAction.moveRight(layer6);
Assert.assertEquals(3, layer0.getChildren().size());
Assert.assertEquals(3, layer3.getChildren().size());
Assert.assertEquals(0, layer3.getChildIndex("layer4"));
Assert.assertEquals(1, layer3.getChildIndex("layer5"));
Assert.assertEquals(2, layer3.getChildIndex("layer6"));
}
} | 3,363 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerDownActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/MoveLayerDownActionTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
public class MoveLayerDownActionTest extends AbstractMoveLayerTest {
/*
TreeStructure:
layer0
|- layer1
|- layer2
|- layer3
|- layer4
|- layer5
|- layer6
|- layer7
*/
private MoveLayerDownAction layerDownAction;
@Override
@Before
public void setupTreeModel() {
super.setupTreeModel();
layerDownAction = new MoveLayerDownAction();
}
@Test
public void testMoveLayer2Down() {
layerDownAction.moveDown(layer2);
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
Assert.assertEquals(1, layer0.getChildIndex("layer3"));
Assert.assertEquals(2, layer0.getChildIndex("layer2"));
Assert.assertEquals(3, layer0.getChildIndex("layer6"));
}
@Test
public void testMoveLayer4Down() {
layerDownAction.moveDown(layer4);
Assert.assertEquals(2, layer3.getChildren().size());
Assert.assertEquals(0, layer3.getChildIndex("layer5"));
Assert.assertEquals(1, layer3.getChildIndex("layer4"));
}
@Test
public void testMoveLayer6Down() { // Not possible it's already the last node
layerDownAction.moveDown(layer6);
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
Assert.assertEquals(1, layer0.getChildIndex("layer2"));
Assert.assertEquals(2, layer0.getChildIndex("layer3"));
Assert.assertEquals(3, layer0.getChildIndex("layer6"));
}
} | 2,640 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerUpActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/MoveLayerUpActionTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
public class MoveLayerUpActionTest extends AbstractMoveLayerTest {
/*
TreeStructure:
layer0
|- layer1
|- layer2
|- layer3
|- layer4
|- layer5
|- layer6
|- layer7
*/
private MoveLayerUpAction layerUpAction;
@Override
@Before
public void setupTreeModel() {
super.setupTreeModel();
layerUpAction = new MoveLayerUpAction();
}
@Test
public void testMoveLayer1Up() {
layerUpAction.moveUp(layer1); // Not possible it's already the first node
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
}
@Test
public void testMoveLayer3Up() {
layerUpAction.moveUp(layer3);
Assert.assertEquals(2, layer3.getChildren().size());
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
Assert.assertEquals(1, layer0.getChildIndex("layer3"));
Assert.assertEquals(2, layer0.getChildIndex("layer2"));
}
@Test
public void testMoveLayer5Up() {
layerUpAction.moveUp(layer5);
Assert.assertEquals(2, layer3.getChildren().size());
Assert.assertEquals(0, layer3.getChildIndex("layer5"));
Assert.assertEquals(1, layer3.getChildIndex("layer4"));
}
@Test
public void testMoveLayer6Up() {
layerUpAction.moveUp(layer6);
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
Assert.assertEquals(1, layer0.getChildIndex("layer2"));
Assert.assertEquals(2, layer0.getChildIndex("layer6"));
Assert.assertEquals(3, layer0.getChildIndex("layer3"));
}
}
| 2,832 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerTreeModelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/LayerTreeModelTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.support.LayerUtils;
import org.junit.Test;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
public class LayerTreeModelTest {
@Test
public void testIt() {
Layer layer0 = new CollectionLayer();
Layer layer1 = new CollectionLayer();
Layer layer2 = new CollectionLayer();
Layer layer3 = new CollectionLayer();
layer0.getChildren().add(layer1);
layer0.getChildren().add(layer2);
layer0.getChildren().add(layer3);
Layer layer4 = new CollectionLayer();
Layer layer5 = new CollectionLayer();
layer3.getChildren().add(layer4);
layer3.getChildren().add(layer5);
LayerTreeModel treeModel = new LayerTreeModel(layer0);
assertSame(layer0, treeModel.getRoot());
Layer[] path = LayerUtils.getLayerPath(layer0, layer0);
assertNotNull(path);
assertEquals(1, path.length);
assertSame(layer0, path[0]);
path = LayerUtils.getLayerPath(layer3, layer4);
assertNotNull(path);
assertEquals(2, path.length);
assertSame(layer3, path[0]);
assertSame(layer4, path[1]);
path = LayerUtils.getLayerPath(layer0, layer4);
assertNotNull(path);
assertEquals(3, path.length);
assertSame(layer0, path[0]);
assertSame(layer3, path[1]);
assertSame(layer4, path[2]);
path = LayerUtils.getLayerPath(layer4, layer3);
assertNotNull(path);
assertEquals(0, path.length);
assertEquals(3, treeModel.getChildCount(layer0));
assertSame(layer1, treeModel.getChild(layer0, 0));
assertSame(layer2, treeModel.getChild(layer0, 1));
assertSame(layer3, treeModel.getChild(layer0, 2));
assertEquals(0, treeModel.getChildCount(layer1));
assertEquals(0, treeModel.getChildCount(layer2));
assertEquals(2, treeModel.getChildCount(layer3));
assertSame(layer4, treeModel.getChild(layer3, 0));
assertSame(layer5, treeModel.getChild(layer3, 1));
final MyTreeModelListener listener = new MyTreeModelListener();
treeModel.addTreeModelListener(listener);
final List<Layer> children = layer3.getChildren();
children.remove(layer4);
try {
SwingUtilities.invokeAndWait(() -> {
assertEquals("treeStructureChanged;", listener.trace);
});
} catch (InterruptedException | InvocationTargetException e) {
// ok
}
}
private static class MyTreeModelListener implements TreeModelListener {
String trace = "";
TreeModelEvent e;
public void treeNodesChanged(TreeModelEvent e) {
trace += "treeNodesChanged;";
this.e = e;
}
public void treeNodesInserted(TreeModelEvent e) {
trace += "treeNodesInserted;";
this.e = e;
}
public void treeNodesRemoved(TreeModelEvent e) {
trace += "treeNodesRemoved;";
this.e = e;
}
public void treeStructureChanged(TreeModelEvent e) {
trace += "treeStructureChanged;";
this.e = e;
}
}
}
| 4,327 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerLeftActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/MoveLayerLeftActionTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
*
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
public class MoveLayerLeftActionTest extends AbstractMoveLayerTest {
/*
TreeStructure:
layer0
|- layer1
|- layer2
|- layer3
|- layer4
|- layer5
|- layer6
|- layer7
*/
private MoveLayerLeftAction layerLeftAction;
@Override
@Before
public void setupTreeModel() {
super.setupTreeModel();
layerLeftAction = new MoveLayerLeftAction();
}
@Test
public void testMoveLayer2Left() {
layerLeftAction.moveLeft(layer2); // Not possible; no parent to move to
Assert.assertEquals(4, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
Assert.assertEquals(1, layer0.getChildIndex("layer2"));
Assert.assertEquals(2, layer0.getChildIndex("layer3"));
Assert.assertEquals(3, layer0.getChildIndex("layer6"));
}
@Test
public void testMoveLayer4Left() {
layerLeftAction.moveLeft(layer4);
Assert.assertEquals(5, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
Assert.assertEquals(1, layer0.getChildIndex("layer2"));
Assert.assertEquals(2, layer0.getChildIndex("layer3"));
Assert.assertEquals(3, layer0.getChildIndex("layer4"));
Assert.assertEquals(4, layer0.getChildIndex("layer6"));
}
@Test
public void testMoveLayer7Left() {
layerLeftAction.moveLeft(layer7);
Assert.assertEquals(5, layer0.getChildren().size());
Assert.assertEquals(0, layer0.getChildIndex("layer1"));
Assert.assertEquals(1, layer0.getChildIndex("layer2"));
Assert.assertEquals(2, layer0.getChildIndex("layer3"));
Assert.assertEquals(3, layer0.getChildIndex("layer6"));
Assert.assertEquals(4, layer0.getChildIndex("layer7"));
}
} | 2,888 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
HistoryComboBoxModelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/layersrc/HistoryComboBoxModelTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.layersrc;
import org.esa.snap.ui.UserInputHistory;
import org.junit.Test;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.BackingStoreException;
import java.util.prefs.NodeChangeListener;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import static org.junit.Assert.*;
public class HistoryComboBoxModelTest {
@Test
public void testAddElement() {
final HistoryComboBoxModel model = new HistoryComboBoxModel(new UserInputHistory(3, "historyItem"));
assertEquals(0, model.getSize());
model.setSelectedItem("one");
assertEquals(1, model.getSize());
model.setSelectedItem("two");
model.setSelectedItem("three");
assertEquals(3, model.getSize());
assertEquals("three", model.getElementAt(0));
assertEquals("two", model.getElementAt(1));
assertEquals("one", model.getElementAt(2));
model.setSelectedItem("four");
assertEquals(3, model.getSize());
assertEquals("four", model.getElementAt(0));
assertEquals("three", model.getElementAt(1));
assertEquals("two", model.getElementAt(2));
model.setSelectedItem("five");
assertEquals(3, model.getSize());
assertEquals("five", model.getElementAt(0));
assertEquals("four", model.getElementAt(1));
assertEquals("three", model.getElementAt(2));
}
@Test
public void testAddElementWithInnitilaizedProperties() {
final Preferences preferences = new DummyPreferences();
preferences.put("historyItem.0", "one");
preferences.put("historyItem.1", "two");
final UserInputHistory history = new UserInputHistory(3, "historyItem");
history.initBy(preferences);
final HistoryComboBoxModel model = new HistoryComboBoxModel(history);
assertEquals(2, model.getSize());
assertEquals("one", model.getElementAt(0));
assertEquals("two", model.getElementAt(1));
model.setSelectedItem("three");
assertEquals(3, model.getSize());
assertEquals("three", model.getElementAt(0));
assertEquals("one", model.getElementAt(1));
assertEquals("two", model.getElementAt(2));
model.setSelectedItem("four");
assertEquals(3, model.getSize());
assertEquals("four", model.getElementAt(0));
assertEquals("three", model.getElementAt(1));
assertEquals("one", model.getElementAt(2));
}
@Test
public void testValidation() {
final Preferences preferences = new DummyPreferences();
preferences.put("historyItem.0", "one");
preferences.put("historyItem.1", "two");
preferences.put("historyItem.2", "three");
final UserInputHistory history = new UserInputHistory(3, "historyItem") {
@Override
protected boolean isValidItem(String item) {
return "two".equals(item);
}
};
history.initBy(preferences);
final HistoryComboBoxModel model = new HistoryComboBoxModel(history);
assertEquals(1, model.getSize());
assertEquals("two", model.getElementAt(0));
}
@Test
public void testSetSelected() {
final Preferences preferences = new DummyPreferences();
preferences.put("historyItem.0", "one");
preferences.put("historyItem.1", "two");
final UserInputHistory history = new UserInputHistory(3, "historyItem");
history.initBy(preferences);
final HistoryComboBoxModel model = new HistoryComboBoxModel(history);
assertEquals(2, model.getSize());
assertEquals("one", model.getElementAt(0));
assertEquals("two", model.getElementAt(1));
model.setSelectedItem("two");
assertEquals(2, model.getSize());
assertEquals("two", model.getElementAt(0));
assertEquals("one", model.getElementAt(1));
model.setSelectedItem("three");
assertEquals(3, model.getSize());
assertEquals("three", model.getElementAt(0));
assertEquals("two", model.getElementAt(1));
assertEquals("one", model.getElementAt(2));
model.setSelectedItem("one");
assertEquals(3, model.getSize());
assertEquals("one", model.getElementAt(0));
assertEquals("three", model.getElementAt(1));
assertEquals("two", model.getElementAt(2));
model.setSelectedItem("four");
assertEquals(3, model.getSize());
assertEquals("four", model.getElementAt(0));
assertEquals("one", model.getElementAt(1));
assertEquals("three", model.getElementAt(2));
}
@Test
public void testSetSelectedOnEmptyHistory() {
final HistoryComboBoxModel model = new HistoryComboBoxModel(new UserInputHistory(3, "historyItem"));
assertEquals(0, model.getSize());
model.setSelectedItem("one");
assertEquals(1, model.getSize());
assertEquals("one", model.getElementAt(0));
model.setSelectedItem("two");
assertEquals(2, model.getSize());
assertEquals("two", model.getElementAt(0));
assertEquals("one", model.getElementAt(1));
}
@Test
public void testLoadHistory() {
final Preferences preferences = new DummyPreferences();
preferences.put("historyItem.0", "one");
final UserInputHistory history = new UserInputHistory(3, "historyItem");
history.initBy(preferences);
final HistoryComboBoxModel model = new HistoryComboBoxModel(history);
assertEquals(1, model.getSize());
preferences.put("historyItem.1", "two");
preferences.put("historyItem.2", "three");
model.getHistory().initBy(preferences);
assertEquals(3, model.getSize());
assertEquals("one", model.getElementAt(0));
assertEquals("two", model.getElementAt(1));
assertEquals("three", model.getElementAt(2));
}
@Test
public void testLoadHistoryOverwritesCurrentModel() {
final Preferences preferences = new DummyPreferences();
preferences.put("historyItem.0", "one");
final UserInputHistory history = new UserInputHistory(3, "historyItem");
history.initBy(preferences);
final HistoryComboBoxModel model = new HistoryComboBoxModel(history);
assertEquals(1, model.getSize());
model.setSelectedItem("two");
model.setSelectedItem("three");
assertEquals(3, model.getSize());
preferences.put("historyItem.1", "two2");
preferences.put("historyItem.2", "three3");
model.getHistory().initBy(preferences);
assertEquals(3, model.getSize());
assertEquals("one", model.getElementAt(0));
assertEquals("two2", model.getElementAt(1));
assertEquals("three3", model.getElementAt(2));
}
@Test
public void testSaveHistory() {
final HistoryComboBoxModel model = new HistoryComboBoxModel(new UserInputHistory(3, "historyItem"));
model.setSelectedItem("one");
model.setSelectedItem("two");
final Preferences preferences = new DummyPreferences();
model.getHistory().copyInto(preferences);
assertEquals("two", preferences.get("historyItem.0", ""));
assertEquals("one", preferences.get("historyItem.1", ""));
assertEquals("", preferences.get("historyItem.2", ""));
model.setSelectedItem("three");
model.getHistory().copyInto(preferences);
assertEquals("three", preferences.get("historyItem.0", ""));
assertEquals("two", preferences.get("historyItem.1", ""));
assertEquals("one", preferences.get("historyItem.2", ""));
}
private class DummyPreferences extends Preferences {
Map<String, Object> propertyMap;
DummyPreferences() {
propertyMap = new HashMap<String, Object>();
}
@Override
public void put(String key, String value) {
propertyMap.put(key, value);
}
@Override
public String get(String key, String def) {
final Object value = propertyMap.get(key);
if (value != null) {
return value.toString();
}
return def;
}
@Override
public void remove(String key) {
}
@Override
public void clear() throws BackingStoreException {
}
@Override
public void putInt(String key, int value) {
propertyMap.put(key, value);
}
@Override
public int getInt(String key, int def) {
final Object value = propertyMap.get(key);
if (value != null) {
return Integer.parseInt(value.toString());
}
return def;
}
@Override
public void putLong(String key, long value) {
}
@Override
public long getLong(String key, long def) {
return 0;
}
@Override
public void putBoolean(String key, boolean value) {
}
@Override
public boolean getBoolean(String key, boolean def) {
return false;
}
@Override
public void putFloat(String key, float value) {
}
@Override
public float getFloat(String key, float def) {
return 0;
}
@Override
public void putDouble(String key, double value) {
}
@Override
public double getDouble(String key, double def) {
return 0;
}
@Override
public void putByteArray(String key, byte[] value) {
}
@Override
public byte[] getByteArray(String key, byte[] def) {
return new byte[0];
}
@Override
public String[] keys() throws BackingStoreException {
return new String[0];
}
@Override
public String[] childrenNames() throws BackingStoreException {
return new String[0];
}
@Override
public Preferences parent() {
return null;
}
@Override
public Preferences node(String pathName) {
return null;
}
@Override
public boolean nodeExists(String pathName) throws BackingStoreException {
return false;
}
@Override
public void removeNode() throws BackingStoreException {
}
@Override
public String name() {
return null;
}
@Override
public String absolutePath() {
return null;
}
@Override
public boolean isUserNode() {
return false;
}
@Override
public String toString() {
return null;
}
@Override
public void flush() throws BackingStoreException {
}
@Override
public void sync() throws BackingStoreException {
}
@Override
public void addPreferenceChangeListener(PreferenceChangeListener pcl) {
}
@Override
public void removePreferenceChangeListener(PreferenceChangeListener pcl) {
}
@Override
public void addNodeChangeListener(NodeChangeListener ncl) {
}
@Override
public void removeNodeChangeListener(NodeChangeListener ncl) {
}
@Override
public void exportNode(OutputStream os) throws IOException, BackingStoreException {
}
@Override
public void exportSubtree(OutputStream os) throws IOException, BackingStoreException {
}
}
}
| 12,517 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WmsLayerConfigurationPersistencyTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsLayerConfigurationPersistencyTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.layersrc.wms;
import com.bc.ceres.binding.ConversionException;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.dom.DefaultDomElement;
import com.bc.ceres.binding.dom.DomElement;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.rcp.session.dom.SessionDomConverter;
import org.geotools.ows.wms.CRSEnvelope;
import org.junit.Before;
import org.junit.Test;
import java.awt.Dimension;
import java.io.File;
import java.lang.reflect.Array;
import java.net.MalformedURLException;
import java.net.URL;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertSame;
import static org.junit.Assert.assertNotNull;
public class WmsLayerConfigurationPersistencyTest {
private ProductManager productManager;
private Band band;
@Before
public void setup() {
Product product = new Product("P", "T", 10, 10);
product.setFileLocation(new File(String.format("out/%s.dim", product.getName())));
band = new VirtualBand("V", ProductData.TYPE_INT32, 10, 10, "42");
product.addBand(band);
productManager = new ProductManager();
productManager.addProduct(product);
}
@Test
public void testPersistency() throws ValidationException, ConversionException, MalformedURLException {
final WmsLayerType wmsLayerType = LayerTypeRegistry.getLayerType(WmsLayerType.class);
final PropertySet configuration = wmsLayerType.createLayerConfig(null);
configuration.setValue(WmsLayerType.PROPERTY_NAME_STYLE_NAME, "FancyStyle");
configuration.setValue(WmsLayerType.PROPERTY_NAME_URL, new URL("http://www.mapserver.org"));
configuration.setValue(WmsLayerType.PROPERTY_NAME_CRS_ENVELOPE, new CRSEnvelope("EPSG:4324", -10, 20, 15, 50));
configuration.setValue(WmsLayerType.PROPERTY_NAME_IMAGE_SIZE, new Dimension(200, 300));
configuration.setValue(WmsLayerType.PROPERTY_NAME_LAYER_INDEX, 12);
configuration.setValue(WmsLayerType.PROPERTY_NAME_RASTER, band);
final DomElement originalDomElement = new DefaultDomElement("configuration");
final SessionDomConverter domConverter = new SessionDomConverter(productManager);
//
domConverter.convertValueToDom(configuration, originalDomElement);
// For debug purposes
System.out.println(originalDomElement.toXml());
//
final PropertyContainer restoredConfiguration = (PropertyContainer) domConverter.convertDomToValue(originalDomElement,
wmsLayerType.createLayerConfig(null));
compareConfigurations(configuration, restoredConfiguration);
}
private static void compareConfigurations(PropertySet originalConfiguration,
PropertySet restoredConfiguration) {
for (final Property originalModel : originalConfiguration.getProperties()) {
final PropertyDescriptor originalDescriptor = originalModel.getDescriptor();
final Property restoredModel = restoredConfiguration.getProperty(originalDescriptor.getName());
final PropertyDescriptor restoredDescriptor = restoredModel.getDescriptor();
assertNotNull(restoredModel);
assertSame(originalDescriptor.getName(), restoredDescriptor.getName());
assertSame(originalDescriptor.getType(), restoredDescriptor.getType());
if (originalDescriptor.isTransient()) {
assertEquals(originalDescriptor.isTransient(), restoredDescriptor.isTransient());
} else {
final Object originalValue = originalModel.getValue();
final Object restoredValue = restoredModel.getValue();
assertSame(originalValue.getClass(), restoredValue.getClass());
if (originalValue.getClass().isArray()) {
final int originalLength = Array.getLength(originalValue);
final int restoredLength = Array.getLength(restoredValue);
assertEquals(originalLength, restoredLength);
for (int i = 0; i < restoredLength; i++) {
assertEquals(Array.get(originalValue, i), Array.get(restoredValue, i));
}
}
}
}
}
}
| 5,553 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WmsLayerTypeTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsLayerTypeTest.java | package org.esa.snap.rcp.layermanager.layersrc.wms;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.VirtualBand;
import org.geotools.ows.wms.CRSEnvelope;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import static org.junit.Assert.assertEquals;
public class WmsLayerTypeTest {
private static VirtualBand band;
@BeforeClass
public static void beforeClass() {
Product product = new Product("P", "T", 10, 10);
product.setFileLocation(new File(String.format("out/%s.dim", product.getName())));
band = new VirtualBand("V", ProductData.TYPE_INT32, 10, 10, "42");
product.addBand(band);
}
@Test
@Ignore
public void testLayerCreation() throws IOException {
// @todo 1 tb/** implement correct certificate handling, Java 9 changed the behaviour and is less graceful tb 2023-03-24
URL wmsUrl = new URL("http://geoservice.dlr.de/basemap/wms");
URLConnection urlConnection = wmsUrl.openConnection();
urlConnection.setConnectTimeout(1000);
boolean connected = false;
try {
urlConnection.connect();
connected = true;
} catch (Throwable ignore) {
}
Assume.assumeTrue(connected);
final CollectionLayer rootLayer = new CollectionLayer();
WmsLayerType wmsLayerType = new WmsLayerType();
TestDummyLayerContext ctx = new TestDummyLayerContext(rootLayer);
PropertySet layerConfig = wmsLayerType.createLayerConfig(ctx);
layerConfig.setValue(WmsLayerType.PROPERTY_NAME_URL, wmsUrl);
layerConfig.setValue(WmsLayerType.PROPERTY_NAME_IMAGE_SIZE, new Dimension(100, 100));
layerConfig.setValue(WmsLayerType.PROPERTY_NAME_CRS_ENVELOPE, new CRSEnvelope("EPSG:4324", -10, 20, 15, 50));
layerConfig.setValue(WmsLayerType.PROPERTY_NAME_RASTER, band);
layerConfig.setValue(WmsLayerType.PROPERTY_NAME_LAYER_INDEX, 12);
layerConfig.setValue(WmsLayerType.PROPERTY_NAME_STYLE_NAME, "default-style-osm_landusage");
Layer worldMapLayer = wmsLayerType.createLayer(ctx, layerConfig);
assertEquals("osm_landusage", worldMapLayer.getName());
}
private static class TestDummyLayerContext implements LayerContext {
private final Layer rootLayer;
private TestDummyLayerContext(Layer rootLayer) {
this.rootLayer = rootLayer;
}
@Override
public Object getCoordinateReferenceSystem() {
return DefaultGeographicCRS.WGS84;
}
@Override
public Layer getRootLayer() {
return rootLayer;
}
}
}
| 3,104 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FeatureFigureEditorApp.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/FeatureFigureEditorApp.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.layersrc.shapefile;
import com.bc.ceres.swing.demo.FigureEditorApp;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.FigureCollection;
import com.bc.ceres.swing.figure.FigureFactory;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.transform.MathTransform2D;
import org.esa.snap.ui.product.SimpleFeatureFigure;
import org.esa.snap.ui.product.SimpleFeatureFigureFactory;
import org.esa.snap.ui.product.SimpleFeaturePointFigure;
import org.esa.snap.ui.product.SimpleFeatureShapeFigure;
import org.geotools.data.DataStore;
import org.geotools.data.DataStoreFinder;
import org.geotools.data.FeatureSource;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class FeatureFigureEditorApp extends FigureEditorApp {
private final SimpleFeatureType featureType;
private final SceneTransformProvider sceneTransformProvider;
private FeatureFigureEditorApp() {
featureType = createSimpleFeatureType("X", Geometry.class, null);
sceneTransformProvider = new SceneTransformProvider() {
@Override
public MathTransform2D getModelToSceneTransform() {
return MathTransform2D.IDENTITY;
}
@Override
public MathTransform2D getSceneToModelTransform() {
return MathTransform2D.IDENTITY;
}
};
}
static class XYZ {
Class<?> geometryType;
SimpleFeatureType defaults;
ArrayList<SimpleFeature> features = new ArrayList<>();
}
private SimpleFeatureType createSimpleFeatureType(String typeName, Class<?> geometryType, SimpleFeatureType defaults) {
SimpleFeatureTypeBuilder sftb = new SimpleFeatureTypeBuilder();
if (defaults != null) {
//sftb.init(defaults);
}
DefaultGeographicCRS crs = DefaultGeographicCRS.WGS84;
sftb.setCRS(crs);
sftb.setName(typeName);
sftb.add("geom", geometryType);
sftb.add("style", String.class);
sftb.setDefaultGeometry("geom");
return sftb.buildFeatureType();
}
public static void main(String[] args) {
run(new FeatureFigureEditorApp());
}
@Override
protected FigureFactory getFigureFactory() {
return new SimpleFeatureFigureFactory(featureType, sceneTransformProvider);
}
@Override
protected void loadFigureCollection(File file, FigureCollection figureCollection) throws IOException {
FeatureSource<SimpleFeatureType, SimpleFeature> featureFeatureSource;
FeatureCollection<SimpleFeatureType, SimpleFeature> featureTypeSimpleFeatureFeatureCollection;
featureFeatureSource = getFeatureSource(file);
featureTypeSimpleFeatureFeatureCollection = featureFeatureSource.getFeatures();
try(FeatureIterator<SimpleFeature> featureIterator = featureTypeSimpleFeatureFeatureCollection.features();) {
while (featureIterator.hasNext()) {
SimpleFeature simpleFeature = featureIterator.next();
DefaultFigureStyle figureStyle = createDefaultFigureStyle();
Object o = simpleFeature.getDefaultGeometry();
if (o instanceof Point) {
figureCollection.addFigure(new SimpleFeaturePointFigure(simpleFeature, sceneTransformProvider, figureStyle));
} else {
figureCollection.addFigure(new SimpleFeatureShapeFigure(simpleFeature, sceneTransformProvider, figureStyle));
}
}
}
}
@Override
protected void storeFigureCollection(FigureCollection figureCollection, File file) throws IOException {
Figure[] figures = figureCollection.getFigures();
Map<Class<?>, List<SimpleFeature>> featureListMap = new HashMap<>();
for (Figure figure : figures) {
SimpleFeatureFigure simpleFeatureFigure = (SimpleFeatureFigure) figure;
SimpleFeature simpleFeature = simpleFeatureFigure.getSimpleFeature();
Class<?> geometryType = simpleFeature.getDefaultGeometry().getClass();
List<SimpleFeature> featureList = featureListMap.computeIfAbsent(geometryType, k -> new ArrayList<SimpleFeature>());
featureList.add(simpleFeature);
}
Set<Map.Entry<Class<?>, List<SimpleFeature>>> entries = featureListMap.entrySet();
for (Map.Entry<Class<?>, List<SimpleFeature>> entry : entries) {
Class<?> geomType = entry.getKey();
List<SimpleFeature> features = entry.getValue();
// ExportGeometryAction.writeEsriShapefile(geomType, features, file);
}
}
private static FeatureSource<SimpleFeatureType, SimpleFeature> getFeatureSource(File file) throws IOException {
Map<String, Object> map = new HashMap<String, Object>();
map.put(ShapefileDataStoreFactory.URLP.key, file.toURI().toURL());
map.put(ShapefileDataStoreFactory.CREATE_SPATIAL_INDEX.key, Boolean.TRUE);
DataStore shapefileStore = DataStoreFinder.getDataStore(map);
String typeName = shapefileStore.getTypeNames()[0]; // Shape files do only have one type name
FeatureSource<SimpleFeatureType, SimpleFeature> featureSource;
featureSource = shapefileStore.getFeatureSource(typeName);
return featureSource;
}
private static DefaultFigureStyle createDefaultFigureStyle() {
DefaultFigureStyle figureStyle = new DefaultFigureStyle();
figureStyle.setStrokeColor(Color.BLACK);
figureStyle.setStrokeWidth(1.0);
figureStyle.setFillColor(Color.WHITE);
return figureStyle;
}
}
| 7,073 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SnapUtilsTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/scripting/SnapUtilsTest.java | package org.esa.snap.rcp.scripting;
import org.junit.Test;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* @author Norman Fomferra
*/
public class SnapUtilsTest {
@Test
public void testAddRemoveAction() throws Exception {
AbstractAction realAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
FileObject actionFile = SnapUtils.addAction(realAction, "Test/Action");
assertNotNull(actionFile);
assertNotNull(actionFile.getParent());
assertEquals("application/x-nbsettings", actionFile.getMIMEType());
assertEquals("Test/Action", actionFile.getParent().getPath());
assertEquals("instance", actionFile.getExt());
Action action = FileUtil.getConfigObject(actionFile.getPath(), Action.class);
assertNotNull(action);
assertEquals(TransientAction.class, action.getClass());
assertSame(realAction, ((TransientAction) action).getDelegate());
boolean ok = SnapUtils.removeAction(actionFile);
assertEquals(true, ok);
action = FileUtil.getConfigObject(actionFile.getPath(), Action.class);
assertNull(action);
}
@Test
public void testAddRemoveActionReference() throws Exception {
AbstractAction realAction = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
FileObject actionFile = SnapUtils.addAction(realAction, "Test/Action");
FileObject actionRef1File = SnapUtils.addActionReference(actionFile, "Test/Refs1", 10);
assertNotNull(actionRef1File);
assertNotNull(actionRef1File.getParent());
assertEquals("Test/Refs1", actionRef1File.getParent().getPath());
assertEquals("shadow", actionRef1File.getExt());
assertEquals("content/unknown", actionRef1File.getMIMEType());
Action refAction = FileUtil.getConfigObject(actionRef1File.getPath(), Action.class);
assertNotNull(refAction);
assertEquals(TransientAction.class, refAction.getClass());
assertSame(realAction, ((TransientAction) refAction).getDelegate());
boolean ok = SnapUtils.removeActionReference(actionFile);
assertEquals(false, ok);
ok = SnapUtils.removeActionReference(actionRef1File);
assertEquals(true, ok);
refAction = FileUtil.getConfigObject(actionRef1File.getPath(), Action.class);
assertNull(refAction);
}
}
| 2,842 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TransientActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/scripting/TransientActionTest.java | package org.esa.snap.rcp.scripting;
import org.junit.Assert;
import org.junit.Test;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
/**
* @author Norman
*/
public class TransientActionTest {
@Test
public void testConstructor() throws Exception {
AbstractAction delegate = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
String path = "Test/X.instance";
TransientAction transientAction = new TransientAction(delegate, path);
assertSame(delegate, transientAction.getDelegate());
assertEquals(path, transientAction.getPath());
try {
new TransientAction(null, path);
Assert.fail();
} catch (NullPointerException ignored) {
}
try {
new TransientAction(delegate, null);
Assert.fail();
} catch (NullPointerException ignored) {
}
try {
new TransientAction(delegate, "Test/u");
Assert.fail();
} catch (IllegalArgumentException ignored) {
}
try {
new TransientAction(delegate, "u.instance");
Assert.fail();
} catch (IllegalArgumentException ignored) {
}
}
@Test
public void testProxyDelegatesAllCalls() throws Exception {
String[] actionCommand = new String[1];
AbstractAction delegate = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
actionCommand[0] = e.getActionCommand();
}
};
delegate.setEnabled(false);
TransientAction transientAction = new TransientAction(delegate, "Test/MyAction.instance");
// Enables state
assertEquals(false, delegate.isEnabled());
assertEquals(false, transientAction.isEnabled());
transientAction.setEnabled(true);
assertEquals(true, delegate.isEnabled());
assertEquals(true, transientAction.isEnabled());
// Property values
assertEquals(null, delegate.getValue("XXX"));
assertEquals(null, transientAction.getValue("XXX"));
transientAction.putValue("XXX", 3456);
assertEquals(3456, delegate.getValue("XXX"));
assertEquals(3456, transientAction.getValue("XXX"));
// Property changes
String[] name = new String[1];
transientAction.addPropertyChangeListener(evt -> {
name[0] = evt.getPropertyName();
});
assertEquals(null, name[0]);
transientAction.putValue("XXX", 9954);
assertEquals("XXX", name[0]);
delegate.putValue("YYY", 9954);
assertEquals("YYY", name[0]);
// Action
assertEquals(null, actionCommand[0]);
delegate.actionPerformed(new ActionEvent(this, 0, "cmd1"));
assertEquals("cmd1", actionCommand[0]);
transientAction.actionPerformed(new ActionEvent(this, 1, "cmd2"));
assertEquals("cmd2", actionCommand[0]);
}
}
| 3,153 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TransientTopComponentTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/scripting/TransientTopComponentTest.java | package org.esa.snap.rcp.scripting;
import org.junit.Assert;
import org.junit.Test;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.windows.TopComponent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
/**
* @author Norman
*/
public class TransientTopComponentTest {
@Test
public void testThatItNeverPersists() throws Exception {
TransientTopComponent tc = new TransientTopComponent() {
};
assertEquals(TopComponent.PERSISTENCE_NEVER, tc.getPersistenceType());
}
}
| 789 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumGraphTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/spectrum/SpectrumGraphTest.java | package org.esa.snap.rcp.spectrum;
import com.bc.ceres.annotation.STTM;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class SpectrumGraphTest {
@Test
@STTM("SNAP-3586")
public void testSetEnergies() {
final double[] energies = {0.34, 0.44, 0.26, 0.126, 0.55};
final SpectrumGraph spectrumGraph = new SpectrumGraph();
spectrumGraph.setEnergies(energies);
assertEquals(0.126, spectrumGraph.getYMin(), 1e-8);
assertEquals(0.55, spectrumGraph.getYMax(), 1e-8);
}
}
| 559 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumTopComponentTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/spectrum/SpectrumTopComponentTest.java | package org.esa.snap.rcp.spectrum;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.ui.product.spectrum.DisplayableSpectrum;
import org.esa.snap.ui.product.spectrum.SpectrumBand;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
import static junit.framework.TestCase.assertNotNull;
import static org.junit.Assert.assertSame;
/**
* @author Tonio Fincke
*/
public class SpectrumTopComponentTest {
@Test
public void testCreateSpectraFromUngroupedBands_noUnits() throws Exception {
final Band band_1 = new Band("cfsvbzt", ProductData.TYPE_INT8, 1, 1);
final Band band_2 = new Band("cgvg", ProductData.TYPE_INT8, 1, 1);
final Band band_3 = new Band("hbhn", ProductData.TYPE_INT8, 1, 1);
final Band band_4 = new Band("nhbjz", ProductData.TYPE_INT8, 1, 1);
final Band band_5 = new Band("tjbu", ProductData.TYPE_INT8, 1, 1);
SpectrumBand[] spectrumBands = new SpectrumBand[]{new SpectrumBand(band_1, false),
new SpectrumBand(band_2, false), new SpectrumBand(band_3, false),
new SpectrumBand(band_4, false), new SpectrumBand(band_5, false)
};
final DisplayableSpectrum[] spectraFromUngroupedBands =
SpectrumTopComponent.createSpectraFromUngroupedBands(spectrumBands, 1, 0);
assertNotNull(spectraFromUngroupedBands);
assertEquals(1, spectraFromUngroupedBands.length);
final Band[] spectralBands = spectraFromUngroupedBands[0].getSpectralBands();
assertEquals(DisplayableSpectrum.DEFAULT_SPECTRUM_NAME, spectraFromUngroupedBands[0].getName());
assertEquals(5, spectralBands.length);
assertSame(band_1, spectralBands[0]);
assertSame(band_2, spectralBands[1]);
assertSame(band_3, spectralBands[2]);
assertSame(band_4, spectralBands[3]);
assertSame(band_5, spectralBands[4]);
}
@Test
public void testCreateSpectraFromUngroupedBands() throws Exception {
final Band band_1 = new Band("cfsvbzt", ProductData.TYPE_INT8, 1, 1);
band_1.setUnit("dvgf");
final Band band_2 = new Band("cgvg", ProductData.TYPE_INT8, 1, 1);
band_2.setUnit("bzhui");
final Band band_3 = new Band("hbhn", ProductData.TYPE_INT8, 1, 1);
band_3.setUnit("drstf");
final Band band_4 = new Band("nhbjz", ProductData.TYPE_INT8, 1, 1);
band_4.setUnit("dvgf");
final Band band_5 = new Band("tjbu", ProductData.TYPE_INT8, 1, 1);
final Band band_6 = new Band("fgzvf", ProductData.TYPE_INT8, 1, 1);
band_6.setUnit("drstf");
SpectrumBand[] spectrumBands = new SpectrumBand[]{new SpectrumBand(band_1, false),
new SpectrumBand(band_2, false), new SpectrumBand(band_3, false),
new SpectrumBand(band_4, false), new SpectrumBand(band_5, false),
new SpectrumBand(band_6, false)
};
final DisplayableSpectrum[] spectraFromUngroupedBands =
SpectrumTopComponent.createSpectraFromUngroupedBands(spectrumBands, 1, 0);
assertNotNull(spectraFromUngroupedBands);
assertEquals(4, spectraFromUngroupedBands.length);
assertEquals("Bands measured in dvgf", spectraFromUngroupedBands[0].getName());
assertEquals(2, spectraFromUngroupedBands[0].getSpectralBands().length);
assertSame(band_1, spectraFromUngroupedBands[0].getSpectralBands()[0]);
assertSame(band_4, spectraFromUngroupedBands[0].getSpectralBands()[1]);
assertEquals("Bands measured in bzhui", spectraFromUngroupedBands[1].getName());
assertEquals(1, spectraFromUngroupedBands[1].getSpectralBands().length);
assertSame(band_2, spectraFromUngroupedBands[1].getSpectralBands()[0]);
assertEquals("Bands measured in drstf", spectraFromUngroupedBands[2].getName());
assertEquals(2, spectraFromUngroupedBands[2].getSpectralBands().length);
assertSame(band_3, spectraFromUngroupedBands[2].getSpectralBands()[0]);
assertSame(band_6, spectraFromUngroupedBands[2].getSpectralBands()[1]);
assertEquals(DisplayableSpectrum.REMAINING_BANDS_NAME, spectraFromUngroupedBands[3].getName());
assertEquals(1, spectraFromUngroupedBands[3].getSpectralBands().length);
assertSame(band_5, spectraFromUngroupedBands[3].getSpectralBands()[0]);
}
} | 4,426 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectraExportActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/spectrum/SpectraExportActionTest.java | package org.esa.snap.rcp.spectrum;
import com.bc.ceres.annotation.STTM;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
public class SpectraExportActionTest {
@Test
@STTM("SNAP-3586")
public void testGetEnergies() {
final Band[] bands = new Band[3];
bands[0] = new Band("one", ProductData.TYPE_INT32, 5, 5);
bands[1] = new Band("two", ProductData.TYPE_INT32, 5, 5);
bands[2] = new Band("three", ProductData.TYPE_INT32, 5, 5);
final Map<Band, Double> bandEnergyMap = new HashMap<>();
bandEnergyMap.put(bands[0], 0.0);
bandEnergyMap.put(bands[1], 1.0);
bandEnergyMap.put(bands[2], 2.0);
final double[] energies = SpectraExportAction.getEnergies(bands, bandEnergyMap);
assertEquals(0.0, energies[0], 1e-8);
assertEquals(1.0, energies[1], 1e-8);
assertEquals(2.0, energies[2], 1e-8);
}
}
| 1,060 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MaskFormTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/mask/MaskFormTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.mask;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Mask;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Assert;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import javax.swing.table.TableModel;
import java.awt.Color;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
public class MaskFormTest {
private Product product;
private MaskManagerForm maskManagerForm;
private MaskViewerForm maskViewerForm;
@Before
public void setUp() {
Assume.assumeFalse("Cannot run in headless", GraphicsEnvironment.isHeadless());
product = createTestProduct();
maskManagerForm = new MaskManagerForm(null, null);
maskManagerForm.reconfigureMaskTable(product, null);
maskViewerForm = new MaskViewerForm(null);
maskViewerForm.reconfigureMaskTable(product, null);
}
@Test
public void testMaskManagerForm() {
Assert.assertEquals(10, product.getMaskGroup().getNodeCount());
Assert.assertSame(product, maskManagerForm.getProduct());
Assert.assertNotNull(maskManagerForm.getHelpButton());
Assert.assertEquals("helpButton", maskManagerForm.getHelpButton().getName());
Assert.assertNotNull(maskManagerForm.createContentPanel());
Assert.assertEquals(10, maskManagerForm.getRowCount());
final TableModel tableModel = maskManagerForm.getMaskTable().getModel();
Assert.assertEquals(10, maskManagerForm.getRowCount());
Assert.assertEquals("M_1", tableModel.getValueAt(0, 0));
Assert.assertEquals("M_2", tableModel.getValueAt(1, 0));
Assert.assertEquals("M_3", tableModel.getValueAt(2, 0));
Assert.assertEquals("M_4", tableModel.getValueAt(3, 0));
Assert.assertEquals("M_5", tableModel.getValueAt(4, 0));
Assert.assertEquals("M_6", tableModel.getValueAt(5, 0));
Assert.assertEquals("M_7", tableModel.getValueAt(6, 0));
Assert.assertEquals("M_8", tableModel.getValueAt(7, 0));
Assert.assertEquals("M_9", tableModel.getValueAt(8, 0));
Assert.assertEquals("M_10", tableModel.getValueAt(9, 0));
}
@Test
public void testMaskViewerForm() {
Assert.assertSame(product, maskViewerForm.getProduct());
Assert.assertNull(maskViewerForm.getHelpButton());
Assert.assertNotNull(maskViewerForm.createContentPanel());
Assert.assertEquals(10, maskViewerForm.getRowCount());
}
static Product createTestProduct() {
Color[] colors = {
Color.WHITE,
Color.BLACK,
Color.GREEN,
Color.BLUE,
Color.CYAN,
Color.MAGENTA,
Color.PINK,
Color.YELLOW,
Color.ORANGE,
Color.RED,
};
Product product = new Product("P", "T", 256, 256);
Band a = product.addBand("A", ProductData.TYPE_UINT8);
Band b = product.addBand("B", ProductData.TYPE_UINT8);
Band c = product.addBand("C", ProductData.TYPE_UINT8);
a.setScalingFactor(1.0 / 255.0);
b.setScalingFactor(1.0 / 255.0);
c.setScalingFactor(1.0 / 255.0);
a.setSourceImage(new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY));
b.setSourceImage(new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY));
c.setSourceImage(new BufferedImage(256, 256, BufferedImage.TYPE_BYTE_GRAY));
for (int i = 0; i < colors.length; i++) {
String expression = "B > " + (i / (colors.length - 1.0));
String name = "M_" + (product.getMaskGroup().getNodeCount() + 1);
Mask mask = Mask.BandMathsType.create(name, expression, product.getSceneRasterWidth(), product.getSceneRasterHeight(),
expression, colors[i], 1.0 - 1.0 / (1 + (i % 4)));
product.getMaskGroup().add(mask);
}
return product;
}
}
| 4,813 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MaskTableModelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/mask/MaskTableModelTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.mask;
import org.esa.snap.core.datamodel.Product;
import org.junit.Test;
import static org.junit.Assert.*;
public class MaskTableModelTest {
@Test
public void testManagementMode() {
MaskTableModel maskTableModel = new MaskTableModel(true);
assertFalse(maskTableModel.isInManagmentMode());
assertEquals(5, maskTableModel.getColumnCount());
assertEquals("Name", maskTableModel.getColumnName(0));
assertEquals("Type", maskTableModel.getColumnName(1));
assertEquals("Colour", maskTableModel.getColumnName(2));
assertEquals("Transparency", maskTableModel.getColumnName(3));
assertEquals("Description", maskTableModel.getColumnName(4));
assertEquals(0, maskTableModel.getRowCount());
Product product = MaskFormTest.createTestProduct();
maskTableModel.setProduct(product, null);
assertTrue(maskTableModel.isInManagmentMode());
assertEquals(5, maskTableModel.getColumnCount());
assertEquals("Name", maskTableModel.getColumnName(0));
assertEquals("Type", maskTableModel.getColumnName(1));
assertEquals("Colour", maskTableModel.getColumnName(2));
assertEquals("Transparency", maskTableModel.getColumnName(3));
assertEquals("Description", maskTableModel.getColumnName(4));
assertEquals(10, maskTableModel.getRowCount());
maskTableModel.setProduct(product, product.getBand("C"));
assertTrue(maskTableModel.isInManagmentMode());
assertEquals(6, maskTableModel.getColumnCount());
assertEquals("Visibility", maskTableModel.getColumnName(0));
assertEquals("Name", maskTableModel.getColumnName(1));
assertEquals("Type", maskTableModel.getColumnName(2));
assertEquals("Colour", maskTableModel.getColumnName(3));
assertEquals("Transparency", maskTableModel.getColumnName(4));
assertEquals("Description", maskTableModel.getColumnName(5));
assertEquals(10, maskTableModel.getRowCount());
}
@Test
public void testViewMode() {
MaskTableModel maskTableModel = new MaskTableModel(false);
assertFalse(maskTableModel.isInManagmentMode());
assertEquals(4, maskTableModel.getColumnCount());
assertEquals("Name", maskTableModel.getColumnName(0));
assertEquals("Colour", maskTableModel.getColumnName(1));
assertEquals("Transparency", maskTableModel.getColumnName(2));
assertEquals("Description", maskTableModel.getColumnName(3));
assertEquals(0, maskTableModel.getRowCount());
Product product = MaskFormTest.createTestProduct();
maskTableModel.setProduct(product, null);
assertFalse(maskTableModel.isInManagmentMode());
assertEquals(4, maskTableModel.getColumnCount());
assertEquals("Name", maskTableModel.getColumnName(0));
assertEquals("Colour", maskTableModel.getColumnName(1));
assertEquals("Transparency", maskTableModel.getColumnName(2));
assertEquals("Description", maskTableModel.getColumnName(3));
assertEquals(10, maskTableModel.getRowCount());
maskTableModel.setProduct(product, product.getBand("C"));
assertFalse(maskTableModel.isInManagmentMode());
assertEquals(5, maskTableModel.getColumnCount());
assertEquals("Visibility", maskTableModel.getColumnName(0));
assertEquals("Name", maskTableModel.getColumnName(1));
assertEquals("Colour", maskTableModel.getColumnName(2));
assertEquals("Transparency", maskTableModel.getColumnName(3));
assertEquals("Description", maskTableModel.getColumnName(4));
assertEquals(10, maskTableModel.getRowCount());
}
}
| 4,452 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MaskApplicationMain.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/mask/MaskApplicationMain.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.mask;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeListenerAdapter;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.ui.GridLayout2;
import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;
import java.awt.event.ActionEvent;
import java.util.Locale;
public class MaskApplicationMain {
private final Product product;
private final MaskManagerForm maskManagerForm;
private final MaskViewerForm maskViewerForm;
private Product selectedProduct;
private RasterDataNode selectedBand;
public MaskApplicationMain() {
product = MaskFormTest.createTestProduct();
product.addProductNodeListener(new ProductNodeListenerAdapter() {
@Override
public void nodeChanged(ProductNodeEvent event) {
System.out.println("event = " + event);
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
System.out.println("event = " + event);
}
@Override
public void nodeAdded(ProductNodeEvent event) {
System.out.println("event = " + event);
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
System.out.println("event = " + event);
}
});
selectedProduct = null;
selectedBand = null;
maskManagerForm = new MaskManagerForm(null, null);
maskManagerForm.reconfigureMaskTable(selectedProduct, selectedBand);
maskViewerForm = new MaskViewerForm(null);
maskViewerForm.reconfigureMaskTable(selectedProduct, selectedBand);
}
public static void main(String[] args) {
Locale.setDefault(Locale.UK);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception ignored) {
// ignore
}
final MaskApplicationMain app = new MaskApplicationMain();
final JFrame maskManagerFrame = createFrame("ROI/Mask Manager", app.maskManagerForm.createContentPanel());
final JFrame maskViewerFrame = createFrame("Bitmask Overlay", app.maskViewerForm.createContentPanel());
final JFrame productManagerFrame = createFrame("Product Manager", createProductManagerPanel(app));
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
maskManagerFrame.setLocation(50, 50);
maskViewerFrame.setLocation(maskManagerFrame.getX() + maskManagerFrame.getWidth(), 50);
productManagerFrame.setLocation(maskViewerFrame.getX() + maskViewerFrame.getWidth(), 50);
maskManagerFrame.setVisible(true);
maskViewerFrame.setVisible(true);
productManagerFrame.setVisible(true);
}
});
}
private static JFrame createFrame(String name, JPanel panel) {
final JFrame frame = new JFrame(name);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.setAlwaysOnTop(true);
frame.pack();
return frame;
}
private static JPanel createProductManagerPanel(final MaskApplicationMain app) {
JPanel panel = new JPanel(new GridLayout2(-1, 1, 2, 2));
panel.setBorder(new EmptyBorder(4, 4, 4, 4));
panel.add(new JButton(new AbstractAction("Select product") {
@Override
public void actionPerformed(ActionEvent e) {
app.selectProduct(app.product);
}
}));
panel.add(new JButton(new AbstractAction("Unselect product") {
@Override
public void actionPerformed(ActionEvent e) {
app.selectProduct(null);
}
}));
String[] bandNames = app.product.getBandNames();
for (String bandName : bandNames) {
AbstractAction action = new AbstractAction("Select band '" + bandName + "'") {
@Override
public void actionPerformed(ActionEvent e) {
app.selectBand(app.product.getBand((String) getValue("bandName")));
}
};
action.putValue("bandName", bandName);
panel.add(new JButton(action));
}
panel.add(new JButton(new AbstractAction("Unselect band") {
@Override
public void actionPerformed(ActionEvent e) {
app.selectBand(null);
}
}));
return panel;
}
void selectProduct(Product product) {
selectedProduct = product;
selectedBand = null;
handleSelectionStateChange();
}
void selectBand(RasterDataNode band) {
if (band != null) {
selectedProduct = band.getProduct();
}
selectedBand = band;
handleSelectionStateChange();
}
private void handleSelectionStateChange() {
maskManagerForm.reconfigureMaskTable(selectedProduct, selectedBand);
maskViewerForm.reconfigureMaskTable(selectedProduct, selectedBand);
}
}
| 6,121 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataPlotPanelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/MetadataPlotPanelTest.java | package org.esa.snap.rcp.statistics;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Marco Peters
*/
public class MetadataPlotPanelTest {
@Test
public void getRecordIndices() throws Exception {
double[] recordIndices;
recordIndices = MetadataPlotPanel.getRecordIndices(3, 5, 10);
assertArrayEquals(new double[]{3, 4, 5, 6, 7}, recordIndices, 1.0e-6);
recordIndices = MetadataPlotPanel.getRecordIndices(3, 8, 10);
assertArrayEquals(new double[]{3, 4, 5, 6, 7, 8, 9, 10}, recordIndices, 1.0e-6);
recordIndices = MetadataPlotPanel.getRecordIndices(12, 8, 10);
assertArrayEquals(new double[]{10}, recordIndices, 1.0e-6);
}
} | 721 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProfileDataTableModelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/ProfileDataTableModelTest.java | package org.esa.snap.rcp.statistics;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.TransectProfileData;
import org.esa.snap.core.datamodel.TransectProfileDataBuilder;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.feature.simple.SimpleFeatureImpl;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.filter.identity.FeatureIdImpl;
import org.junit.Before;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
import javax.swing.table.TableModel;
import java.awt.geom.Path2D;
import static org.junit.Assert.*;
/**
* @author Norman Fomferra
*/
public class ProfileDataTableModelTest {
private Product product;
private Band band;
private Path2D path;
private ProfilePlotPanel.DataSourceConfig dataSourceConfig;
@Before
public void setUp() throws Exception {
// Draw a "Z"
path = new Path2D.Double();
path.moveTo(0, 0);
path.lineTo(3, 0);
path.lineTo(0, 3);
path.lineTo(3, 3);
product = new Product("p", "t", 4, 4);
band = product.addBand("b", "4 * (Y-0.5) + (X-0.5) + 0.1");
dataSourceConfig = new ProfilePlotPanel.DataSourceConfig();
SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
ftb.setName("ft");
ftb.add("lat", Double.class);
ftb.add("lon", Double.class);
ftb.add("data", Double.class);
SimpleFeatureType ft = ftb.buildFeatureType();
DefaultFeatureCollection fc = new DefaultFeatureCollection("id", ft);
fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.3}, ft, new FeatureIdImpl("id1"), false));
fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.5}, ft, new FeatureIdImpl("id2"), false));
fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.7}, ft, new FeatureIdImpl("id3"), false));
fc.add(new SimpleFeatureImpl(new Object[]{0, 0, 0.1}, ft, new FeatureIdImpl("id4"), false));
dataSourceConfig.pointDataSource = new VectorDataNode("vd", fc);
dataSourceConfig.dataField = ft.getDescriptor("data");
dataSourceConfig.boxSize = 1;
dataSourceConfig.computeInBetweenPoints = true;
}
@Test
public void testModelWithCorrData() throws Exception {
TransectProfileData profileData = new TransectProfileDataBuilder()
.raster(band)
.path(path)
.boxSize(dataSourceConfig.boxSize)
.build();
TableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig);
assertEquals(10, tableModel.getColumnCount());
assertEquals("pixel_no", tableModel.getColumnName(0));
assertEquals("pixel_x", tableModel.getColumnName(1));
assertEquals("pixel_y", tableModel.getColumnName(2));
assertEquals("latitude", tableModel.getColumnName(3));
assertEquals("longitude", tableModel.getColumnName(4));
assertEquals("b_mean", tableModel.getColumnName(5));
assertEquals("b_sigma", tableModel.getColumnName(6));
assertEquals("data_ref", tableModel.getColumnName(7));
assertEquals("lat_ref", tableModel.getColumnName(8));
assertEquals("lon_ref", tableModel.getColumnName(9));
assertEquals(10, tableModel.getRowCount());
assertEquals(1, tableModel.getValueAt(0, 0));
assertEquals(0.0, tableModel.getValueAt(0, 1));
assertEquals(0.0, tableModel.getValueAt(0, 2));
assertEquals(null, tableModel.getValueAt(0, 3));
assertEquals(null, tableModel.getValueAt(0, 4));
assertEquals(0.1F, tableModel.getValueAt(0, 5));
assertEquals(0.0F, tableModel.getValueAt(0, 6));
assertEquals(0.3, tableModel.getValueAt(0, 7));
assertEquals(0, tableModel.getValueAt(0, 8));
assertEquals(0, tableModel.getValueAt(0, 9));
assertEquals(2, tableModel.getValueAt(1, 0));
assertEquals(1.0, tableModel.getValueAt(1, 1));
assertEquals(0.0, tableModel.getValueAt(1, 2));
assertEquals(null, tableModel.getValueAt(1, 3));
assertEquals(null, tableModel.getValueAt(1, 4));
assertEquals(1.1F, tableModel.getValueAt(1, 5));
assertEquals(0.0F, tableModel.getValueAt(1, 6));
assertEquals(null, tableModel.getValueAt(1, 7));
assertEquals(null, tableModel.getValueAt(1, 8));
assertEquals(null, tableModel.getValueAt(1, 9));
assertEquals(10, tableModel.getValueAt(9, 0));
assertEquals(3.0, tableModel.getValueAt(9, 1));
assertEquals(3.0, tableModel.getValueAt(9, 2));
assertEquals(null, tableModel.getValueAt(9, 3));
assertEquals(null, tableModel.getValueAt(9, 4));
assertEquals(15.1F, tableModel.getValueAt(9, 5));
assertEquals(0.0F, tableModel.getValueAt(9, 6));
assertEquals(0.1, tableModel.getValueAt(9, 7));
assertEquals(0, tableModel.getValueAt(9, 8));
assertEquals(0, tableModel.getValueAt(9, 9));
}
@Test
public void testModelWithoutCorrData() throws Exception {
dataSourceConfig.dataField = null;
dataSourceConfig.boxSize = 1;
TransectProfileData profileData = new TransectProfileDataBuilder()
.raster(band)
.path(path)
.boxSize(dataSourceConfig.boxSize)
.build();
TableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig);
assertEquals(8, tableModel.getColumnCount());
assertEquals("pixel_no", tableModel.getColumnName(0));
assertEquals("pixel_x", tableModel.getColumnName(1));
assertEquals("pixel_y", tableModel.getColumnName(2));
assertEquals("latitude", tableModel.getColumnName(3));
assertEquals("longitude", tableModel.getColumnName(4));
assertEquals("b_mean", tableModel.getColumnName(5));
assertEquals("b_sigma", tableModel.getColumnName(6));
assertEquals("", tableModel.getColumnName(7));
assertEquals(10, tableModel.getRowCount());
assertEquals(1, tableModel.getValueAt(0, 0));
assertEquals(0.0, tableModel.getValueAt(0, 1));
assertEquals(0.0, tableModel.getValueAt(0, 2));
assertEquals(null, tableModel.getValueAt(0, 3));
assertEquals(null, tableModel.getValueAt(0, 4));
assertEquals(0.1F, tableModel.getValueAt(0, 5));
assertEquals(0.0F, tableModel.getValueAt(0, 6));
assertEquals(null, tableModel.getValueAt(0, 7));
assertEquals(2, tableModel.getValueAt(1, 0));
assertEquals(1.0, tableModel.getValueAt(1, 1));
assertEquals(0.0, tableModel.getValueAt(1, 2));
assertEquals(null, tableModel.getValueAt(1, 3));
assertEquals(null, tableModel.getValueAt(1, 4));
assertEquals(1.1F, tableModel.getValueAt(1, 5));
assertEquals(0.0F, tableModel.getValueAt(1, 6));
assertEquals(null, tableModel.getValueAt(1, 7));
assertEquals(10, tableModel.getValueAt(9, 0));
assertEquals(3.0, tableModel.getValueAt(9, 1));
assertEquals(3.0, tableModel.getValueAt(9, 2));
assertEquals(null, tableModel.getValueAt(9, 3));
assertEquals(null, tableModel.getValueAt(9, 4));
assertEquals(15.1F, tableModel.getValueAt(9, 5));
assertEquals(0.0F, tableModel.getValueAt(9, 6));
assertEquals(null, tableModel.getValueAt(9, 7));
}
@Test
public void testModelCsv() throws Exception {
TransectProfileData profileData = new TransectProfileDataBuilder()
.raster(band)
.path(path)
.boxSize(dataSourceConfig.boxSize)
.build();
ProfileDataTableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig);
String csv = tableModel.toCsv();
assertEquals("pixel_no\tpixel_x\tpixel_y\tlatitude\tlongitude\tb_mean\tb_sigma\tdata_ref\tlat_ref\tlon_ref\n" +
"1\t0.0\t0.0\t\t\t0.1\t0.0\t0.3\t0\t0\n" +
"2\t1.0\t0.0\t\t\t1.1\t0.0\t\t\t\n" +
"3\t2.0\t0.0\t\t\t2.1\t0.0\t\t\t\n" +
"4\t3.0\t0.0\t\t\t3.1\t0.0\t0.5\t0\t0\n" +
"5\t2.0\t1.0\t\t\t6.1\t0.0\t\t\t\n" +
"6\t1.0\t2.0\t\t\t9.1\t0.0\t\t\t\n" +
"7\t0.0\t3.0\t\t\t12.1\t0.0\t0.7\t0\t0\n" +
"8\t1.0\t3.0\t\t\t13.1\t0.0\t\t\t\n" +
"9\t2.0\t3.0\t\t\t14.1\t0.0\t\t\t\n" +
"10\t3.0\t3.0\t\t\t15.1\t0.0\t0.1\t0\t0\n", csv);
}
@Test
public void testModelCsvNoInBetweenPoints() throws Exception {
dataSourceConfig.computeInBetweenPoints = false;
TransectProfileData profileData = new TransectProfileDataBuilder()
.raster(band)
.path(path)
.boxSize(dataSourceConfig.boxSize)
.build();
ProfileDataTableModel tableModel = new ProfileDataTableModel(band.getName(), profileData, dataSourceConfig);
String csv = tableModel.toCsv();
assertEquals("pixel_no\tpixel_x\tpixel_y\tlatitude\tlongitude\tb_mean\tb_sigma\tdata_ref\tlat_ref\tlon_ref\n" +
"1\t0.0\t0.0\t\t\t0.1\t0.0\t0.3\t0\t0\n" +
"4\t3.0\t0.0\t\t\t3.1\t0.0\t0.5\t0\t0\n" +
"7\t0.0\t3.0\t\t\t12.1\t0.0\t0.7\t0\t0\n" +
"10\t3.0\t3.0\t\t\t15.1\t0.0\t0.1\t0\t0\n", csv);
}
}
| 9,767 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
XYImagePlotTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/XYImagePlotTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.statistics;
import org.junit.Test;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import static org.junit.Assert.*;
public class XYImagePlotTest {
@Test
public void testDefaultValues() {
final XYImagePlot imagePlot = new XYImagePlot();
assertNull(imagePlot.getImage());
assertNull(imagePlot.getImageDataBounds());
assertNull(imagePlot.getDataset());
assertNotNull(imagePlot.getDomainAxis());
assertNotNull(imagePlot.getRangeAxis());
assertTrue(imagePlot.isDomainGridlinesVisible());
assertTrue(imagePlot.isRangeGridlinesVisible());
}
@Test
public void testImage() {
final XYImagePlot imagePlot = new XYImagePlot();
final BufferedImage image = new BufferedImage(16, 9, BufferedImage.TYPE_INT_ARGB);
imagePlot.setImage(image);
assertSame(image, imagePlot.getImage());
assertEquals(new Rectangle(0, 0, 16, 9), imagePlot.getImageDataBounds());
final BufferedImage otherImage = new BufferedImage(4, 3, BufferedImage.TYPE_INT_ARGB);
imagePlot.setImage(otherImage);
assertSame(otherImage, imagePlot.getImage());
assertEquals(new Rectangle(0, 0, 16, 9), imagePlot.getImageDataBounds());
}
@Test
public void testImageDataBounds() {
final XYImagePlot imagePlot = new XYImagePlot();
assertNull(imagePlot.getDataset());
final Rectangle bounds = new Rectangle(0, 2, 20, 40);
imagePlot.setImageDataBounds(bounds);
assertNotSame(bounds, imagePlot.getImageDataBounds());
assertEquals(bounds, imagePlot.getImageDataBounds());
assertEquals(0.0, imagePlot.getDomainAxis().getLowerBound(), 1e-10);
assertEquals(20.0, imagePlot.getDomainAxis().getUpperBound(), 1e-10);
assertEquals(2.0, imagePlot.getRangeAxis().getLowerBound(), 1e-10);
assertEquals(42.0, imagePlot.getRangeAxis().getUpperBound(), 1e-10);
assertNotNull(imagePlot.getDataset());
}
@Test
public void testImageSourceArea() {
final XYImagePlot imagePlot = new XYImagePlot();
final BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_ARGB);
imagePlot.setImage(image);
imagePlot.setImageDataBounds(new Rectangle2D.Double(-1.0, 0.0, 2.0, 1.0));
imagePlot.getDomainAxis().setRange(-0.5, +0.5);
imagePlot.getRangeAxis().setRange(0.25, 0.75);
Rectangle area = imagePlot.getImageSourceArea();
assertEquals(50, area.x);
assertEquals(25, area.y);
assertEquals(100, area.width);
assertEquals(50, area.height);
imagePlot.getDomainAxis().setRange(0, 0.1);
imagePlot.getRangeAxis().setRange(0.5, 0.6);
area = imagePlot.getImageSourceArea();
assertEquals(100, area.x);
assertEquals(40, area.y);
assertEquals(10, area.width);
assertEquals(10, area.height);
imagePlot.getDomainAxis().setRange(0.5, 1.0);
imagePlot.getRangeAxis().setRange(0.7, 1.0);
area = imagePlot.getImageSourceArea();
assertEquals(150, area.x);
assertEquals(0, area.y);
assertEquals(50, area.width);
assertEquals(30, area.height);
}
} | 4,029 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RefreshActionEnablerTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/RefreshActionEnablerTest.java | package org.esa.snap.rcp.statistics;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import javax.swing.JButton;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Mask;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class RefreshActionEnablerTest {
private JButton refreshButton;
@Before
public void setUp() {
refreshButton = new JButton();
refreshButton.setEnabled(false);
}
@Test
public void propertyChange_band_change() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("xProduct", Product.class));
propertyContainer.addProperty(Property.create("yProduct", Product.class));
propertyContainer.addProperty(Property.create("zProduct", Product.class));
propertyContainer.addProperty(Property.create("xBand", Band.class));
propertyContainer.addProperty(Property.create("yBand", Band.class));
propertyContainer.addProperty(Property.create("zBand", Band.class));
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton);
refreshActionEnabler.addProductBandEnablement("xProduct", "xBand");
refreshActionEnabler.addProductBandEnablement("yProduct", "yBand");
refreshActionEnabler.addProductBandEnablement("zProduct", "zBand");
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
propertyContainer.setValue("xBand", new Band("name", ProductData.TYPE_INT8, 1, 1));
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("yBand", new Band("name", ProductData.TYPE_INT8, 1, 1));
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("zBand", new Band("name", ProductData.TYPE_INT8, 1, 1));
assertTrue(refreshButton.isEnabled());
}
@Test
public void propertyChange_band_change_with_option() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("xProduct", Product.class));
propertyContainer.addProperty(Property.create("yProduct", Product.class));
propertyContainer.addProperty(Property.create("zProduct", Product.class));
propertyContainer.addProperty(Property.create("colorProduct", Product.class));
propertyContainer.addProperty(Property.create("xBand", Band.class));
propertyContainer.addProperty(Property.create("yBand", Band.class));
propertyContainer.addProperty(Property.create("zBand", Band.class));
propertyContainer.addProperty(Property.create("colorBand", Band.class));
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton);
refreshActionEnabler.addProductBandEnablement("xProduct", "xBand");
refreshActionEnabler.addProductBandEnablement("yProduct", "yBand");
refreshActionEnabler.addProductBandEnablement("zProduct", "zBand");
refreshActionEnabler.addProductBandEnablement("colorProduct", "colorBand", true);
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
propertyContainer.setValue("colorBand", new Band("name", ProductData.TYPE_INT8, 1, 1));
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("xBand", new Band("name", ProductData.TYPE_INT8, 1, 1));
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("yBand", new Band("name", ProductData.TYPE_INT8, 1, 1));
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("colorBand", new Band("otherName", ProductData.TYPE_INT8, 1, 1));
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("zBand", new Band("name", ProductData.TYPE_INT8, 1, 1));
assertTrue(refreshButton.isEnabled());
propertyContainer.setValue("colorBand", null);
assertTrue(refreshButton.isEnabled());
}
@Test
public void propertyChange_product_change() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("xProduct", Product.class));
propertyContainer.addProperty(Property.create("yProduct", Product.class));
propertyContainer.addProperty(Property.create("zProduct", Product.class));
propertyContainer.addProperty(Property.create("xBand", Band.class));
propertyContainer.addProperty(Property.create("yBand", Band.class));
propertyContainer.addProperty(Property.create("zBand", Band.class));
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton);
refreshActionEnabler.addProductBandEnablement("xProduct", "xBand");
refreshActionEnabler.addProductBandEnablement("yProduct", "yBand");
refreshActionEnabler.addProductBandEnablement("zProduct", "zBand");
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
refreshButton.setEnabled(true);
propertyContainer.setValue("xProduct", new Product("name", "type"));
assertFalse(refreshButton.isEnabled());
refreshButton.setEnabled(true);
propertyContainer.setValue("yProduct", new Product("name", "type"));
assertFalse(refreshButton.isEnabled());
refreshButton.setEnabled(true);
propertyContainer.setValue("zProduct", new Product("name", "type"));
assertFalse(refreshButton.isEnabled());
}
@Test
public void propertyChange_product_change_with_option() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("xProduct", Product.class));
propertyContainer.addProperty(Property.create("yProduct", Product.class));
propertyContainer.addProperty(Property.create("zProduct", Product.class));
propertyContainer.addProperty(Property.create("colorProduct", Product.class));
propertyContainer.addProperty(Property.create("xBand", Band.class));
propertyContainer.addProperty(Property.create("yBand", Band.class));
propertyContainer.addProperty(Property.create("zBand", Band.class));
propertyContainer.addProperty(Property.create("colorBand", Band.class));
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton);
refreshActionEnabler.addProductBandEnablement("xProduct", "xBand");
refreshActionEnabler.addProductBandEnablement("yProduct", "yBand");
refreshActionEnabler.addProductBandEnablement("zProduct", "zBand");
refreshActionEnabler.addProductBandEnablement("colorProduct", "colorBand", true);
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
refreshButton.setEnabled(true);
propertyContainer.setValue("xProduct", new Product("name", "type"));
assertFalse(refreshButton.isEnabled());
refreshButton.setEnabled(true);
propertyContainer.setValue("yProduct", new Product("name", "type"));
assertFalse(refreshButton.isEnabled());
refreshButton.setEnabled(true);
propertyContainer.setValue("zProduct", new Product("name", "type"));
assertFalse(refreshButton.isEnabled());
refreshButton.setEnabled(true);
propertyContainer.setValue("colorProduct", new Product("name", "type"));
assertTrue(refreshButton.isEnabled());
}
@Test
public void propertyChange_other_property_change() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("random", String.class));
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton, "random");
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
propertyContainer.setValue("random", "vfsgtdnf");
assertTrue(refreshButton.isEnabled());
}
@Test
public void propertyChange_irrelevant_property_change() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("random", String.class));
propertyContainer.addProperty(Property.create("irrelevant", String.class));
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton, "random");
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
propertyContainer.setValue("irrelevant", "vfsgtdnf");
assertFalse(refreshButton.isEnabled());
}
@Test
public void propertyChange_roi_mask_property_change() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("useRoiMask", Boolean.class));
propertyContainer.setValue("useRoiMask", false);
propertyContainer.addProperty(Property.create("roiMask", Mask.class));
propertyContainer.setValue("roiMask", null);
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton, "useRoiMask", "roiMask");
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
propertyContainer.setValue("useRoiMask", true);
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("roiMask", new Mask("name", 1, 1, Mask.BandMathsType.INSTANCE));
assertTrue(refreshButton.isEnabled());
refreshButton.setEnabled(false);
propertyContainer.setValue("useRoiMask", false);
assertTrue(refreshButton.isEnabled());
refreshButton.setEnabled(false);
propertyContainer.setValue("useRoiMask", true);
assertTrue(refreshButton.isEnabled());
refreshButton.setEnabled(false);
propertyContainer.setValue("roiMask", null);
assertTrue(refreshButton.isEnabled());
}
@Test
public void propertyChange_auto_min_max_property_change() {
PropertyContainer propertyContainer = new PropertyContainer();
propertyContainer.addProperty(Property.create("autoMinMax", Boolean.class));
propertyContainer.setValue("autoMinMax", false);
propertyContainer.addProperty(Property.create("min", Double.class));
propertyContainer.setValue("min", 0.0);
propertyContainer.addProperty(Property.create("max", Double.class));
propertyContainer.setValue("max", 1.0);
RefreshActionEnabler refreshActionEnabler = new RefreshActionEnabler(refreshButton, "autoMinMax", "min", "max");
propertyContainer.addPropertyChangeListener(refreshActionEnabler);
propertyContainer.setValue("autoMinMax", false);
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("min", 0.0);
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("min", 0.1);
assertTrue(refreshButton.isEnabled());
refreshButton.setEnabled(false);
propertyContainer.setValue("max", 1.0);
assertFalse(refreshButton.isEnabled());
propertyContainer.setValue("max", 0.9);
assertTrue(refreshButton.isEnabled());
refreshButton.setEnabled(false);
propertyContainer.setValue("autoMinMax", true);
assertTrue(refreshButton.isEnabled());
}
} | 11,440 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomLogarithmicAxisTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/CustomLogarithmicAxisTest.java | package org.esa.snap.rcp.statistics;
import org.jfree.chart.axis.NumberTick;
import org.jfree.chart.ui.RectangleEdge;
import org.junit.Test;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Date: 11.04.12
* Time: 13:18
*
* @author olafd
*/
public class CustomLogarithmicAxisTest {
@Test
public void testRefreshTicks() throws Exception {
CustomLogarithmicAxis testAxis = new CustomLogarithmicAxis("testAxis");
// axis range includes 3 power of 10 values: 1, 10, 100
testAxis.setRange(0.3, 300.0);
List ticks = testAxis.refreshTicks(RectangleEdge.TOP, CustomLogarithmicAxis.HORIZONTAL);
assertNotNull(ticks);
assertEquals(28, ticks.size());
// we expect labels at the power of 10 values only
assertEquals("", ((NumberTick) ticks.get(0)).getText());
assertEquals("", ((NumberTick) ticks.get(1)).getText());
assertEquals("1", ((NumberTick) ticks.get(7)).getText());
assertEquals("", ((NumberTick) ticks.get(9)).getText());
assertEquals("10", ((NumberTick) ticks.get(16)).getText());
assertEquals("", ((NumberTick) ticks.get(18)).getText());
assertEquals("100", ((NumberTick) ticks.get(25)).getText());
assertEquals("", ((NumberTick) ticks.get(26)).getText());
// axis range includes 2 power of 10 values: 1, 10
testAxis.setRange(0.3, 30.0);
ticks = testAxis.refreshTicks(RectangleEdge.TOP, CustomLogarithmicAxis.HORIZONTAL);
assertNotNull(ticks);
assertEquals(19, ticks.size());
// we expect labels at the power of 10 values only
assertEquals("", ((NumberTick) ticks.get(0)).getText());
assertEquals("", ((NumberTick) ticks.get(1)).getText());
assertEquals("1", ((NumberTick) ticks.get(7)).getText());
assertEquals("", ((NumberTick) ticks.get(9)).getText());
assertEquals("10", ((NumberTick) ticks.get(16)).getText());
assertEquals("", ((NumberTick) ticks.get(18)).getText());
// axis range includes 1 power of 10 values: 1
testAxis.setRange(0.3, 3.0);
ticks = testAxis.refreshTicks(RectangleEdge.TOP, CustomLogarithmicAxis.HORIZONTAL);
assertNotNull(ticks);
assertEquals(10, ticks.size());
// we expect labels at every tick!
// todo: clarify why these tests work locally, but not on buildserver (who expects "0.3", "0.4", ...)
// assertEquals("0,3", ((NumberTick) ticks.get(0)).getText());
// assertEquals("0,4", ((NumberTick) ticks.get(1)).getText());
// assertEquals("0,5", ((NumberTick) ticks.get(2)).getText());
// assertEquals("0,6", ((NumberTick) ticks.get(3)).getText());
// assertEquals("0,7", ((NumberTick) ticks.get(4)).getText());
// assertEquals("0,8", ((NumberTick) ticks.get(5)).getText());
// assertEquals("0,9", ((NumberTick) ticks.get(6)).getText());
assertEquals(0.3, ((NumberTick) ticks.get(0)).getValue(), 1.E-6);
assertEquals(0.4, ((NumberTick) ticks.get(1)).getValue(), 1.E-6);
assertEquals(0.5, ((NumberTick) ticks.get(2)).getValue(), 1.E-6);
assertEquals(0.6, ((NumberTick) ticks.get(3)).getValue(), 1.E-6);
assertEquals(0.7, ((NumberTick) ticks.get(4)).getValue(), 1.E-6);
assertEquals(0.8, ((NumberTick) ticks.get(5)).getValue(), 1.E-6);
assertEquals(0.9, ((NumberTick) ticks.get(6)).getValue(), 1.E-6);
assertEquals("1", ((NumberTick) ticks.get(7)).getText());
assertEquals("2", ((NumberTick) ticks.get(8)).getText());
assertEquals("3", ((NumberTick) ticks.get(9)).getText());
// axis range includes no power of 10 values
testAxis.setRange(0.3, 0.8);
ticks = testAxis.refreshTicks(RectangleEdge.TOP, CustomLogarithmicAxis.HORIZONTAL);
assertNotNull(ticks);
assertEquals(6, ticks.size());
// we expect labels at every tick!
// todo: clarify why these tests work locally, but not on buildserver (who expects "0.3", "0.4", ...)
// assertEquals("0,3", ((NumberTick) ticks.get(0)).getText());
// assertEquals("0,4", ((NumberTick) ticks.get(1)).getText());
// assertEquals("0,5", ((NumberTick) ticks.get(2)).getText());
// assertEquals("0,6", ((NumberTick) ticks.get(3)).getText());
// assertEquals("0,7", ((NumberTick) ticks.get(4)).getText());
// assertEquals("0,8", ((NumberTick) ticks.get(5)).getText());
assertEquals(0.3, ((NumberTick) ticks.get(0)).getValue(), 1.E-6);
assertEquals(0.4, ((NumberTick) ticks.get(1)).getValue(), 1.E-6);
assertEquals(0.5, ((NumberTick) ticks.get(2)).getValue(), 1.E-6);
assertEquals(0.6, ((NumberTick) ticks.get(3)).getValue(), 1.E-6);
assertEquals(0.7, ((NumberTick) ticks.get(4)).getValue(), 1.E-6);
assertEquals(0.8, ((NumberTick) ticks.get(5)).getValue(), 1.E-6);
}
@Test
public void testRefreshTicksForNegativeAxisRange() throws Exception {
CustomLogarithmicAxis testAxis = new CustomLogarithmicAxis("testAxis");
testAxis.setRange(-300, -3);
List ticks = testAxis.refreshTicks(RectangleEdge.TOP, CustomLogarithmicAxis.HORIZONTAL);
assertNotNull(ticks);
assertEquals(19, ticks.size());
// we expect labels at the power of 10 values only
assertEquals("", ((NumberTick) ticks.get(0)).getText());
assertEquals("", ((NumberTick) ticks.get(1)).getText());
assertEquals("-10", ((NumberTick) ticks.get(7)).getText());
assertEquals("", ((NumberTick) ticks.get(9)).getText());
assertEquals("-100", ((NumberTick) ticks.get(16)).getText());
assertEquals("", ((NumberTick) ticks.get(18)).getText());
}
@Test
public void testRefreshTicksForInvalidAxisRange() throws Exception {
CustomLogarithmicAxis testAxis = new CustomLogarithmicAxis("testAxis");
// axis range maximum/minimum switched
try {
testAxis.setRange(30, 3);
} catch (IllegalArgumentException expected) {
assertEquals("Range(double, double): require lower (30.0) <= upper (3.0).", expected.getMessage());
}
// axis range includes zero
testAxis.setRange(-30, 30);
List ticks = testAxis.refreshTicks(RectangleEdge.TOP, CustomLogarithmicAxis.HORIZONTAL);
assertNotNull(ticks);
assertEquals(0, ticks.size());
}
@Test
public void testRefreshTicksVerticalAxisOrientation() throws Exception {
CustomLogarithmicAxis testAxis = new CustomLogarithmicAxis("testAxis");
testAxis.setRange(-300, -3);
List ticks = testAxis.refreshTicks(RectangleEdge.LEFT, CustomLogarithmicAxis.VERTICAL);
assertNotNull(ticks);
assertEquals(19, ticks.size());
assertEquals("", ((NumberTick) ticks.get(0)).getText());
assertEquals("", ((NumberTick) ticks.get(1)).getText());
assertEquals("-10", ((NumberTick) ticks.get(7)).getText());
assertEquals("", ((NumberTick) ticks.get(9)).getText());
assertEquals("-100", ((NumberTick) ticks.get(16)).getText());
assertEquals("", ((NumberTick) ticks.get(18)).getText());
}
}
| 7,264 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CorrelativeFieldSelectorTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/CorrelativeFieldSelectorTest.java | package org.esa.snap.rcp.statistics;
import com.bc.ceres.binding.Property;
import com.bc.ceres.swing.binding.BindingContext;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import javax.management.Descriptor;
import static org.junit.Assert.*;
/**
* @author Norman Fomferra
*/
public class CorrelativeFieldSelectorTest {
@Test
public void testExpectedProperties() throws Exception {
final BindingContext bindingContext = new BindingContext();
try {
new CorrelativeFieldSelector(bindingContext);
fail();
} catch (IllegalArgumentException expected) {
}
bindingContext.getPropertySet().addProperties(Property.create("pointDataSource", ProductNode.class));
try {
new CorrelativeFieldSelector(bindingContext);
fail();
} catch (IllegalArgumentException expected) {
}
bindingContext.getPropertySet().addProperties(Property.create("pointDataSource", VectorDataNode.class));
try {
new CorrelativeFieldSelector(bindingContext);
fail();
} catch (IllegalArgumentException expected) {
}
bindingContext.getPropertySet().addProperties(Property.create("dataField", Descriptor.class));
try {
new CorrelativeFieldSelector(bindingContext);
fail();
} catch (IllegalArgumentException expected) {
}
bindingContext.getPropertySet().addProperties(Property.create("dataField", AttributeDescriptor.class));
new CorrelativeFieldSelector(bindingContext);
}
@Test
public void testUpdatePointDataSource() throws Exception {
final BindingContext bindingContext = new BindingContext();
bindingContext.getPropertySet().addProperties(Property.create("pointDataSource", VectorDataNode.class));
bindingContext.getPropertySet().addProperties(Property.create("dataField", AttributeDescriptor.class));
final CorrelativeFieldSelector correlativeFieldSelector = new CorrelativeFieldSelector(bindingContext);
final Product product = new Product("name", "type", 10, 10);
product.getVectorDataGroup().add(new VectorDataNode("a", createFeatureType(Geometry.class)));
product.getVectorDataGroup().add(new VectorDataNode("b", createFeatureType(Point.class)));
assertEquals(0, correlativeFieldSelector.pointDataSourceList.getItemCount());
assertEquals(0, correlativeFieldSelector.dataFieldList.getItemCount());
correlativeFieldSelector.updatePointDataSource(product);
assertEquals(3, correlativeFieldSelector.pointDataSourceList.getItemCount());
assertEquals(0, correlativeFieldSelector.dataFieldList.getItemCount());
correlativeFieldSelector.pointDataSourceProperty.setValue(product.getVectorDataGroup().get("b"));
assertEquals(3, correlativeFieldSelector.dataFieldList.getItemCount());
}
private SimpleFeatureType createFeatureType(Class binding) {
SimpleFeatureTypeBuilder builder = new SimpleFeatureTypeBuilder();
builder.setName("featureType");
builder.add("chl", Float.class);
builder.add("sst", Double.class);
builder.add("time", ProductData.UTC.class);
builder.add("point", binding);
builder.setDefaultGeometry("point");
return builder.buildFeatureType();
}
}
| 3,799 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AxisRangeControlTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/AxisRangeControlTest.java | package org.esa.snap.rcp.statistics;
import org.junit.Test;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import java.awt.Component;
import java.awt.GridLayout;
import static org.junit.Assert.*;
public class AxisRangeControlTest {
@Test
public void testBindingContextInPlace() throws Exception {
final AxisRangeControl axisRangeControl = new AxisRangeControl("X-Axis");
axisRangeControl.getPanel();
assertNotNull(axisRangeControl.getBindingContext());
assertNotNull(axisRangeControl.getBindingContext().getBinding("autoMinMax"));
assertNotNull(axisRangeControl.getBindingContext().getBinding("min"));
assertNotNull(axisRangeControl.getBindingContext().getBinding("max"));
}
@Test
public void testInitialValues() throws Exception {
final AxisRangeControl axisRangeControl = new AxisRangeControl("");
axisRangeControl.getPanel();
assertEquals(true, axisRangeControl.getBindingContext().getBinding("autoMinMax").getPropertyValue());
assertEquals((Double) 0.0, axisRangeControl.getMin());
assertEquals((Double) 100.0, axisRangeControl.getMax());
}
@Test
public void testMinMaxSetterAndGetter() {
final AxisRangeControl axisRangeControl = new AxisRangeControl("");
axisRangeControl.adjustComponents(3.4, 13.8, 2);
assertEquals((Double) 3.4, axisRangeControl.getMin());
assertEquals((Double) 13.8, axisRangeControl.getMax());
}
@Test
public void testVerySmallValues() {
final AxisRangeControl axisRangeControl = new AxisRangeControl("");
axisRangeControl.getPanel();
int numDecimalPlaces = 2;
axisRangeControl.adjustComponents(-5e-9, 5e-9, numDecimalPlaces);
assertEquals(0.0, axisRangeControl.getMin(), 1e-7);
assertEquals(Math.pow(10, -numDecimalPlaces), axisRangeControl.getMax(), 1e-7);
}
@Test
public void testAdjustcomponents_valueChanges() {
final AxisRangeControl axisRangeControl = new AxisRangeControl("");
axisRangeControl.getPanel();
int numDecimalPlaces = 2;
axisRangeControl.adjustComponents(1.0, 2.0, numDecimalPlaces);
assertEquals(1.0, axisRangeControl.getMin(), 1e-7);
assertEquals(2.0, axisRangeControl.getMax(), 1e-7);
axisRangeControl.adjustComponents(1.99999999999, 2.5, numDecimalPlaces);
assertEquals(2.0, axisRangeControl.getMin(), 1e-7);
assertEquals(2.5, axisRangeControl.getMax(), 1e-7);
axisRangeControl.adjustComponents(1.0, 2.0000000000001, numDecimalPlaces);
assertEquals(1.0, axisRangeControl.getMin(), 1e-7);
assertEquals(2.0, axisRangeControl.getMax(), 1e-7);
}
@Test
public void testSetTitle() {
final String axisName = "Titel";
final AxisRangeControl control = new AxisRangeControl(axisName);
final JPanel rangeControlPanel = control.getPanel();
final Component component = rangeControlPanel.getComponent(0);
assertTrue(component instanceof TitledSeparator);
final TitledSeparator titledSeparator = (TitledSeparator) component;
final JLabel titleLabel = titledSeparator.getLabelComponent();
assertEquals(axisName, titleLabel.getText());
control.setTitleSuffix("radiance_3");
assertEquals(axisName + " (radiance_3)", titleLabel.getText());
control.setTitleSuffix("");
assertEquals(axisName, titleLabel.getText());
control.setTitleSuffix("radiance_5");
assertEquals(axisName + " (radiance_5)", titleLabel.getText());
control.setTitleSuffix(null);
assertEquals(axisName, titleLabel.getText());
}
public static void main(String[] args) throws ClassNotFoundException, UnsupportedLookAndFeelException, IllegalAccessException, InstantiationException {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
final JPanel axesPanel = new JPanel(new GridLayout(-1, 1));
axesPanel.add(new AxisRangeControl("X-Axis").getPanel());
axesPanel.add(new AxisRangeControl("Y-Axis").getPanel());
final JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(axesPanel);
frame.pack();
frame.setVisible(true);
}
} | 4,510 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
StatisticsUtilsTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/StatisticsUtilsTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.statistics;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.TransectProfileData;
import org.junit.Test;
import java.awt.geom.Line2D;
import java.io.IOException;
import java.util.Arrays;
import static org.junit.Assert.*;
/**
* @author Marco Peters
* @since BEAM 4.6
*/
public class StatisticsUtilsTest {
@Test
public void testCreateTransectProfileText_Byte() throws IOException {
final Product product = new Product("X", "Y", 2, 1);
Band node = product.addBand("name", ProductData.TYPE_INT8);
node.setSynthetic(true);
node.setNoDataValue(0);
node.setNoDataValueUsed(true);
final byte[] data = new byte[product.getSceneRasterWidth() * product.getSceneRasterHeight()];
Arrays.fill(data, (byte) 1);
data[0] = 0; // no data
node.setData(ProductData.createInstance(data));
final Line2D.Float shape = new Line2D.Float(0.5f, 0.5f, 1.5f, 0.5f);
final TransectProfileData profileData = node.createTransectProfileData(shape);
final String profileDataString = StatisticsUtils.TransectProfile.createTransectProfileText(node, profileData);
assertTrue(profileDataString.contains("NaN"));
assertFalse(profileDataString.toLowerCase().contains("no data"));
}
@Test
public void testCreateTransectProfileText_Float() throws IOException {
final Product product = new Product("X", "Y", 2, 1);
Band node = product.addBand("name", ProductData.TYPE_FLOAT32);
node.setSynthetic(true);
final float[] data = new float[product.getSceneRasterWidth() * product.getSceneRasterHeight()];
Arrays.fill(data, 1.0f);
data[0] = Float.NaN; // no data
node.setData(ProductData.createInstance(data));
final Line2D.Float shape = new Line2D.Float(0.5f, 0.5f, 1.5f, 0.5f);
final TransectProfileData profileData = node.createTransectProfileData(shape);
final String profileDataString = StatisticsUtils.TransectProfile.createTransectProfileText(node, profileData);
assertTrue(profileDataString.contains("NaN"));
assertFalse(profileDataString.toLowerCase().contains("no data"));
}
}
| 3,046 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
HistogramPanelModelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/HistogramPanelModelTest.java | /*
* Copyright (C) 2011 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.statistics;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.Stx;
import org.junit.Test;
import javax.media.jai.Histogram;
import static org.junit.Assert.*;
/**
* @author Thomas Storm
*/
public class HistogramPanelModelTest {
@Test
public void testRemoveStxFromProduct() throws Exception {
HistogramPanelModel model = new HistogramPanelModel();
Band band = new Band("name", ProductData.TYPE_UINT32, 10, 10);
Product product = new Product("dummy", "dummy", 10, 10);
product.addBand(band);
HistogramPanelModel.HistogramConfig config = new HistogramPanelModel.HistogramConfig(
band,
"Roy Mask",
10,
true
);
model.setStx(config, arbitraryStx());
assertTrue(model.hasStx(config));
model.removeStxFromProduct(product);
assertFalse(model.hasStx(config));
}
private static Stx arbitraryStx() {
return new Stx(10, 20, 15, 2, 0, 0, true, true, new Histogram(10, 10, 20, 1), 12);
}
}
| 1,923 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataPlotSettingsTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/statistics/MetadataPlotSettingsTest.java | package org.esa.snap.rcp.statistics;
import org.esa.snap.core.datamodel.MetadataAttribute;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.function.IntUnaryOperator;
import static org.junit.Assert.*;
public class MetadataPlotSettingsTest {
@Test
public void testUsableFieldsRetrieval_WithoutRecords() throws Exception {
MetadataElement elem = new MetadataElement("Records");
addAttributes(elem);
List<String> fieldNames = MetadataPlotSettings.retrieveUsableFieldNames(elem);
assertEquals(3, fieldNames.size());
assertTrue(fieldNames.contains("singleValue"));
assertTrue(fieldNames.contains("array"));
assertTrue(fieldNames.contains("splittedArray"));
assertTrue(!fieldNames.contains("string"));
}
@Test
public void testUsableFieldsRetrieval_WithRecords() throws Exception {
MetadataElement elem = new MetadataElement("Records");
MetadataElement element1 = new MetadataElement("Records.1");
addAttributes(element1);
elem.addElement(element1);
MetadataElement element2 = new MetadataElement("Records.2");
addAttributes(element2);
elem.addElement(element2);
List<String> fieldNames = MetadataPlotSettings.retrieveUsableFieldNames(elem);
assertEquals(3, fieldNames.size());
assertTrue(fieldNames.contains("singleValue"));
assertTrue(fieldNames.contains("array"));
assertTrue(fieldNames.contains("splittedArray"));
assertTrue(!fieldNames.contains("string"));
}
private void addAttributes(MetadataElement element) {
element.addAttribute(new MetadataAttribute("string", ProductData.createInstance("O815"), true));
element.addAttribute(new MetadataAttribute("singleValue", ProductData.createInstance(new byte[]{108}), true));
element.addAttribute(new MetadataAttribute("array", ProductData.createInstance(new byte[]{4, 8, 15, 16, 23, 42}), true));
element.addAttribute(new MetadataAttribute("splittedArray.1", ProductData.createInstance(new byte[]{4}), true));
element.addAttribute(new MetadataAttribute("splittedArray.2", ProductData.createInstance(new byte[]{8}), true));
element.addAttribute(new MetadataAttribute("splittedArray.3", ProductData.createInstance(new byte[]{15}), true));
element.addAttribute(new MetadataAttribute("splittedArray.4", ProductData.createInstance(new byte[]{16}), true));
element.addAttribute(new MetadataAttribute("splittedArray.5", ProductData.createInstance(new byte[]{23}), true));
element.addAttribute(new MetadataAttribute("splittedArray.6", ProductData.createInstance(new byte[]{42}), true));
}
} | 2,848 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PinPositionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/placemark/PinPositionTest.java | package org.esa.snap.rcp.placemark;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.esa.snap.core.datamodel.CrsGeoCoding;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.PinDescriptor;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Placemark;
import org.esa.snap.core.datamodel.Product;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Before;
import org.junit.Test;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import static org.junit.Assert.*;
public class PinPositionTest {
private Placemark placemark;
@Before
public void setup() throws TransformException, FactoryException {
final AffineTransform i2m = new AffineTransform();
i2m.scale(2.0, 2.0);
final GeoCoding geoCoding = new CrsGeoCoding(DefaultGeographicCRS.WGS84, new Rectangle(0, 0, 10, 10), i2m);
final Product product = new Product("P", "T", 10, 10);
product.setSceneGeoCoding(geoCoding);
placemark = Placemark.createPointPlacemark(PinDescriptor.getInstance(), "P1", "L", "", new PixelPos(1.0f, 1.0f), null, product.getSceneGeoCoding());
product.getPinGroup().add(placemark);
}
@Test
public void initialState() {
final double x = placemark.getPixelPos().getX();
final double y = placemark.getPixelPos().getY();
assertEquals(1.0, x, 0.0);
assertEquals(1.0, y, 0.0);
final Point point = (Point) placemark.getFeature().getDefaultGeometry();
assertEquals(2.0, point.getX(), 0.0);
assertEquals(2.0, point.getY(), 0.0);
final double lon = placemark.getGeoPos().getLon();
final double lat = placemark.getGeoPos().getLat();
assertEquals(2.0, lon, 0.0);
assertEquals(2.0, lat, 0.0);
}
@Test
public void movePinByGeometry() {
placemark.getFeature().setDefaultGeometry(newPoint(4.0, 2.0));
placemark.getProduct().getVectorDataGroup().get("pins").fireFeaturesChanged(placemark.getFeature());
final Point point = (Point) placemark.getFeature().getDefaultGeometry();
assertEquals(4.0, point.getX(), 0.0);
assertEquals(2.0, point.getY(), 0.0);
// todo: rq/?? - make asserts successful
final double x = placemark.getPixelPos().getX();
final double y = placemark.getPixelPos().getY();
assertEquals(2.0, x, 0.0);
assertEquals(1.0, y, 0.0);
// todo: rq/?? - make asserts successful
final double lon = placemark.getGeoPos().getLon();
final double lat = placemark.getGeoPos().getLat();
assertEquals(4.0, lon, 0.0);
assertEquals(2.0, lat, 0.0);
}
@Test
public void movePinByPixelPosition() {
placemark.setPixelPos(new PixelPos(2.0f, 1.0f));
final double x = placemark.getPixelPos().getX();
final double y = placemark.getPixelPos().getY();
assertEquals(2.0, x, 0.0);
assertEquals(1.0, y, 0.0);
// todo: rq/?? - make asserts successful
final Point point = (Point) placemark.getFeature().getDefaultGeometry();
assertEquals(4.0, point.getX(), 0.0);
assertEquals(2.0, point.getY(), 0.0);
// todo: rq/?? - make asserts successful
final double lon = placemark.getGeoPos().getLon();
final double lat = placemark.getGeoPos().getLat();
assertEquals(4.0, lon, 0.0);
assertEquals(2.0, lat, 0.0);
}
private Point newPoint(double x, double y) {
return new GeometryFactory().createPoint(new Coordinate(x, y));
}
}
| 3,826 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PlacemarkDialogTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/placemark/PlacemarkDialogTest.java | package org.esa.snap.rcp.placemark;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PinDescriptor;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.junit.Test;
import java.awt.HeadlessException;
import static org.junit.Assert.*;
public class PlacemarkDialogTest {
@Test
public void test() {
try {
PlacemarkDialog pinDialog = new PlacemarkDialog(null, new Product("x", "y", 10, 10), PinDescriptor.getInstance(), false);
pinDialog.setDescription("descrip");
assertEquals("descrip", pinDialog.getDescription());
pinDialog.setLat(3.6f);
assertEquals(3.6f, pinDialog.getLat(), 1e-15);
pinDialog.setLon(5.7f);
assertEquals(5.7f, pinDialog.getLon(), 1e-15);
GeoPos geoPos = pinDialog.getGeoPos();
assertNotNull(geoPos);
assertEquals(3.6f, geoPos.lat, 1e-6f);
assertEquals(5.7f, geoPos.lon, 1e-6f);
pinDialog.setName("name");
assertEquals("name", pinDialog.getName());
pinDialog.setLabel("label");
assertEquals("label", pinDialog.getLabel());
pinDialog.setPixelX(2.3F);
assertEquals(2.3F, pinDialog.getPixelX(), 1e-6F);
pinDialog.setPixelY(14.1F);
assertEquals(14.1F, pinDialog.getPixelY(), 1e-6F);
PixelPos pixelPos = pinDialog.getPixelPos();
assertNotNull(pixelPos);
assertEquals(2.3F, pixelPos.x, 1e-6F);
assertEquals(14.1F, pixelPos.y, 1e-6F);
} catch (HeadlessException e) {
System.out.println("A " + PlacemarkDialogTest.class + " test has not been performed: HeadlessException");
}
}
}
| 1,805 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OpenRGBImageViewActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/actions/window/OpenRGBImageViewActionTest.java | package org.esa.snap.rcp.actions.window;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.math.Range;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class OpenRGBImageViewActionTest {
@Test
public void testMergeChannelDefs_allValuesFromUserInput() {
final RGBImageProfile imageProfile = new RGBImageProfile("whatever",
new String[]{"r", "g", "b"},
null,
new Range[]{new Range(1, 2), new Range(3, 4), new Range(5, 6)});
final Band[] bands = new Band[3];
bands[0] = mock(Band.class);
bands[1] = mock(Band.class);
bands[2] = mock(Band.class);
final RGBChannelDef rgbChannelDef = OpenRGBImageViewAction.mergeRgbChannelDefs(imageProfile, bands);
assertEquals(1.0, rgbChannelDef.getMinDisplaySample(0), 1e-8);
assertEquals(2.0, rgbChannelDef.getMaxDisplaySample(0), 1e-8);
assertEquals(3.0, rgbChannelDef.getMinDisplaySample(1), 1e-8);
assertEquals(4.0, rgbChannelDef.getMaxDisplaySample(1), 1e-8);
assertEquals(5.0, rgbChannelDef.getMinDisplaySample(2), 1e-8);
assertEquals(6.0, rgbChannelDef.getMaxDisplaySample(2), 1e-8);
}
@Test
public void testMergeChannelDefs_someValuesFromBandChannelDef() {
final RGBImageProfile imageProfile = new RGBImageProfile("whatever",
new String[]{"r", "g", "b"},
null,
new Range[]{new Range(1, 2), new Range(Double.NaN, 4), new Range(5, Double.NaN)});
final Band[] bands = new Band[3];
bands[0] = mock(Band.class);
bands[1] = mock(Band.class);
final RGBChannelDef chDef_1 = new RGBChannelDef();
chDef_1.setMinDisplaySample(1, 0.13);
when(bands[1].getImageInfo()).thenReturn(new ImageInfo(chDef_1));
bands[2] = mock(Band.class);
final RGBChannelDef chDef_2 = new RGBChannelDef();
chDef_2.setMaxDisplaySample(2, 6.78);
when(bands[2].getImageInfo()).thenReturn(new ImageInfo(chDef_2));
final RGBChannelDef rgbChannelDef = OpenRGBImageViewAction.mergeRgbChannelDefs(imageProfile, bands);
assertEquals(1.0, rgbChannelDef.getMinDisplaySample(0), 1e-8);
assertEquals(2.0, rgbChannelDef.getMaxDisplaySample(0), 1e-8);
assertEquals(0.13, rgbChannelDef.getMinDisplaySample(1), 1e-8);
assertEquals(4.0, rgbChannelDef.getMaxDisplaySample(1), 1e-8);
assertEquals(5.0, rgbChannelDef.getMinDisplaySample(2), 1e-8);
assertEquals(6.78, rgbChannelDef.getMaxDisplaySample(2), 1e-8);
}
@Test
public void testMergeChannelDefs_someValuesFromColorPalette() {
final RGBImageProfile imageProfile = new RGBImageProfile("whatever",
new String[]{"r", "g", "b"},
null,
new Range[]{new Range(1, Double.NaN), new Range(3, 4), new Range(Double.NaN, 6)});
final Band[] bands = new Band[3];
bands[0] = mock(Band.class);
final ColorPaletteDef colorPaletteDef_0 = new ColorPaletteDef(0.8, 11.9);
when(bands[0].getImageInfo()).thenReturn(new ImageInfo(colorPaletteDef_0));
bands[1] = mock(Band.class);
bands[2] = mock(Band.class);
final ColorPaletteDef colorPaletteDef_2 = new ColorPaletteDef(0.9, 12.0);
when(bands[2].getImageInfo()).thenReturn(new ImageInfo(colorPaletteDef_2));
final RGBChannelDef rgbChannelDef = OpenRGBImageViewAction.mergeRgbChannelDefs(imageProfile, bands);
assertEquals(1.0, rgbChannelDef.getMinDisplaySample(0), 1e-8);
assertEquals(11.9, rgbChannelDef.getMaxDisplaySample(0), 1e-8);
assertEquals(3.0, rgbChannelDef.getMinDisplaySample(1), 1e-8);
assertEquals(4.0, rgbChannelDef.getMaxDisplaySample(1), 1e-8);
assertEquals(0.9, rgbChannelDef.getMinDisplaySample(2), 1e-8);
assertEquals(6.0, rgbChannelDef.getMaxDisplaySample(2), 1e-8);
}
}
| 4,044 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AttachPixelGeoCodingActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/actions/tools/AttachPixelGeoCodingActionTest.java | package org.esa.snap.rcp.actions.tools;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AttachPixelGeoCodingActionTest {
@Test
public void testGetValidBandCount_none() {
final Product product = new Product("test", "test_type", 10, 15);
final int validCount = AttachPixelGeoCodingAction.getValidBandCount(product);
assertEquals(0, validCount);
}
@Test
public void testGetValidBandCount_one() {
final Product product = new Product("test", "test_type", 11, 16);
final Band band = new Band("right", ProductData.TYPE_FLOAT64, 11, 16);
product.addBand(band);
final int validCount = AttachPixelGeoCodingAction.getValidBandCount(product);
assertEquals(1, validCount);
}
@Test
public void testGetValidBandCount_oneRight_oneWrong() {
final Product product = new Product("test", "test_type", 12, 17);
Band band = new Band("right", ProductData.TYPE_INT32, 12, 17);
product.addBand(band);
band = new Band("wrong", ProductData.TYPE_INT32, 3, 3);
product.addBand(band);
final int validCount = AttachPixelGeoCodingAction.getValidBandCount(product);
assertEquals(1, validCount);
}
@Test
public void testGetValidBandCount_threeRight_oneWrong_clippedAt2() {
final Product product = new Product("test", "test_type", 13, 18);
Band band = new Band("right_1", ProductData.TYPE_INT8, 13, 18);
product.addBand(band);
band = new Band("wrong", ProductData.TYPE_INT8, 3, 3);
product.addBand(band);
band = new Band("right_2", ProductData.TYPE_INT8, 13, 18);
product.addBand(band);
band = new Band("right_3", ProductData.TYPE_INT8, 13, 18);
product.addBand(band);
final int validCount = AttachPixelGeoCodingAction.getValidBandCount(product);
assertEquals(2, validCount);
}
@Test
public void testGetRequiredMemory() {
Product product = new Product("test", "test_type", 100, 180);
long memSize = AttachPixelGeoCodingAction.getRequiredMemory(product);
assertEquals(288000L, memSize);
product = new Product("test", "test_type", 190, 1200);
memSize = AttachPixelGeoCodingAction.getRequiredMemory(product);
assertEquals(3648000L, memSize);
}
}
| 2,511 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RecentPathsTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/actions/file/RecentPathsTest.java | package org.esa.snap.rcp.actions.file;
import com.bc.ceres.core.runtime.internal.Platform;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.prefs.Preferences;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
/**
* @author Norman
*/
public class RecentPathsTest {
private RecentPaths recentPaths;
@Before
public void setUp() throws Exception {
Preferences preferences = Preferences.userNodeForPackage(RecentPathsTest.class).node("test");
preferences.remove("recents");
recentPaths = new RecentPaths(Preferences.userNodeForPackage(RecentPathsTest.class).node("test"), "recents", false);
}
@Test
public void testEmpty() {
List<String> paths = recentPaths.get();
assertNotNull(paths);
assertTrue(paths.isEmpty());
}
@Test
public void testLastInIsFirstOut() {
recentPaths.add("a");
recentPaths.add("b");
recentPaths.add("c");
assertEquals(Arrays.asList("c", "b", "a"), recentPaths.get());
}
@Test
public void testEmptyEntriesAreNotAdded() {
recentPaths.add("a");
recentPaths.add("");
recentPaths.add("c");
assertEquals(Arrays.asList("c", "a"), recentPaths.get());
}
@Test
public void testEntriesWithIllegalCharsAreNotAdded() {
Assume.assumeTrue(Platform.ID.win.equals(Platform.getCurrentPlatform().getId()));
recentPaths.add("a");
recentPaths.add("C:\\Users\\Anton\\AppData\\Local\\Temp\\AERONET:AOD@551(@ESA)-2015-10-10.tif");
recentPaths.add("c");
assertEquals(Arrays.asList("c", "a"), recentPaths.get());
}
@Test
public void testEqualEntriesAreRemoved() {
recentPaths.add("a");
recentPaths.add("b");
recentPaths.add("a");
recentPaths.add("a");
assertEquals(Arrays.asList("a", "b"), recentPaths.get());
}
}
| 2,059 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CloseProductActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/actions/file/CloseProductActionTest.java | package org.esa.snap.rcp.actions.file;
import org.esa.snap.core.dataio.ProductSubsetDef;
import org.esa.snap.core.datamodel.Product;
import org.junit.Test;
import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import static org.junit.Assert.*;
/**
* @author Marco Peters
*/
public class CloseProductActionTest {
@Test
public void testFindFirstSourceProduct() throws Exception {
Product toBeClosedProduct = new Product("ToBeClosed", "Type", 100, 100);
Product dependentProduct = createDependentProduct(toBeClosedProduct);
HashSet<Product> stillOpen = new HashSet<>(Collections.singletonList(dependentProduct));
Product firstSourceProduct = CloseProductAction.findFirstSourceProduct(toBeClosedProduct, stillOpen);
assertEquals(dependentProduct, firstSourceProduct);
}
@Test
public void testFindFirstSourceProduct_IgnoreIndependent() throws Exception {
Product toBeClosedProduct = new Product("ToBeClosed", "Type", 100, 100);
Product dependingProduct = new Product("dependingProduct", "Type", 100, 100);
Product dependentProduct = createDependentProduct(dependingProduct);
HashSet<Product> stillOpen = new HashSet<>(Collections.singletonList(dependentProduct));
stillOpen.add(dependingProduct);
Product firstSourceProduct = CloseProductAction.findFirstSourceProduct(toBeClosedProduct, stillOpen);
assertNull(firstSourceProduct);
}
private Product createDependentProduct(Product toBeClosedProduct) throws IOException {
ProductSubsetDef subset = new ProductSubsetDef("subset");
subset.setSubSampling(2,2);
return toBeClosedProduct.createSubset(subset, "dependent", "none");
}
} | 1,766 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportKmzFileActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/actions/file/export/ExportKmzFileActionTest.java | package org.esa.snap.rcp.actions.file.export;
import com.bc.ceres.annotation.STTM;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.runtime.Config;
import org.junit.Test;
import java.nio.file.Path;
import java.nio.file.Paths;
import static org.junit.Assert.assertEquals;
public class ExportKmzFileActionTest {
@Test
@STTM("SNAP-237")
public void testSetGetLastDir() {
final String oldValue = Config.instance().load().preferences().get(AbstractExportImageAction.IMAGE_EXPORT_DIR_PREFERENCES_KEY, null);
try {
final String expectedDefault = SystemUtils.getUserHomeDir().getPath();
String lastDir = ExportKmzFileAction.getLastDir();
assertEquals(expectedDefault, lastDir);
final Path newPath = Paths.get(expectedDefault).resolve("subDir");
ExportKmzFileAction.setLastDir(newPath.toFile());
lastDir = ExportKmzFileAction.getLastDir();
assertEquals(newPath.toString(), lastDir);
} finally {
if (oldValue != null) {
Config.instance().load().preferences().put(AbstractExportImageAction.IMAGE_EXPORT_DIR_PREFERENCES_KEY, oldValue);
}
}
}
}
| 1,227 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportGeometryActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/actions/file/export/ExportGeometryActionTest.java | package org.esa.snap.rcp.actions.file.export;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.FeatureUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.actions.vector.VectorDataNodeImporter;
import org.geotools.data.simple.SimpleFeatureIterator;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.locationtech.jts.geom.*;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import static org.esa.snap.core.datamodel.PlainFeatureFactory.createPlainFeature;
import static org.esa.snap.core.datamodel.PlainFeatureFactory.createPlainFeatureType;
import static org.junit.Assert.*;
/**
* @author Marco Peters
*/
public class ExportGeometryActionTest {
private static Product product;
private static File tempDir;
@BeforeClass
public static void setUpTestClass() throws Exception {
product = new Product("world", "myWorld", 20, 10);
product.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 20, 10, -180, 90, 18, 18, 0.0, 0.0));
File tempTempFile = File.createTempFile("temp", null);
tempDir = new File(tempTempFile.getParentFile(), "ExportGeometryActionTest");
tempDir.mkdir();
tempTempFile.delete();
}
@AfterClass
public static void tearDown() throws Exception {
FileUtils.deleteTree(tempDir);
}
@Test
public void changeGeometryType() throws Exception {
SimpleFeatureType defaultFeatureType = PlainFeatureFactory.createDefaultFeatureType();
assertEquals(Geometry.class, defaultFeatureType.getGeometryDescriptor().getType().getBinding());
SimpleFeatureType changedFeatureType = ExportGeometryAction.changeGeometryType(defaultFeatureType, Polygon.class);
assertEquals(Polygon.class, changedFeatureType.getGeometryDescriptor().getType().getBinding());
}
@Test
public void testWritingShapeFile_Pins() throws Exception {
Placemark pin = Placemark.createPointPlacemark(PinDescriptor.getInstance(),
"name1",
"label1",
"",
new PixelPos(0, 0), new GeoPos(52.0, 10.0),
null);
ArrayList<SimpleFeature> features = new ArrayList<>();
features.add(pin.getFeature());
Class<Point> geomType = Point.class;
doExportImport(features, geomType);
}
@Test
public void testWritingShapeFile_Geometry() throws Exception {
SimpleFeatureType sft = createPlainFeatureType("Polygon", Geometry.class, DefaultGeographicCRS.WGS84);
GeometryFactory gf = new GeometryFactory();
Polygon polygon = gf.createPolygon(gf.createLinearRing(new Coordinate[]{
new Coordinate(0, 0),
new Coordinate(1, 0),
new Coordinate(0, 1),
new Coordinate(0, 0),
}), null);
SimpleFeature polygonFeature = createPlainFeature(sft, "_1", polygon, "");
ArrayList<SimpleFeature> features = new ArrayList<>();
features.add(polygonFeature);
Class<Polygon> geomType = Polygon.class;
doExportImport(features, geomType);
}
private void doExportImport(ArrayList<SimpleFeature> features, Class<? extends Geometry> geomType) throws IOException {
File tempFile = File.createTempFile("pins", null, tempDir);
try {
ExportGeometryAction.writeEsriShapefile(geomType, features, tempFile);
assertTrue(tempFile.exists());
VectorDataNode vectorDataNode = readIn(new File(String.format("%s_%s.shp", tempFile.getAbsolutePath(), geomType.getSimpleName())), product);
assertEquals(1, vectorDataNode.getFeatureCollection().getCount());
try (SimpleFeatureIterator readFeatures = vectorDataNode.getFeatureCollection().features()) {
while (readFeatures.hasNext()) {
SimpleFeature next = readFeatures.next();
assertNotNull(next.getDefaultGeometry());
}
}
} catch (Throwable t) {
t.printStackTrace();
fail(String.format("Throwable '%s: %s' not expected", t.getClass().getSimpleName(), t.getMessage()));
} finally {
boolean deleted = tempFile.delete();
if (!deleted) {
tempFile.deleteOnExit();
}
}
}
private VectorDataNode readIn(File file, Product product) throws IOException {
DefaultFeatureCollection featureCollection = FeatureUtils.loadShapefileForProduct(file,
product,
new DummyFeatureCrsProvider(),
ProgressMonitor.NULL);
ProductNodeGroup<VectorDataNode> vectorDataGroup = product.getVectorDataGroup();
String name = VectorDataNodeImporter.findUniqueVectorDataNodeName(featureCollection.getSchema().getName().getLocalPart(),
vectorDataGroup);
return new VectorDataNode(name, featureCollection);
}
private static class DummyFeatureCrsProvider implements FeatureUtils.FeatureCrsProvider {
@Override
public CoordinateReferenceSystem getFeatureCrs(Product product) {
return product.getSceneCRS();
}
@Override
public boolean clipToProductBounds() {
return true;
}
}
} | 5,701 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImportTrackActionTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/actions/vector/ImportTrackActionTest.java | package org.esa.snap.rcp.actions.vector;
import org.esa.snap.core.datamodel.CrsGeoCoding;
import org.geotools.feature.FeatureCollection;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.io.InputStreamReader;
import static org.junit.Assert.*;
/**
* @author Norman Fomferra
*/
public class ImportTrackActionTest {
@Test
public void testReadTrack() throws Exception {
CrsGeoCoding geoCoding = new CrsGeoCoding(DefaultGeographicCRS.WGS84, new Rectangle(360, 180), new AffineTransform());
InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("TrackData.csv"));
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = ImportTrackAction.readTrack(reader, geoCoding);
assertNotNull(featureCollection);
assertEquals(23, featureCollection.size());
// test ordering
SimpleFeature[] simpleFeatures = featureCollection.toArray(new SimpleFeature[0]);
assertEquals(23, simpleFeatures.length);
assertEquals("ID00000000", simpleFeatures[0].getID());
assertEquals("ID00000011", simpleFeatures[11].getID());
assertEquals("ID00000022", simpleFeatures[22].getID());
}
}
| 1,412 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductGroupNodeTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/nodes/ProductGroupNodeTest.java | package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.rcp.util.TestProducts;
import org.junit.Test;
import org.openide.awt.UndoRedo;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import static org.junit.Assert.*;
/**
* @author Norman Fomferra
*/
public class ProductGroupNodeTest {
@Test
public void testDefaultTree() throws Exception {
ProductManager productManager = new ProductManager();
ProductGroupNode rootNode = new ProductGroupNode(productManager);
Product product1 = TestProducts.createProduct1();
productManager.addProduct(product1);
assertEquals(1, rootNode.getChildren().getNodesCount());
assertEquals(PNode.class, rootNode.getChildren().getNodeAt(0).getClass());
PNode pNode = (PNode) rootNode.getChildren().getNodeAt(0);
assertSame(product1, pNode.getProduct());
assertEquals("[1] Test_Product_1", pNode.getDisplayName());
Children children = pNode.getChildren();
assertNotNull(children);
Node[] groupNodes = children.getNodes();
assertNotNull(groupNodes);
assertEquals(5, groupNodes.length);
assertEquals("Metadata", groupNodes[0].getDisplayName());
assertEquals("Vector Data", groupNodes[1].getDisplayName());
assertEquals("Tie-Point Grids", groupNodes[2].getDisplayName());
assertEquals("Bands", groupNodes[3].getDisplayName());
assertEquals("Masks", groupNodes[4].getDisplayName());
//assertEquals("Flag-Codings", groupNodes[2].getDisplayName());
//assertEquals("Index-Codings", groupNodes[3].getDisplayName());
for (Node groupNode : groupNodes) {
assertTrue(groupNode instanceof UndoRedo.Provider);
}
}
}
| 1,857 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ThirdPartyLicensesTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/about/ThirdPartyLicensesTest.java | package org.esa.snap.rcp.about;
import org.junit.Test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import static junit.framework.TestCase.assertEquals;
import static org.junit.Assert.assertNotNull;
public class ThirdPartyLicensesTest {
@Test
public void testLoadThirdPartyLicensesFromCsv_fromResource() {
InputStream is = ThirdPartyLicensesTest.class.getResourceAsStream("TEST_THIRDPARTY_LICENSES.txt");
final ThirdPartyLicensesCsvTable licensesCsvTable = new ThirdPartyLicensesCsvTable(new BufferedReader(new InputStreamReader(is)));
assertNotNull(licensesCsvTable);
final int abderaIdx = 0;
final int oroIdx = 63;
final int iTextIdx = 112;
assertEquals("abdera", licensesCsvTable.getName(abderaIdx));
assertEquals("oro", licensesCsvTable.getName(oroIdx));
assertEquals("iText", licensesCsvTable.getName(iTextIdx));
assertEquals("Atom client", licensesCsvTable.getDescrUse(abderaIdx));
assertEquals("Text processing", licensesCsvTable.getDescrUse(oroIdx));
assertEquals("PDF Library", licensesCsvTable.getDescrUse(iTextIdx));
assertEquals("Apache", licensesCsvTable.getIprOwner(0));
assertEquals("ORO", licensesCsvTable.getIprOwner(oroIdx));
assertEquals("lowagie", licensesCsvTable.getIprOwner(iTextIdx));
assertEquals("Apache License", licensesCsvTable.getLicense(abderaIdx));
assertEquals("Apache License", licensesCsvTable.getLicense(oroIdx));
assertEquals("MPL", licensesCsvTable.getLicense(iTextIdx));
assertEquals("http://abdera.apache.org/", licensesCsvTable.getIprOwnerUrl(abderaIdx));
assertEquals("http://jakarta.apache.org/oro/", licensesCsvTable.getIprOwnerUrl(oroIdx));
assertEquals("http://www.lowagie.com/iText/", licensesCsvTable.getIprOwnerUrl(iTextIdx));
assertEquals("https://www.apache.org/licenses/", licensesCsvTable.getLicenseUrl(abderaIdx));
assertEquals("https://www.apache.org/licenses/", licensesCsvTable.getLicenseUrl(oroIdx));
assertEquals("https://www.mozilla.org/en-US/MPL/", licensesCsvTable.getLicenseUrl(iTextIdx));
}
}
| 2,223 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
XStreamSessionIOTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/session/XStreamSessionIOTest.java | package org.esa.snap.rcp.session;
import org.esa.snap.core.util.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import static org.junit.Assert.assertEquals;
public class XStreamSessionIOTest {
private Path tempDirectory;
@Before
public void setUp() throws IOException {
tempDirectory = Files.createTempDirectory("xstream_test");
}
@After
public void tearDown() {
if (tempDirectory != null) {
FileUtils.deleteTree(tempDirectory.toFile());
}
}
@Test
public void testWriteReadSession() throws Exception {
Session session = new Session();
Session.ProductRef productRef = new Session.ProductRef();
productRef.refNo = 2;
productRef.productReaderPlugin = "theReaderPlug";
productRef.uri = new URI("file://some/where");
session.productRefs = new Session.ProductRef[] {productRef};
Session.ViewRef viewRef = new Session.ViewRef();
viewRef.type = "testType";
viewRef.productRefNo = 2;
session.viewRefs = new Session.ViewRef[] {viewRef};
session.modelVersion = "heffalump";
XStreamSessionIO xStreamSessionIO = new XStreamSessionIO();
File file = new File(tempDirectory.toFile(), "test,xml");
xStreamSessionIO.writeSession(session, file);
Session readSession = xStreamSessionIO.readSession(new FileReader(file));
assertEquals("heffalump", readSession.modelVersion);
assertEquals(1, readSession.productRefs.length);
assertEquals(productRef.refNo, readSession.productRefs[0].refNo);
assertEquals(productRef.productReaderPlugin, readSession.productRefs[0].productReaderPlugin);
assertEquals(productRef.uri.toString(), readSession.productRefs[0].uri.toString());
assertEquals(1, readSession.viewRefs.length);
assertEquals(viewRef.type, readSession.viewRefs[0].type);
assertEquals(viewRef.productRefNo, readSession.viewRefs[0].productRefNo);
}
}
| 2,196 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RasterImageLayerConfigurationPersistencyTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/session/dom/RasterImageLayerConfigurationPersistencyTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.session.dom;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.layer.RasterImageLayerType;
public class RasterImageLayerConfigurationPersistencyTest extends AbstractLayerConfigurationPersistencyTest {
public RasterImageLayerConfigurationPersistencyTest() {
super(LayerTypeRegistry.getLayerType(RasterImageLayerType.class));
}
@Override
protected Layer createLayer(LayerType layerType) throws Exception {
final PropertySet configuration = layerType.createLayerConfig(null);
final Band raster = getProductManager().getProduct(0).getBandAt(0);
configuration.setValue(RasterImageLayerType.PROPERTY_NAME_RASTER, raster);
return layerType.createLayer(null, configuration);
}
}
| 1,657 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FeatureLayerConfigurationPersistencyTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/session/dom/FeatureLayerConfigurationPersistencyTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.session.dom;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.geotools.styling.*;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.Polygon;
import org.esa.snap.core.util.FeatureUtils;
import org.esa.snap.rcp.layermanager.layersrc.shapefile.FeatureLayer;
import org.esa.snap.rcp.layermanager.layersrc.shapefile.FeatureLayerType;
import org.geotools.factory.CommonFactoryFinder;
import org.geotools.feature.FeatureCollection;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.filter.FilterFactory;
import java.io.IOException;
import java.net.URL;
public class FeatureLayerConfigurationPersistencyTest extends AbstractLayerConfigurationPersistencyTest {
public FeatureLayerConfigurationPersistencyTest() {
super(LayerTypeRegistry.getLayerType(FeatureLayerType.class));
}
@Override
protected Layer createLayer(LayerType layerType) throws Exception {
final PropertySet configuration = layerType.createLayerConfig(null);
final URL shapefileUrl = getClass().getResource("bundeslaender.shp");
configuration.setValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_URL, shapefileUrl);
configuration.setValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_CRS, DefaultGeographicCRS.WGS84);
final Coordinate[] coordinates = {
new Coordinate(-10, 50),
new Coordinate(+10, 50),
new Coordinate(+10, 30),
new Coordinate(-10, 30),
new Coordinate(-10, 50)
};
final GeometryFactory geometryFactory = new GeometryFactory();
final LinearRing ring = geometryFactory.createLinearRing(coordinates);
final Polygon clipGeometry = geometryFactory.createPolygon(ring, new LinearRing[0]);
configuration.setValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_CLIP_GEOMETRY, clipGeometry);
configuration.setValue(FeatureLayerType.PROPERTY_NAME_SLD_STYLE, createStyle());
FeatureCollection<SimpleFeatureType, SimpleFeature> fc;
try {
fc = FeatureUtils.createFeatureCollection(
shapefileUrl, DefaultGeographicCRS.WGS84, clipGeometry);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
return new FeatureLayer(layerType, fc, configuration);
}
private static Style createStyle() {
StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null);
FilterFactory filterFactory = CommonFactoryFinder.getFilterFactory(null);
PolygonSymbolizer symbolizer = styleFactory.createPolygonSymbolizer();
Fill fill = styleFactory.createFill(
filterFactory.literal("#FFAA00"),
filterFactory.literal(0.5)
);
symbolizer.setFill(fill);
StyleBuilder styleBuilder = new StyleBuilder();
Rule rule = styleBuilder.createRule(symbolizer);
//rule.setSymbolizers(new Symbolizer[]{symbolizer});
FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(rule);
//fts.setRules(new Rule[]{rule});
// @todo 1 tb/tb test this 2023-04-26
StyleImpl style = (StyleImpl) styleFactory.createStyle();
style.addFeatureTypeStyle(fts);
return style;
}
}
| 4,383 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RgbImageLayerConfigurationPersistencyTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/session/dom/RgbImageLayerConfigurationPersistencyTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.session.dom;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.layer.RgbImageLayerType;
public class RgbImageLayerConfigurationPersistencyTest extends AbstractLayerConfigurationPersistencyTest {
public RgbImageLayerConfigurationPersistencyTest() {
super(LayerTypeRegistry.getLayerType(RgbImageLayerType.class));
}
@Override
protected Layer createLayer(LayerType layerType) throws Exception {
final PropertySet configuration = layerType.createLayerConfig(null);
final Product product = createTestProduct("Test", "TEST");
addVirtualBand(product, "a", ProductData.TYPE_INT32, "17");
addVirtualBand(product, "b", ProductData.TYPE_INT32, "11");
addVirtualBand(product, "c", ProductData.TYPE_INT32, "67");
getProductManager().addProduct(product);
configuration.setValue("product", product);
configuration.setValue("expressionR", "a + b");
configuration.setValue("expressionG", "b + c");
configuration.setValue("expressionB", "a - c");
return layerType.createLayer(null, configuration);
}
}
| 2,078 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SessionManagerTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/session/dom/SessionManagerTest.java | package org.esa.snap.rcp.session.dom;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.session.SessionManager;
import org.junit.Test;
import java.io.File;
import static org.junit.Assert.*;
/**
* Created by muhammad.bc on 7/17/2015.
*/
public class SessionManagerTest {
@Test
public void testFileFilter() throws Exception {
SnapFileFilter filter = SessionManager.getDefault().getSessionFileFilter();
assertTrue(filter.accept(new File("test.snap")));
assertFalse(filter.accept(new File("test.nc")));
assertArrayEquals(new String[]{".snap"}, filter.getExtensions());
}
}
| 642 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractLayerConfigurationPersistencyTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/session/dom/AbstractLayerConfigurationPersistencyTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.session.dom;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.dom.DefaultDomElement;
import com.bc.ceres.binding.dom.DomElement;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerType;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.VirtualBand;
import org.junit.BeforeClass;
import org.junit.Test;
import java.io.File;
import java.lang.reflect.Array;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertSame;
import static org.junit.Assert.assertNotNull;
public abstract class AbstractLayerConfigurationPersistencyTest {
private static ProductManager productManager;
private final LayerType layerType;
protected AbstractLayerConfigurationPersistencyTest(LayerType layerType) {
assertNotNull(layerType);
this.layerType = layerType;
}
@BeforeClass
public static void setupClass() {
final Product product = createTestProduct("P", "T");
addVirtualBand(product, "V", ProductData.TYPE_INT32, "42");
productManager = new ProductManager();
productManager.addProduct(product);
}
protected static ProductManager getProductManager() {
return productManager;
}
protected static Product createTestProduct(String name, String type) {
Product product = new Product(name, type, 10, 10);
product.setFileLocation(new File(String.format("out/%s.dim", name)));
return product;
}
protected static RasterDataNode addVirtualBand(Product product, String bandName, int dataType, String expression) {
final Band band = new VirtualBand(bandName, dataType, 10, 10, expression);
product.addBand(band);
return band;
}
@Test
public void testLayerConfigurationPersistency() throws Exception {
final Layer layer = createLayer(layerType);
final SessionDomConverter domConverter = new SessionDomConverter(getProductManager());
final DomElement originalDomElement = new DefaultDomElement("configuration");
domConverter.convertValueToDom(layer.getConfiguration(), originalDomElement);
//System.out.println(originalDomElement.toXml());
PropertySet template = layer.getLayerType().createLayerConfig(null);
final PropertyContainer restoredConfiguration = (PropertyContainer) domConverter.convertDomToValue(originalDomElement, template);
compareConfigurations(layer.getConfiguration(), restoredConfiguration);
final DomElement restoredDomElement = new DefaultDomElement("configuration");
domConverter.convertValueToDom(restoredConfiguration, restoredDomElement);
// assertEquals(originalDomElement.toXml(), restoredDomElement.toXml());
}
protected abstract Layer createLayer(LayerType layerType) throws Exception;
private static void compareConfigurations(PropertySet originalConfiguration,
PropertySet restoredConfiguration) {
for (final Property originalModel : originalConfiguration.getProperties()) {
final PropertyDescriptor originalDescriptor = originalModel.getDescriptor();
final Property restoredModel = restoredConfiguration.getProperty(originalDescriptor.getName());
final PropertyDescriptor restoredDescriptor = restoredModel.getDescriptor();
assertNotNull(restoredModel);
assertSame(originalDescriptor.getName(), restoredDescriptor.getName());
assertSame(originalDescriptor.getType(), restoredDescriptor.getType());
if (originalDescriptor.isTransient()) {
assertEquals(originalDescriptor.isTransient(), restoredDescriptor.isTransient());
} else {
final Object originalValue = originalModel.getValue();
final Object restoredValue = restoredModel.getValue();
assertSame(originalValue.getClass(), restoredValue.getClass());
if (originalValue.getClass().isArray()) {
final int originalLength = Array.getLength(originalValue);
final int restoredLength = Array.getLength(restoredValue);
assertEquals(originalLength, restoredLength);
for (int i = 0; i < restoredLength; i++) {
assertEquals(Array.get(originalValue, i), Array.get(restoredValue, i));
}
}
}
}
}
}
| 5,596 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
NoDataLayerConfigurationPersistencyTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/session/dom/NoDataLayerConfigurationPersistencyTest.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.session.dom;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.layer.NoDataLayerType;
import org.junit.After;
import org.junit.Before;
import java.awt.Color;
public class NoDataLayerConfigurationPersistencyTest extends AbstractLayerConfigurationPersistencyTest {
private Product product;
private RasterDataNode raster;
public NoDataLayerConfigurationPersistencyTest() {
super(LayerTypeRegistry.getLayerType(NoDataLayerType.class));
}
@Before
public void setup() {
product = createTestProduct("Test", "Test");
raster = addVirtualBand(product, "virtualBand", ProductData.TYPE_INT32, "17");
getProductManager().addProduct(product);
}
@After
public void tearDown() {
getProductManager().removeProduct(product);
}
@Override
protected Layer createLayer(LayerType layerType) throws Exception {
final PropertySet configuration = layerType.createLayerConfig(null);
configuration.setValue("raster", raster);
configuration.setValue("color", new Color(17, 11, 67));
return layerType.createLayer(null, configuration);
}
}
| 2,166 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DateTimePickerCellEditorTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/util/DateTimePickerCellEditorTest.java | package org.esa.snap.rcp.util;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Test;
import java.text.DateFormat;
import java.util.Locale;
import java.util.TimeZone;
import static org.junit.Assert.*;
/**
* @author Marco Peters
*/
public class DateTimePickerCellEditorTest {
private static final DateFormat DATE_FORMAT = ProductData.UTC.createDateFormat("yyyy-MM-dd'T'HH:mm:ss");
private static final DateFormat TIME_FORMAT = ProductData.UTC.createDateFormat("HH:mm:ss");
@Test
public void testDateFormatTimeZone() throws Exception {
Locale.setDefault(Locale.ENGLISH);
DateTimePickerCellEditor editor = new DateTimePickerCellEditor(DATE_FORMAT, TIME_FORMAT);
DateFormat[] formats = editor.getFormats();
assertEquals(1, formats.length);
assertSame(DATE_FORMAT, formats[0]);
assertEquals(DATE_FORMAT, formats[0]);
assertEquals(TimeZone.getTimeZone("UTC"), formats[0].getTimeZone());
assertSame(TIME_FORMAT, editor.getTimeFormat());
assertEquals(TimeZone.getTimeZone("UTC"), editor.getTimeFormat().getTimeZone());
}
}
| 1,132 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultSelectionSupportTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/test/java/org/esa/snap/rcp/util/internal/DefaultSelectionSupportTest.java | package org.esa.snap.rcp.util.internal;
import org.esa.snap.rcp.util.ContextGlobalExtender;
import org.esa.snap.rcp.util.SelectionSupport;
import org.esa.snap.ui.product.ProductSceneView;
import org.junit.Assume;
import org.junit.Test;
import org.mockito.Mockito;
import org.openide.util.Utilities;
import java.awt.GraphicsEnvironment;
import static org.junit.Assert.assertEquals;
public class DefaultSelectionSupportTest {
@Test
public void testSingleSelection() {
Assume.assumeFalse("Cannot run in headless", GraphicsEnvironment.isHeadless());
ContextGlobalExtender globalExtender = Utilities.actionsGlobalContext().lookup(ContextGlobalExtender.class);
DefaultSelectionSupport<ProductSceneView> selectionChangeSupport = new DefaultSelectionSupport<>(ProductSceneView.class);
MySelectionChangeHandler changeListener = new MySelectionChangeHandler();
selectionChangeSupport.addHandler(changeListener);
ProductSceneView sceneView1 = Mockito.mock(ProductSceneView.class);
globalExtender.put("view", sceneView1);
assertEquals(1, changeListener.count);
globalExtender.remove("view");
assertEquals(0, changeListener.count);
}
@Test
public void testMultiSelection() {
Assume.assumeFalse("Cannot run in headless", GraphicsEnvironment.isHeadless());
ContextGlobalExtender globalExtender = Utilities.actionsGlobalContext().lookup(ContextGlobalExtender.class);
DefaultSelectionSupport<ProductSceneView> selectionChangeSupport = new DefaultSelectionSupport<>(ProductSceneView.class);
MySelectionChangeHandler changeListener = new MySelectionChangeHandler();
selectionChangeSupport.addHandler(changeListener);
ProductSceneView sceneView1 = Mockito.mock(ProductSceneView.class);
ProductSceneView sceneView2 = Mockito.mock(ProductSceneView.class);
ProductSceneView sceneView3 = Mockito.mock(ProductSceneView.class);
globalExtender.put("view1", sceneView1);
assertEquals(1, changeListener.count);
globalExtender.put("view2", sceneView2);
assertEquals(2, changeListener.count);
globalExtender.put("view3", sceneView3);
assertEquals(3, changeListener.count);
globalExtender.remove("view2");
assertEquals(2, changeListener.count);
}
private static class MySelectionChangeHandler implements SelectionSupport.Handler<ProductSceneView> {
volatile int count = 0;
@Override
public void selectionChange(ProductSceneView oldValue, ProductSceneView newValue) {
if (oldValue != null) {
count--;
}
if (newValue != null) {
count++;
}
}
}
}
| 2,775 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/package-info.java | /*
* Copyright (C) 2015 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
/**
* Provides SNAP's Rich Client Platform (RPC) API and the implementation of the
* SNAP Desktop application based on the NetBeans Platform.
* <p>
* The central class in this package is the {@link org.esa.snap.rcp.SnapApp}
* which represents the SNAP Desktop application.
* <p>
* {@link org.esa.snap.rcp.SnapDialogs} is a utility class used to display
* typical user information or interaction dialogs.
*/
package org.esa.snap.rcp; | 1,151 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SnapApp.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/SnapApp.java | package org.esa.snap.rcp;
import com.bc.ceres.core.ExtensionFactory;
import com.bc.ceres.core.ExtensionManager;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import com.formdev.flatlaf.FlatLightLaf;
import eu.esa.snap.netbeans.docwin.DocumentWindowManager;
import org.esa.snap.core.dataio.ProductReader;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.gpf.GPF;
import org.esa.snap.core.gpf.Operator;
import org.esa.snap.core.gpf.OperatorSpi;
import org.esa.snap.core.gpf.OperatorSpiRegistry;
import org.esa.snap.core.util.PreferencesPropertyMap;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.actions.file.OpenProductAction;
import org.esa.snap.rcp.actions.file.SaveProductAction;
import org.esa.snap.rcp.cli.SnapArgs;
import org.esa.snap.rcp.session.OpenSessionAction;
import org.esa.snap.rcp.util.ContextGlobalExtenderImpl;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.util.SelectionSupport;
import org.esa.snap.rcp.util.internal.DefaultSelectionSupport;
import org.esa.snap.runtime.Config;
import org.esa.snap.runtime.Engine;
import org.esa.snap.tango.TangoIcons;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.awt.NotificationDisplayer;
import org.openide.awt.StatusDisplayer;
import org.openide.awt.ToolbarPool;
import org.openide.awt.UndoRedo;
import org.openide.modules.ModuleInfo;
import org.openide.modules.OnStart;
import org.openide.modules.OnStop;
import org.openide.util.*;
import org.openide.util.lookup.ServiceProvider;
import org.openide.windows.OnShowing;
import org.openide.windows.WindowManager;
import javax.imageio.spi.IIORegistry;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.spi.ImageWriterSpi;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.util.List;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
/**
* The class {@code SnapApp} is a facade for SNAP Desktop applications. There is only a single instance of
* a SNAP application which is retrieved by
* <pre>
* SnapApp app = SnapApp.getDefault();
* </pre>
* {@code SnapApp} is the main entry point for most SNAP Desktop extensions. An extension might want to be informed
* about selection changes in the application. Here are some examples:
* <pre>
* app.getSelectionSupport(Product.class).addHandler(myProductSelectionHandler);
* app.getSelectionSupport(ProductNode.class).addHandler(myProductNodeSelectionHandler);
* app.getSelectionSupport(RasterDataNode.class).addHandler(myRasterDataNodeSelectionHandler);
* app.getSelectionSupport(ProductSceneView.class).addHandler(myViewSelectionHandler);
* </pre>
* Or might want to retrieve the currently selected objects:
* <pre>
* Product product = app.getSelectedProduct();
* ProductNode productNode = getSelectedProductNode();
* ProductSceneView view = app.getSelectedProductSceneView();
* // For any other type of selected object, use:
* Figure figure = Utilities.actionsGlobalContext().lookup(Figure.class);
* </pre>
* <p>
* If you want to alter the behaviour of the default implementation of the SNAP Desktop application,
* then register your derived class as a service using
* <pre>
* @ServiceProvider(service = MoonApp.class, supersedes = "SnapApp")
* public class MoonApp extends SnapApp {
* ...
* }
* </pre>
*
* @author Norman Fomferra
* @see SelectionSupport
* @see org.esa.snap.rcp.util.SelectionSupport.Handler
* @since 2.0
*/
@ServiceProvider(service = SnapApp.class)
@SuppressWarnings("UnusedDeclaration")
public class SnapApp {
private final static Logger LOG = Logger.getLogger(SnapApp.class.getName());
private final ProductManager productManager;
private final Map<Class<?>, SelectionSupport<?>> selectionChangeSupports;
private Engine engine;
/**
* Constructor.
* <p>
* As this class is a registered service, the constructor is not supposed to be called directly.
*/
public SnapApp() {
productManager = new ProductManager();
// Register a provider that delivers an UndoManager for a Product instance.
UndoManagerProvider undoManagerProvider = new UndoManagerProvider();
ExtensionManager.getInstance().register(Product.class, undoManagerProvider);
productManager.addListener(undoManagerProvider);
productManager.addListener(new MultiSizeWarningListener());
selectionChangeSupports = new HashMap<>();
}
/**
* Gets the SNAP application singleton which provides access to various SNAP APIs and resources.
* <p>
* The the method basically returns
* <pre>
* Lookup.getDefault().lookup(SnapApp.class)
* </pre>
*
* @return The SNAP applications global singleton instance.
*/
public static SnapApp getDefault() {
SnapApp instance = Lookup.getDefault().lookup(SnapApp.class);
if (instance == null) {
instance = new SnapApp();
}
return instance;
}
/**
* The method changes the default look and feel to FlatLaf Light on Windows, if the user has not changed the look and feel before.
* Because of two reasons. First, it looks nicer, and second but more important, it fixes a bug in the Windows look and feel.
* The bug is that icons disappear in the Analysis menu when one of the items clicked. It occurs in SNAP 10 with JDK11 and Netbeans 11.3.
*/
private static void initialiseLookAndFeel() {
if (Utilities.isWindows()) {
Preferences lafPreference = NbPreferences.root().node("laf");
if (lafPreference == null || lafPreference.get("laf", null) == null) {
try {
UIManager.setLookAndFeel(FlatLightLaf.class.getName());
lafPreference.put("laf", FlatLightLaf.class.getName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException |
UnsupportedLookAndFeelException e) {
LOG.warning("Could not set FlatLaf Light Look and Feel");
}
}
}
}
private static void initImageIO() {
// todo - actually this should be done in the activator of ceres-jai which does not exist yet
Lookup.Result<ModuleInfo> moduleInfos = Lookup.getDefault().lookupResult(ModuleInfo.class);
String ceresJaiCodeName = "org.esa.snap.ceres.jai";
Optional<? extends ModuleInfo> info = moduleInfos.allInstances().stream().filter(
moduleInfo -> ceresJaiCodeName.equals(moduleInfo.getCodeName())).findFirst();
if (info.isPresent()) {
ClassLoader classLoader = info.get().getClassLoader();
IIORegistry iioRegistry = IIORegistry.getDefaultInstance();
iioRegistry.registerServiceProviders(IIORegistry.lookupProviders(ImageReaderSpi.class, classLoader));
iioRegistry.registerServiceProviders(IIORegistry.lookupProviders(ImageWriterSpi.class, classLoader));
} else {
LOG.warning(String.format("Module '%s' not found. Not able to load image-IO services.", ceresJaiCodeName));
}
}
private static String getOperatorName(Operator operator) {
String operatorName = operator.getSpi().getOperatorDescriptor().getAlias();
if (operatorName == null) {
operatorName = operator.getSpi().getOperatorDescriptor().getName();
}
return operatorName;
}
private static <T extends ProductNode> T getProductNode(T explorerNode, T viewNode, ProductSceneView sceneView, SelectionSourceHint hint) {
switch (hint) {
case VIEW:
if (viewNode != null) {
return viewNode;
} else {
return explorerNode;
}
case EXPLORER:
if (explorerNode != null) {
return explorerNode;
} else {
return viewNode;
}
case AUTO:
default:
if (sceneView != null && sceneView.hasFocus()) {
return viewNode;
}
return explorerNode;
}
}
/**
* Gets SNAP's global document window manager. Use it to open your own document windows, or register a listener to
* be notified on window events such as opening, closing, selection, deselection.
*
* @return SNAP's global document window manager.
*/
public DocumentWindowManager getDocumentWindowManager() {
return DocumentWindowManager.getDefault();
}
/**
* Gets SNAP's global data product manager. Use it to add your own data product instances, or register a listener to
* be notified on product addition and removal events.
*
* @return SNAP's global product manager.
*/
public ProductManager getProductManager() {
return productManager;
}
/**
* @return SNAP's global undo / redo manager.
*/
public UndoRedo.Manager getUndoManager(Product product) {
return product.getExtension(UndoRedo.Manager.class);
}
/**
* @return SNAP's main frame window.
*/
public Frame getMainFrame() {
return WindowManager.getDefault().getMainWindow();
}
/**
* Sets the current status bar message.
*
* @param message The new status bar message.
*/
public void setStatusBarMessage(String message) {
StatusDisplayer.getDefault().setStatusText(message);
}
/**
* @return The SNAP application's name. The default is {@code "SNAP"}.
*/
public String getInstanceName() {
try {
return NbBundle.getBundle("org.netbeans.core.ui.Bundle").getString("LBL_ProductInformation");
} catch (Exception e) {
return "SNAP";
}
}
/**
* @return The user's application preferences.
*/
public Preferences getPreferences() {
return NbPreferences.forModule(getClass());
}
/**
* @return The SNAP logger.
*/
public Logger getLogger() {
return LOG;
}
/**
* Handles an error.
*
* @param message An error message.
* @param t An exception or {@code null}.
*/
public void handleError(String message, Throwable t) {
if (t != null) {
t.printStackTrace();
}
Dialogs.showError("Error", message);
getLogger().log(Level.SEVERE, message, t);
ImageIcon icon = TangoIcons.status_dialog_error(TangoIcons.Res.R16);
JLabel balloonDetails = new JLabel(message);
JButton popupDetails = new JButton("Report");
popupDetails.addActionListener(e -> {
try {
Desktop.getDesktop().browse(new URI("http://forum.step.esa.int/"));
} catch (URISyntaxException | IOException e1) {
getLogger().log(Level.SEVERE, message, e1);
}
});
NotificationDisplayer.getDefault().notify("Error",
icon,
balloonDetails,
popupDetails,
NotificationDisplayer.Priority.HIGH,
NotificationDisplayer.Category.ERROR);
}
/**
* Provides a {@link SelectionSupport} instance for object selections.
*
* @param type The type of selected objects whose selection state to observe.
* @return A selection support instance for the given object type, or {@code null}.
*/
public <T> SelectionSupport<T> getSelectionSupport(Class<T> type) {
@SuppressWarnings("unchecked")
DefaultSelectionSupport<T> selectionChangeSupport = (DefaultSelectionSupport<T>) selectionChangeSupports.get(type);
if (selectionChangeSupport == null) {
selectionChangeSupport = new DefaultSelectionSupport<>(type);
selectionChangeSupports.put(type, selectionChangeSupport);
}
return selectionChangeSupport;
}
/**
* @return The currently selected product scene view, or {@code null}.
*/
public ProductSceneView getSelectedProductSceneView() {
return Utilities.actionsGlobalContext().lookup(ProductSceneView.class);
}
/**
* Return the currently selected product node.
* <p>
* The {@link SelectionSourceHint hint} defines what is the primary and secondary selection source. Source is either the
* {@link SelectionSourceHint#VIEW scene view} or the {@link SelectionSourceHint#EXPLORER product explorer}. If it is set to
* {@link SelectionSourceHint#AUTO} the algorithm tries to make a good guess, checking which component has the focus.
*
* @return The currently selected product node, or {@code null}.
*/
public ProductNode getSelectedProductNode(SelectionSourceHint hint) {
ProductNode viewNode = null;
ProductSceneView productSceneView = getSelectedProductSceneView();
if (productSceneView != null) {
viewNode = productSceneView.getProduct();
}
ProductNode explorerNode = Utilities.actionsGlobalContext().lookup(ProductNode.class);
return getProductNode(explorerNode, viewNode, productSceneView, hint);
}
/**
* Return the currently selected product.
* <p>
* The {@link SelectionSourceHint hint} defines what is the primary and secondary selection source. Source is either the
* {@link SelectionSourceHint#VIEW scene view} or the {@link SelectionSourceHint#EXPLORER product explorer}. If it is set to
* {@link SelectionSourceHint#AUTO} the algorithm tries to make a good guess, checking which component has the focus.
*
* @param hint gives a hint to the implementation which selection source should be preferred.
* @return The currently selected product or {@code null}.
*/
public Product getSelectedProduct(SelectionSourceHint hint) {
Product viewProduct = null;
ProductSceneView productSceneView = getSelectedProductSceneView();
if (productSceneView != null) {
viewProduct = productSceneView.getProduct();
}
Product explorerProduct = null;
ProductNode productNode = Utilities.actionsGlobalContext().lookup(ProductNode.class);
if (productNode != null) {
explorerProduct = productNode.getProduct();
}
return getProductNode(explorerProduct, viewProduct, productSceneView, hint);
}
/**
* Gets an {@link AppContext} representation of the SNAP application.
* <p>
* Its main use is to provide compatibility for SNAP heritage GUI code (from BEAM & NEST) which used
* the {@link AppContext} interface.
*
* @return An {@link AppContext} representation of this {@code SnapApp}.
*/
public AppContext getAppContext() {
return new SnapContext();
}
/**
* Called if SNAP starts up. The method is not supposed to be called by clients directly.
* <p>
* Overrides should call {@code super.onStart()} as a first step unless they know what they are doing.
*/
public void onStart() {
engine = Engine.start(false);
initialiseLookAndFeel();
String toolbarConfig = "Standard";
if (Config.instance().debug()) {
WindowManager.getDefault().setRole("developer");
toolbarConfig = "Developer";
}
// See src/main/resources/org/esa/snap/rcp/layer.xml
// See src/main/resources/org/esa/snap/rcp/toolbars/Standard.xml
// See src/main/resources/org/esa/snap/rcp/toolbars/Developer.xml
ToolbarPool.getDefault().setConfiguration(toolbarConfig);
}
/**
* Called if SNAP shuts down. The method is not supposed to be called by clients directly.
* <p>
* Overrides should call {@code super.onStop()} in a final step unless they know what they are doing.
*/
public void onStop() {
engine.stop();
disposeProducts();
try {
getPreferences().flush();
} catch (BackingStoreException e) {
getLogger().log(Level.SEVERE, e.getMessage(), e);
}
}
/**
* Called if SNAP is showing on the user's desktop. The method is not supposed to be called by clients directly.
* <p>
* Overrides should call {@code super.onShowing()} as a first step unless they know whet they are doing.
*/
public void onShowing() {
getMainFrame().setTitle(getEmptyTitle());
getSelectionSupport(ProductSceneView.class).addHandler(new SceneViewListener());
getSelectionSupport(ProductNode.class).addHandler(new ProductNodeListener());
NodeNameListener nodeNameListener = new NodeNameListener();
getProductManager().addListener(new ProductManager.Listener() {
@Override
public void productAdded(ProductManager.Event event) {
event.getProduct().addProductNodeListener(nodeNameListener);
}
@Override
public void productRemoved(ProductManager.Event event) {
event.getProduct().removeProductNodeListener(nodeNameListener);
}
});
if (SnapArgs.getDefault().getSessionFile() != null) {
File sessionFile = SnapArgs.getDefault().getSessionFile().toFile();
if (sessionFile != null) {
new OpenSessionAction().openSession(sessionFile);
}
}
List<Path> fileList = SnapArgs.getDefault().getFileList();
if (!fileList.isEmpty()) {
OpenProductAction productAction = new OpenProductAction();
File[] files = fileList.stream().map(Path::toFile).filter(Objects::nonNull).toArray(File[]::new);
productAction.setFiles(files);
productAction.execute();
}
}
/**
* Called if SNAP is about to shut down. The method is not supposed to be called by clients directly.
* <p>
* Overrides should call {@code super.onTryStop()()} unless they know whet they are doing. The method should return
* immediately {@code false} if the super call returns {@code false}.
*
* @return {@code false} if the shutdown process shall be cancelled immediately. {@code true}, if it is ok
* to continue shut down.
*/
public boolean onTryStop() {
final ArrayList<Product> modifiedProducts = new ArrayList<>(5);
final Product[] products = getProductManager().getProducts();
for (final Product product : products) {
final ProductReader reader = product.getProductReader();
if (reader != null) {
final Object input = reader.getInput();
if (input instanceof Product) {
modifiedProducts.add(product);
}
}
if (!modifiedProducts.contains(product) && product.isModified()) {
modifiedProducts.add(product);
}
}
if (!modifiedProducts.isEmpty()) {
final StringBuilder message = new StringBuilder();
if (modifiedProducts.size() == 1) {
message.append("The following product has been modified:");
message.append("\n ").append(modifiedProducts.get(0).getDisplayName());
message.append("\n\nDo you wish to save it?");
} else {
message.append("The following products have been modified:");
for (Product modifiedProduct : modifiedProducts) {
message.append("\n ").append(modifiedProduct.getDisplayName());
}
message.append("\n\nDo you want to save them?");
}
Dialogs.Answer answer = Dialogs.requestDecision("Exit", message.toString(), true, null);
// decision request cancelled --> cancel SNAP shutdown
if (answer == Dialogs.Answer.YES) {
//Save Products in reverse order is necessary because derived products must be saved first
Collections.reverse(modifiedProducts);
for (Product modifiedProduct : modifiedProducts) {
Boolean saveStatus = new SaveProductAction(modifiedProduct).execute();
if (saveStatus == null) {
// save cancelled --> cancel SNAP shutdown
return false;
}
}
} else return answer != Dialogs.Answer.CANCELLED;
}
return true;
}
private void initGPF() {
GPF gpf = GPF.getDefaultInstance();
OperatorSpiRegistry operatorSpiRegistry = gpf.getOperatorSpiRegistry();
Set<OperatorSpi> services = operatorSpiRegistry.getServiceRegistry().getServices();
for (OperatorSpi service : services) {
LOG.info(String.format("GPF operator SPI: %s (alias '%s')", service.getClass(), service.getOperatorAlias()));
}
gpf.setProductManager(getProductManager());
gpf.setProgressMonitoredOperatorExecutor(operator -> {
SnapAppGPFOperatorExecutor snapAppGPFOperatorExecutor = new SnapAppGPFOperatorExecutor(operator);
snapAppGPFOperatorExecutor.executeWithBlocking();
});
}
private void updateMainFrameTitle(ProductSceneView sceneView) {
String title;
if (sceneView != null) {
Product product = sceneView.getProduct();
if (product != null) {
title = String.format("%s - %s - %s", sceneView.getSceneName(), product.getName(), getProductPath(product));
} else {
title = sceneView.getSceneName();
}
title = appendTitleSuffix(title);
} else {
title = getEmptyTitle();
}
getMainFrame().setTitle(title);
}
private void updateMainFrameTitle(ProductNode node) {
String title;
if (node != null) {
Product product = node.getProduct();
if (product != null) {
if (node == product) {
title = String.format("%s - [%s]", product.getDisplayName(), getProductPath(product));
} else {
title = String.format("%s - [%s] - [%s]", node.getDisplayName(), product.getName(), getProductPath(product));
}
} else {
title = node.getDisplayName();
}
title = appendTitleSuffix(title);
} else {
title = getEmptyTitle();
}
getMainFrame().setTitle(title);
}
private String getProductPath(Product product) {
File fileLocation = product.getFileLocation();
if (fileLocation != null) {
try {
return fileLocation.getCanonicalPath();
} catch (IOException e) {
return fileLocation.getAbsolutePath();
}
} else {
return "not saved";
}
}
private void disposeProducts() {
Product[] products = getProductManager().getProducts();
getProductManager().removeAllProducts();
for (Product product : products) {
product.dispose();
}
}
private String appendTitleSuffix(String title) {
String appendix = !Utilities.isMac() ? String.format(" - %s", getInstanceName()) : "";
return title + appendix;
}
private String getEmptyTitle() {
String instanceName = getInstanceName();
if (instanceName != null && instanceName.length() > 0) {
return String.format("%s", instanceName);
} else {
return String.format("[%s]", "Empty");
}
}
/**
* Provides a hint to {@link SnapApp#getSelectedProduct(SelectionSourceHint)} } which selection provider should be used as primary selection source
*/
public enum SelectionSourceHint {
/**
* The scene view shall be preferred as selection source.
*/
VIEW,
/**
* The product explorer shall be preferred as selection source.
*/
EXPLORER,
/**
* The primary selection source is automatically detected.
*/
AUTO,
}
/**
* This non-API class is public as an implementation detail. Don't use it, it may be removed anytime.
* <p>
* NetBeans {@code @OnStart}: {@code Runnable}s defined by various modules are invoked in parallel and as soon
* as possible. It is guaranteed that execution of all {@code runnable}s is finished
* before the startup sequence is claimed over.
*/
@OnStart
public static class StartOp implements Runnable {
@Override
public void run() {
LOG.info("Starting SNAP Desktop");
try {
SnapApp.getDefault().onStart();
} finally {
initImageIO();
SystemUtils.init3rdPartyLibsByCl(Lookup.getDefault().lookup(ClassLoader.class));
SnapApp.getDefault().initGPF();
}
}
}
/**
* This non-API class is public as an implementation detail. Don't use it, it may be removed anytime.
* <p>
* NetBeans {@code @OnShowing}: Annotation to place on a {@code Runnable} with default constructor which should be invoked as soon as the window
* system is shown. The {@code Runnable}s are invoked in AWT event dispatch thread one by one
*/
@OnShowing
public static class ShowingOp implements Runnable {
@Override
public void run() {
LOG.info("Showing SNAP Desktop");
SnapApp.getDefault().onShowing();
}
}
/**
* This non-API class is public as an implementation detail. Don't use it, it may be removed anytime.
* <p>
* NetBeans {@code @OnStop}: Annotation that can be applied to {@code Runnable} or {@code Callable<Boolean>}
* subclasses with default constructor which will be invoked during shutdown sequence or when the
* module is being shutdown.
* <p>
* First of all call {@code Callable}s are consulted to allow or deny proceeding with the shutdown.
* <p>
* If the shutdown is approved, all {@code Runnable}s registered are acknowledged and can perform the shutdown
* cleanup. The {@code Runnable}s are invoked in parallel. It is guaranteed their execution is finished before
* the shutdown sequence is over.
*/
@OnStop
public static class MaybeStopOp implements Callable {
@Override
public Boolean call() {
LOG.info("Request to stop SNAP Desktop");
return SnapApp.getDefault().onTryStop();
}
}
/**
* This non-API class is public as an implementation detail. Don't use it, it may be removed anytime.
*/
@OnStop
public static class StopOp implements Runnable {
@Override
public void run() {
LOG.info("Stopping SNAP Desktop");
SnapApp.getDefault().onStop();
}
}
/**
* This non-API class is public as an implementation detail. Don't use it, it may be removed anytime.
* <p>
* This class proxies the original ContextGlobalProvider and ensures that a set
* of additional objects remain in the GlobalContext regardless of the TopComponent
* selection.
*
* @see org.esa.snap.rcp.util.ContextGlobalExtenderImpl
*/
@ServiceProvider(
service = ContextGlobalProvider.class,
supersedes = "org.netbeans.modules.openide.windows.GlobalActionContextImpl"
)
public static class ActionContextExtender extends ContextGlobalExtenderImpl {
}
/**
* Associates objects with an undo manager.
*/
private static class UndoManagerProvider implements ExtensionFactory, ProductManager.Listener {
private final Map<Object, UndoRedo.Manager> undoManagers = new HashMap<>();
@Override
public Class<?>[] getExtensionTypes() {
return new Class<?>[]{UndoRedo.Manager.class};
}
@Override
public Object getExtension(Object object, Class<?> extensionType) {
return undoManagers.get(object);
}
@Override
public void productAdded(ProductManager.Event event) {
undoManagers.put(event.getProduct(), new UndoRedo.Manager());
}
@Override
public void productRemoved(ProductManager.Event event) {
UndoRedo.Manager manager = undoManagers.remove(event.getProduct());
if (manager != null) {
manager.die();
}
}
}
private static class SnapContext implements AppContext {
@Override
public ProductManager getProductManager() {
return getDefault().getProductManager();
}
@Override
public Product getSelectedProduct() {
return getDefault().getSelectedProduct(SelectionSourceHint.AUTO);
}
@Override
public Window getApplicationWindow() {
return getDefault().getMainFrame();
}
@Override
public String getApplicationName() {
return getDefault().getInstanceName();
}
@Override
public void handleError(String message, Throwable t) {
getDefault().handleError(message, t);
}
@Override
@Deprecated
public PropertyMap getPreferences() {
final Preferences preferences = getDefault().getPreferences();
return new PreferencesPropertyMap(preferences);
}
@Override
public ProductSceneView getSelectedProductSceneView() {
return getDefault().getSelectedProductSceneView();
}
}
private static class MultiSizeWarningListener implements ProductManager.Listener {
@Override
public void productAdded(ProductManager.Event event) {
final Product product = event.getProduct();
}
@Override
public void productRemoved(ProductManager.Event event) {
}
}
private class SceneViewListener implements SelectionSupport.Handler<ProductSceneView> {
@Override
public void selectionChange(ProductSceneView oldValue, ProductSceneView newValue) {
updateMainFrameTitle(newValue);
}
}
private class ProductNodeListener implements SelectionSupport.Handler<ProductNode> {
@Override
public void selectionChange(ProductNode oldValue, ProductNode newValue) {
updateMainFrameTitle(newValue);
}
}
private class NodeNameListener extends ProductNodeListenerAdapter {
@Override
public void nodeChanged(ProductNodeEvent event) {
if (ProductNode.PROPERTY_NAME_NAME.equals(event.getPropertyName())) {
updateMainFrameTitle(event.getSourceNode());
}
}
}
private class SnapAppGPFOperatorExecutor extends ProgressMonitorSwingWorker<Void, Void> {
private final Operator operator;
private SnapAppGPFOperatorExecutor(Operator operator) {
super(SnapApp.getDefault().getMainFrame(), "Executing " + getOperatorName(operator));
this.operator = operator;
}
@Override
protected Void doInBackground(ProgressMonitor pm) throws Exception {
operator.execute(pm);
return null;
}
}
}
| 31,939 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImageCursorSynchronizer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/sync/ImageCursorSynchronizer.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.sync;
import com.bc.ceres.glayer.support.ImageLayer;
import eu.esa.snap.netbeans.docwin.DocumentWindowManager;
import eu.esa.snap.netbeans.docwin.DocumentWindowManager.Predicate;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.tools.SyncImageCursorsAction;
import org.esa.snap.rcp.windows.ProductSceneViewTopComponent;
import org.esa.snap.ui.PixelPositionListener;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.windows.OnShowing;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.Map;
import java.util.WeakHashMap;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
/**
* @author Marco Peters, Norman Fomferra
*/
@OnShowing
public class ImageCursorSynchronizer implements Runnable {
public static final String PROPERTY_KEY_AUTO_SYNC_CURSORS = SyncImageCursorsAction.PREFERENCE_KEY;
private static final GeoPos INVALID_GEO_POS = new GeoPos(Float.NaN, Float.NaN);
private static final Predicate<Object, ProductSceneView> SCENE_VIEW_PREDICATE = Predicate.view(ProductSceneView.class);
private Map<ProductSceneView, ImageCursorOverlay> psvOverlayMap;
private Map<ProductSceneView, MyPixelPositionListener> viewPplMap;
private PsvListUpdater psvOverlayMapUpdater;
@Override
public void run() {
psvOverlayMap = new WeakHashMap<>();
viewPplMap = new WeakHashMap<>();
psvOverlayMapUpdater = new PsvListUpdater();
Preferences preferences = SnapApp.getDefault().getPreferences();
preferences.addPreferenceChangeListener(new ImageCursorSynchronizerPreferenceChangeListener());
}
private boolean isActive() {
return SnapApp.getDefault().getPreferences().getBoolean(PROPERTY_KEY_AUTO_SYNC_CURSORS,
SyncImageCursorsAction.PREFERENCE_DEFAULT_VALUE);
}
public void updateCursorOverlays(GeoPos geoPos, ProductSceneView sourceView) {
if (!isActive()) {
return;
}
for (Map.Entry<ProductSceneView, ImageCursorOverlay> entry : psvOverlayMap.entrySet()) {
final ProductSceneView view = entry.getKey();
ImageCursorOverlay overlay = entry.getValue();
if (overlay == null) {
if (view != sourceView) {
overlay = new ImageCursorOverlay(view, geoPos);
psvOverlayMap.put(view, overlay);
view.getLayerCanvas().addOverlay(overlay);
}
} else {
if (view != sourceView) {
overlay.setGeoPosition(geoPos);
view.getLayerCanvas().repaint();
} else {
view.getLayerCanvas().removeOverlay(overlay);
psvOverlayMap.put(view, null);
}
}
}
}
private void initPsvOverlayMap() {
WindowUtilities.getOpened(ProductSceneViewTopComponent.class)
.map(ProductSceneViewTopComponent::getView)
.forEach(this::addPPL);
}
private void clearPsvOverlayMap() {
for (Map.Entry<ProductSceneView, ImageCursorOverlay> entry : psvOverlayMap.entrySet()) {
final ProductSceneView view = entry.getKey();
removePPL(view);
view.getLayerCanvas().removeOverlay(entry.getValue());
}
psvOverlayMap.clear();
}
private void addPPL(ProductSceneView view) {
GeoCoding geoCoding = view.getProduct().getSceneGeoCoding();
if (geoCoding != null && geoCoding.canGetPixelPos()) {
psvOverlayMap.put(view, null);
MyPixelPositionListener ppl = new MyPixelPositionListener(view);
viewPplMap.put(view, ppl);
view.addPixelPositionListener(ppl);
}
}
private void removePPL(ProductSceneView view) {
MyPixelPositionListener ppl = viewPplMap.get(view);
if (ppl != null) {
viewPplMap.remove(view);
view.removePixelPositionListener(ppl);
}
}
private class PsvListUpdater implements DocumentWindowManager.Listener<Object, ProductSceneView> {
@Override
public void windowOpened(DocumentWindowManager.Event<Object, ProductSceneView> e) {
addPPL(e.getWindow().getView());
}
@Override
public void windowClosed(DocumentWindowManager.Event<Object, ProductSceneView> e) {
removePPL(e.getWindow().getView());
}
}
private class MyPixelPositionListener implements PixelPositionListener {
private final ProductSceneView view;
private MyPixelPositionListener(ProductSceneView view) {
this.view = view;
}
@Override
public void pixelPosChanged(ImageLayer baseImageLayer, int pixelX, int pixelY, int currentLevel,
boolean pixelPosValid, MouseEvent e) {
PixelPos pixelPos = computeLevelZeroPixelPos(baseImageLayer, pixelX, pixelY, currentLevel);
GeoPos geoPos = view.getRaster().getGeoCoding().getGeoPos(pixelPos, null);
updateCursorOverlays(geoPos, view);
}
private PixelPos computeLevelZeroPixelPos(ImageLayer imageLayer, int pixelX, int pixelY, int currentLevel) {
if (currentLevel != 0) {
AffineTransform i2mTransform = imageLayer.getImageToModelTransform(currentLevel);
Point2D modelP = i2mTransform.transform(new Point2D.Double(pixelX + 0.5, pixelY + 0.5), null);
AffineTransform m2iTransform = imageLayer.getModelToImageTransform();
Point2D imageP = m2iTransform.transform(modelP, null);
return new PixelPos(new Float(imageP.getX()), new Float(imageP.getY()));
} else {
return new PixelPos(pixelX + 0.5, pixelY + 0.5);
}
}
@Override
public void pixelPosNotAvailable() {
updateCursorOverlays(INVALID_GEO_POS, null);
}
}
private class ImageCursorSynchronizerPreferenceChangeListener implements PreferenceChangeListener {
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
if (PROPERTY_KEY_AUTO_SYNC_CURSORS.equals(evt.getKey())) {
if (isActive()) {
initPsvOverlayMap();
DocumentWindowManager.getDefault().addListener(SCENE_VIEW_PREDICATE, psvOverlayMapUpdater);
} else {
DocumentWindowManager.getDefault().removeListener(SCENE_VIEW_PREDICATE, psvOverlayMapUpdater);
clearPsvOverlayMap();
}
}
}
}
}
| 7,736 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImageCursorOverlay.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/sync/ImageCursorOverlay.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.sync;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.grender.Viewport;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.product.ProductSceneView;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
/**
* @author Marco Peters
* @since BEAM 4.6
*/
class ImageCursorOverlay implements LayerCanvas.Overlay {
private static final int MAX_CROSSHAIR_SIZE = 20;
private final ProductSceneView sceneView;
private GeoPos geoPosition;
private BasicStroke cursorStroke;
private Color cursorColor;
ImageCursorOverlay(ProductSceneView sceneView, GeoPos geoPos) {
this.sceneView = sceneView;
geoPosition = geoPos;
cursorStroke = new BasicStroke(1F);
cursorColor = Color.WHITE;
}
public void setGeoPosition(GeoPos geoPosition) {
this.geoPosition = geoPosition;
}
@Override
public void paintOverlay(LayerCanvas canvas, Rendering rendering) {
if (geoPosition == null || !geoPosition.isValid()) {
return;
}
final GeoCoding geoCoding = sceneView.getRaster().getGeoCoding();
if (!geoCoding.canGetPixelPos()) {
return;
}
final Product product = sceneView.getRaster().getProduct();
final PixelPos pixelPos = geoCoding.getPixelPos(geoPosition, null);
if (!pixelPos.isValid() || !product.containsPixel(pixelPos)) {
return;
}
final Viewport viewport = canvas.getViewport();
drawCursor(rendering.getGraphics(), viewport, pixelPos);
}
private void drawCursor(Graphics2D graphics, Viewport viewport, PixelPos pixelPos) {
AffineTransform i2mTransform = sceneView.getBaseImageLayer().getImageToModelTransform();
AffineTransform m2vTransform = viewport.getModelToViewTransform();
AffineTransform i2vTransform = new AffineTransform(m2vTransform);
i2vTransform.concatenate(i2mTransform);
Point centerPixel = new Point((int) Math.floor(pixelPos.x), (int) Math.floor(pixelPos.y));
Rectangle pixelImageRect = new Rectangle(centerPixel, new Dimension(1, 1));
Rectangle2D pixelViewRect = i2vTransform.createTransformedShape(pixelImageRect).getBounds2D();
graphics.setStroke(cursorStroke);
graphics.setColor(cursorColor);
graphics.setXORMode(Color.BLACK);
graphics.draw(pixelViewRect);
if (pixelViewRect.getBounds2D().getWidth() < MAX_CROSSHAIR_SIZE) {
drawCrosshair(graphics, i2vTransform, centerPixel, pixelViewRect);
}
}
private void drawCrosshair(Graphics2D graphics, AffineTransform i2vTransform, Point centerPixel,
Rectangle2D pixelViewRect) {
Rectangle surroundImageRect = new Rectangle(centerPixel.x - 1, centerPixel.y - 1, 3, 3);
Rectangle2D surroundViewRect = i2vTransform.createTransformedShape(surroundImageRect).getBounds2D();
double scale = MAX_CROSSHAIR_SIZE / surroundViewRect.getBounds2D().getWidth();
if (scale > 1) {
double newWidth = surroundViewRect.getWidth() * scale;
double newHeight = surroundViewRect.getHeight() * scale;
double newX = surroundViewRect.getCenterX() - newWidth / 2;
double newY = surroundViewRect.getCenterY() - newHeight / 2;
surroundViewRect.setRect(newX, newY, newWidth, newHeight);
}
graphics.draw(surroundViewRect);
Line2D.Double northLine = new Line2D.Double(surroundViewRect.getCenterX(), surroundViewRect.getMinY(),
surroundViewRect.getCenterX(), pixelViewRect.getMinY());
Line2D.Double eastLine = new Line2D.Double(surroundViewRect.getMaxX(), surroundViewRect.getCenterY(),
pixelViewRect.getMaxX(), surroundViewRect.getCenterY());
Line2D.Double southLine = new Line2D.Double(surroundViewRect.getCenterX(), surroundViewRect.getMaxY(),
surroundViewRect.getCenterX(), pixelViewRect.getMaxY());
Line2D.Double westLine = new Line2D.Double(surroundViewRect.getMinX(), surroundViewRect.getCenterY(),
pixelViewRect.getMinX(), surroundViewRect.getCenterY());
graphics.draw(northLine);
graphics.draw(eastLine);
graphics.draw(southLine);
graphics.draw(westLine);
}
}
| 5,604 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImageViewSynchronizer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/sync/ImageViewSynchronizer.java | package org.esa.snap.rcp.sync;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.swing.LayerCanvasModel;
import com.bc.ceres.grender.Viewport;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.tools.SyncImageViewsAction;
import org.esa.snap.rcp.windows.ProductSceneViewTopComponent;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.Utilities;
import org.openide.windows.OnShowing;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
/**
* @author Norman
*/
@OnShowing
public class ImageViewSynchronizer implements Runnable {
public static final String PROPERTY_KEY_AUTO_SYNC_VIEWS = SyncImageViewsAction.PREFERENCE_KEY;
private ProductSceneView lastView;
private LayerCanvasModelChangeHandler layerCanvasModelChangeHandler;
@Override
public void run() {
layerCanvasModelChangeHandler = new LayerCanvasModelChangeHandler();
Preferences preferences = SnapApp.getDefault().getPreferences();
preferences.addPreferenceChangeListener(new ImageViewSynchronizerPreferenceChangeListener());
Lookup.Result<ProductSceneView> lookupResult = Utilities.actionsGlobalContext().lookupResult(ProductSceneView.class);
lookupResult.addLookupListener(new ImageViewSynchronizerLookupListener());
syncImageViewsWithSelectedView();
}
private void syncImageViewsWithSelectedView() {
ProductSceneView currentSceneView = SnapApp.getDefault().getSelectedProductSceneView();
if (currentSceneView != null) {
syncImageViews(currentSceneView);
}
}
private void syncImageViews(ProductSceneView currentSceneView) {
if (isActive()) {
WindowUtilities.getOpened(ProductSceneViewTopComponent.class).forEach(topComponent -> {
ProductSceneView oldSceneView = topComponent.getView();
if (oldSceneView != currentSceneView) {
currentSceneView.synchronizeViewportIfPossible(oldSceneView);
}
});
}
}
private boolean isActive() {
return SnapApp.getDefault().getPreferences().getBoolean(PROPERTY_KEY_AUTO_SYNC_VIEWS,
SyncImageViewsAction.PREFERENCE_DEFAULT_VALUE);
}
private class LayerCanvasModelChangeHandler implements LayerCanvasModel.ChangeListener {
@Override
public void handleLayerPropertyChanged(Layer layer, PropertyChangeEvent event) {
}
@Override
public void handleLayerDataChanged(Layer layer, Rectangle2D modelRegion) {
}
@Override
public void handleLayersAdded(Layer parentLayer, Layer[] childLayers) {
}
@Override
public void handleLayersRemoved(Layer parentLayer, Layer[] childLayers) {
}
@Override
public void handleViewportChanged(Viewport viewport, boolean orientationChanged) {
syncImageViewsWithSelectedView();
}
}
private class ImageViewSynchronizerPreferenceChangeListener implements PreferenceChangeListener {
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
if (PROPERTY_KEY_AUTO_SYNC_VIEWS.equals(evt.getKey())) {
syncImageViewsWithSelectedView();
}
}
}
private class ImageViewSynchronizerLookupListener implements LookupListener {
@Override
public void resultChanged(LookupEvent ev) {
ProductSceneView newView = SnapApp.getDefault().getSelectedProductSceneView();
if (lastView != newView) {
final ProductSceneView oldView = lastView;
if (oldView != null) {
if (oldView.getLayerCanvas() != null) {
oldView.getLayerCanvas().getModel().removeChangeListener(layerCanvasModelChangeHandler);
}
}
lastView = newView;
if (lastView != null) {
syncImageViews(lastView);
if (lastView.getLayerCanvas() != null) {
lastView.getLayerCanvas().getModel().addChangeListener(layerCanvasModelChangeHandler);
}
}
}
}
}
}
| 4,581 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultCursorSynchronizer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/sync/DefaultCursorSynchronizer.java | package org.esa.snap.rcp.sync;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.rcp.windows.ProductSceneViewTopComponent;
import org.esa.snap.ui.product.ProductSceneView;
import java.util.HashMap;
import java.util.Map;
/**
* @author Tonio Fincke
*/
public class DefaultCursorSynchronizer {
private Map<ProductSceneView, ImageCursorOverlay> psvOverlayMap;
private boolean enabled;
public DefaultCursorSynchronizer() {
psvOverlayMap = new HashMap<>();
enabled = false;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
if (this.enabled != enabled) {
if (enabled) {
initPsvOverlayMap();
} else {
clearPsvOverlayMap();
}
this.enabled = enabled;
}
}
public void updateCursorOverlays(GeoPos geoPos) {
if (!isEnabled()) {
return;
}
for (Map.Entry<ProductSceneView, ImageCursorOverlay> entry : psvOverlayMap.entrySet()) {
final ProductSceneView view = entry.getKey();
ImageCursorOverlay overlay = entry.getValue();
if (overlay == null) {
overlay = new ImageCursorOverlay(view, geoPos);
psvOverlayMap.put(view, overlay);
view.getLayerCanvas().addOverlay(overlay);
} else {
overlay.setGeoPosition(geoPos);
view.getLayerCanvas().repaint();
}
}
}
private void initPsvOverlayMap() {
WindowUtilities.getOpened(ProductSceneViewTopComponent.class)
.map(ProductSceneViewTopComponent::getView)
.forEach(this::addPPL);
}
private void clearPsvOverlayMap() {
for (Map.Entry<ProductSceneView, ImageCursorOverlay> entry : psvOverlayMap.entrySet()) {
final ProductSceneView view = entry.getKey();
view.getLayerCanvas().removeOverlay(entry.getValue());
}
psvOverlayMap.clear();
}
private void addPPL(ProductSceneView view) {
GeoCoding geoCoding = view.getProduct().getSceneGeoCoding();
if (geoCoding != null && geoCoding.canGetPixelPos()) {
psvOverlayMap.put(view, null);
}
}
}
| 2,412 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OpenLayerEditorAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/OpenLayerEditorAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import org.esa.snap.ui.UIUtils;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingUtilities;
import java.awt.event.ActionEvent;
class OpenLayerEditorAction extends AbstractAction {
OpenLayerEditorAction() {
super("Open Layer Editor", UIUtils.loadImageIcon("icons/LayerEditor24.png"));
putValue(Action.ACTION_COMMAND_KEY, getClass().getName());
}
@Override
public void actionPerformed(ActionEvent e) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final TopComponent layerEditorTopComponent = WindowManager.getDefault().findTopComponent("LayerEditorTopComponent");
layerEditorTopComponent.open();
layerEditorTopComponent.requestActive();
}
});
}
}
| 1,674 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerManagerForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/LayerManagerForm.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.support.AbstractLayerListener;
import com.bc.ceres.glayer.support.LayerUtils;
import com.bc.ceres.swing.TreeCellExtender;
import com.jidesoft.swing.CheckBoxTree;
import com.jidesoft.swing.CheckBoxTreeSelectionModel;
import org.esa.snap.core.layer.MaskLayerType;
import org.esa.snap.rcp.layermanager.layersrc.SelectLayerSourceAssistantPage;
import org.esa.snap.rcp.windows.ToolTopComponent;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.help.HelpDisplayer;
import org.esa.snap.ui.layer.LayerSourceAssistantPane;
import org.esa.snap.ui.layer.LayerSourceDescriptor;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.VectorDataLayer;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.DropMode;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSlider;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
class LayerManagerForm implements AbstractLayerForm {
private final ProductSceneView view;
private final ToolTopComponent parentComponent;
private CheckBoxTree layerTree;
private JSlider transparencySlider;
private JSlider swipeSlider;
private JPanel control;
private boolean adjusting;
private LayerTreeModel layerTreeModel;
private JLabel transparencyLabel;
private JLabel swipeLabel;
private RemoveLayerAction removeLayerAction;
private MoveLayerUpAction moveLayerUpAction;
private MoveLayerDownAction moveLayerDownAction;
private MoveLayerLeftAction moveLayerLeftAction;
private MoveLayerRightAction moveLayerRightAction;
private OpenLayerEditorAction openLayerEditorAction;
private ZoomToLayerAction zoomToLayerAction;
private LayerManagerForm.TransparencyChangeListener transparencyChangeListener;
private LayerManagerForm.SwipeChangeListener swipeChangeListener;
LayerManagerForm(ToolTopComponent parentComponent) {
super();
this.parentComponent = parentComponent;
this.view = parentComponent.getSelectedProductSceneView();
transparencyChangeListener = new TransparencyChangeListener();
swipeChangeListener = new SwipeChangeListener();
initUI();
}
private void initUI() {
layerTreeModel = new LayerTreeModel(view.getRootLayer());
layerTree = createCheckBoxTree(layerTreeModel);
layerTree.setCellRenderer(new MyTreeCellRenderer());
TreeCellExtender.equip(layerTree);
Hashtable<Integer, JLabel> transparencySliderLabelTable = new Hashtable<>();
transparencySliderLabelTable.put(0, createSliderLabel("0%"));
transparencySliderLabelTable.put(127, createSliderLabel("50%"));
transparencySliderLabelTable.put(255, createSliderLabel("100%"));
transparencySlider = new JSlider(0, 255, 0);
transparencySlider.setLabelTable(transparencySliderLabelTable);
transparencySlider.setPaintLabels(true);
transparencySlider.addChangeListener(new TransparencySliderListener());
transparencyLabel = new JLabel("Transparency:");
Hashtable<Integer, JLabel> swipeSliderLabelTable = new Hashtable<>();
swipeSliderLabelTable.put(0, createSliderLabel("0%"));
swipeSliderLabelTable.put(50, createSliderLabel("50%"));
swipeSliderLabelTable.put(100, createSliderLabel("100%"));
swipeSlider = new JSlider(0, 100, 0);
swipeSlider.setLabelTable(swipeSliderLabelTable);
swipeSlider.setPaintLabels(true);
swipeSlider.addChangeListener(new SwipeSliderListener());
swipeLabel = new JLabel("Swipe:");
final JPanel sliderPanel = GridBagUtils.createPanel();
final GridBagConstraints slidegbc = new GridBagConstraints();
slidegbc.anchor = GridBagConstraints.NORTHWEST;
slidegbc.fill = GridBagConstraints.HORIZONTAL;
slidegbc.gridy = 0;
slidegbc.gridx = 0;
sliderPanel.add(transparencyLabel, slidegbc);
slidegbc.gridx = 1;
slidegbc.weightx = 2;
sliderPanel.add(transparencySlider, slidegbc);
slidegbc.gridy++;
slidegbc.gridx = 0;
sliderPanel.add(swipeLabel, slidegbc);
slidegbc.gridx = 1;
slidegbc.weightx = 2;
sliderPanel.add(swipeSlider, slidegbc);
getRootLayer().addListener(new RootLayerListener());
AbstractButton addButton = createToolButton("icons/Plus24.gif");
addButton.addActionListener(new AddLayerActionListener());
removeLayerAction = new RemoveLayerAction();
AbstractButton removeButton = ToolButtonFactory.createButton(removeLayerAction, false);
openLayerEditorAction = new OpenLayerEditorAction();
AbstractButton openButton = ToolButtonFactory.createButton(openLayerEditorAction, false);
zoomToLayerAction = new ZoomToLayerAction();
AbstractButton zoomButton = ToolButtonFactory.createButton(zoomToLayerAction, false);
moveLayerUpAction = new MoveLayerUpAction();
AbstractButton upButton = ToolButtonFactory.createButton(moveLayerUpAction, false);
moveLayerDownAction = new MoveLayerDownAction();
AbstractButton downButton = ToolButtonFactory.createButton(moveLayerDownAction, false);
moveLayerLeftAction = new MoveLayerLeftAction();
AbstractButton leftButton = ToolButtonFactory.createButton(moveLayerLeftAction, false);
moveLayerRightAction = new MoveLayerRightAction();
AbstractButton rightButton = ToolButtonFactory.createButton(moveLayerRightAction, false);
AbstractButton helpButton = createToolButton("icons/Help22.png");
helpButton.setToolTipText("Help."); /*I18N*/
helpButton.setName("helpButton");
helpButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
HelpDisplayer.show(Bundle.CTL_LayerManagerTopComponent_HelpId());
}
});
final JPanel actionBar = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.CENTER;
gbc.fill = GridBagConstraints.NONE;
gbc.insets.top = 2;
gbc.gridy = 0;
actionBar.add(addButton, gbc);
gbc.gridy++;
actionBar.add(removeButton, gbc);
gbc.gridy++;
actionBar.add(openButton, gbc);
gbc.gridy++;
actionBar.add(zoomButton, gbc);
gbc.gridy++;
actionBar.add(upButton, gbc);
gbc.gridy++;
actionBar.add(downButton, gbc);
gbc.gridy++;
actionBar.add(leftButton, gbc);
gbc.gridy++;
actionBar.add(rightButton, gbc);
gbc.gridy++;
gbc.insets.bottom = 0;
gbc.fill = GridBagConstraints.VERTICAL;
gbc.weighty = 1.0;
gbc.gridwidth = 2;
actionBar.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy = 10;
gbc.anchor = GridBagConstraints.EAST;
actionBar.add(helpButton, gbc);
JPanel layerPanel = new JPanel(new BorderLayout(4, 4));
layerPanel.add(new JScrollPane(layerTree), BorderLayout.CENTER);
layerPanel.add(sliderPanel, BorderLayout.SOUTH);
control = new JPanel(new BorderLayout(4, 4));
control.add(layerPanel, BorderLayout.CENTER);
control.add(actionBar, BorderLayout.EAST);
initLayerTreeVisibility(view.getRootLayer());
updateFormControl();
}
private static JLabel createSliderLabel(String text) {
JLabel label = new JLabel(text);
Font oldFont = label.getFont();
Font newFont = oldFont.deriveFont(oldFont.getSize2D() * 0.85f);
label.setFont(newFont);
return label;
}
public Layer getRootLayer() {
return view.getRootLayer();
}
@Override
public JComponent getFormControl() {
return control;
}
@Override
public void updateFormControl() {
Layer selectedLayer = getSelectedLayer();
updateLayerStyleUI(selectedLayer);
updateLayerTreeSelection(selectedLayer);
boolean isLayerSelected = selectedLayer != null;
removeLayerAction.setEnabled(isLayerSelected && !isLayerProtected(selectedLayer));
openLayerEditorAction.setEnabled(isLayerSelected);
moveLayerUpAction.setEnabled(isLayerSelected && moveLayerUpAction.canMove(selectedLayer));
moveLayerDownAction.setEnabled(isLayerSelected && moveLayerDownAction.canMove(selectedLayer));
moveLayerLeftAction.setEnabled(isLayerSelected && moveLayerLeftAction.canMove(selectedLayer));
moveLayerRightAction.setEnabled(isLayerSelected && moveLayerRightAction.canMove(selectedLayer));
zoomToLayerAction.setEnabled(isLayerSelected);
}
public static boolean isLayerProtected(Layer layer) {
return isLayerProtectedImpl(layer) || isChildLayerProtected(layer);
}
private Layer getSelectedLayer() {
return view.getSelectedLayer();
}
private static boolean isLayerProtectedImpl(Layer layer) {
return layer.getId().equals(ProductSceneView.BASE_IMAGE_LAYER_ID);
}
private static boolean isChildLayerProtected(Layer selectedLayer) {
Layer[] children = selectedLayer.getChildren().toArray(new Layer[selectedLayer.getChildren().size()]);
for (Layer childLayer : children) {
if (isLayerProtectedImpl(childLayer) ||
isChildLayerProtected(childLayer)) {
return true;
}
}
return false;
}
private static boolean isLayerNameEditable(Layer layer) {
if (layer instanceof VectorDataLayer ||
layer.getConfiguration().isPropertyDefined(MaskLayerType.PROPERTY_NAME_MASK)) {
return false;
}
return true;
}
private static Layer getLayer(TreePath path) {
if (path == null) {
return null;
}
return (Layer) path.getLastPathComponent();
}
private void initLayerTreeVisibility(final Layer layer) {
updateLayerTreeVisibility(layer);
for (Layer childLayer : layer.getChildren()) {
initLayerTreeVisibility(childLayer);
}
}
private void updateLayerTreeVisibility(Layer layer) {
CheckBoxTreeSelectionModel checkBoxTreeSelectionModel = layerTree.getCheckBoxTreeSelectionModel();
Layer[] layerPath = LayerUtils.getLayerPath(layerTreeModel.getRootLayer(), layer);
if (layerPath.length > 0) {
if (layer.isVisible()) {
checkBoxTreeSelectionModel.addSelectionPath(new TreePath(layerPath));
} else {
checkBoxTreeSelectionModel.removeSelectionPath(new TreePath(layerPath));
}
final List<Layer> children = layer.getChildren();
if (!children.isEmpty()) {
for (Layer child : children) {
updateLayerTreeVisibility(child);
}
}
}
}
private void updateLayerTreeSelection(Layer selectedLayer) {
if (selectedLayer != null) {
Layer[] layerPath = LayerUtils.getLayerPath(layerTreeModel.getRootLayer(), selectedLayer);
if (layerPath.length > 0) {
layerTree.setSelectionPath(new TreePath(layerPath));
} else {
layerTree.clearSelection();
}
} else {
layerTree.clearSelection();
}
}
private void updateLayerStyleUI(Layer layer) {
transparencyLabel.setEnabled(layer != null);
transparencySlider.setEnabled(layer != null);
if (layer != null) {
final double transparency = layer.getTransparency();
final int n = (int) Math.round(255.0 * transparency);
transparencySlider.setValue(n);
}
swipeLabel.setEnabled(layer != null);
swipeSlider.setEnabled(layer != null);
if (layer != null) {
final double swipe = layer.getSwipePercent();
final int n = (int) Math.round(100.0 * swipe);
swipeSlider.setValue(n);
}
}
private CheckBoxTree createCheckBoxTree(LayerTreeModel treeModel) {
final CheckBoxTree checkBoxTree = new CheckBoxTree(treeModel) {
@Override
public boolean isPathEditable(TreePath path) {
Layer layer = getLayer(path);
if (layer != null) {
return isLayerNameEditable(layer);
}
return false;
}
};
checkBoxTree.setRootVisible(false);
checkBoxTree.setShowsRootHandles(true);
checkBoxTree.setDigIn(false);
checkBoxTree.setEditable(true);
checkBoxTree.setDragEnabled(true);
checkBoxTree.setDropMode(DropMode.ON_OR_INSERT);
checkBoxTree.setTransferHandler(new LayerTreeTransferHandler(view, checkBoxTree));
checkBoxTree.getSelectionModel().addTreeSelectionListener(new LayerSelectionListener());
final CheckBoxTreeSelectionModel checkBoxSelectionModel = checkBoxTree.getCheckBoxTreeSelectionModel();
checkBoxSelectionModel.addTreeSelectionListener(new CheckBoxTreeSelectionListener());
final DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) checkBoxTree.getActualCellRenderer();
renderer.setLeafIcon(null);
renderer.setClosedIcon(null);
renderer.setOpenIcon(null);
return checkBoxTree;
}
private void installTransparencyChangeListener(Layer selectedLayer) {
selectedLayer.addListener(transparencyChangeListener);
}
private void removeTransparencyChangeListener(Layer selectedLayer) {
selectedLayer.removeListener(transparencyChangeListener);
}
private void installSwipeChangeListener(Layer selectedLayer) {
selectedLayer.addListener(swipeChangeListener);
}
private void removeSwipeChangeListener(Layer selectedLayer) {
selectedLayer.removeListener(swipeChangeListener);
}
public static AbstractButton createToolButton(final String iconPath) {
return ToolButtonFactory.createButton(UIUtils.loadImageIcon(iconPath), false);
}
private class RootLayerListener extends AbstractLayerListener {
@Override
public void handleLayerPropertyChanged(Layer layer, PropertyChangeEvent event) {
if ("visible".equals(event.getPropertyName())) {
updateLayerTreeVisibility(layer);
}
}
@Override
public void handleLayersAdded(Layer parentLayer, Layer[] childLayers) {
for (Layer layer : childLayers) {
updateLayerTreeVisibility(layer);
updateLayerTreeSelection(layer);
}
}
}
private class TransparencySliderListener implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
TreePath path = layerTree.getSelectionPath();
if (path != null) {
Layer layer = getLayer(path);
adjusting = true;
layer.setTransparency(transparencySlider.getValue() / 255.0);
adjusting = false;
}
}
}
private class SwipeSliderListener implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
TreePath path = layerTree.getSelectionPath();
if (path != null) {
Layer layer = getLayer(path);
adjusting = true;
layer.setSwipePercent(swipeSlider.getValue() / 100.0);
adjusting = false;
}
}
}
private class AddLayerActionListener implements ActionListener {
private Rectangle screenBounds;
@Override
public void actionPerformed(ActionEvent e) {
LayerSourceAssistantPane pane = new LayerSourceAssistantPane(SwingUtilities.getWindowAncestor(control),
"Add Layer");
final Map<String, LayerSourceDescriptor> layerSourceDescriptors1 =
LayerManager.getDefault().getLayerSourceDescriptors();
final LayerSourceDescriptor[] layerSourceDescriptors2 =
layerSourceDescriptors1.values().toArray(new LayerSourceDescriptor[layerSourceDescriptors1.size()]);
pane.show(new SelectLayerSourceAssistantPage(layerSourceDescriptors2), screenBounds);
screenBounds = pane.getWindow().getBounds();
}
}
private static class MyTreeCellRenderer extends DefaultTreeCellRenderer {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
boolean leaf,
int row, boolean hasFocus) {
JLabel label = (JLabel) super.getTreeCellRendererComponent(tree,
value, sel,
expanded, leaf, row,
hasFocus);
Layer layer = (Layer) value;
if (ProductSceneView.BASE_IMAGE_LAYER_ID.equals(layer.getId())) {
label.setText(String.format("<html><b>%s</b></html>", layer.getName()));
}
return label;
}
}
private class TransparencyChangeListener extends AbstractLayerListener {
@Override
public void handleLayerPropertyChanged(Layer layer, PropertyChangeEvent event) {
if("transparency".equals(event.getPropertyName())) {
updateLayerStyleUI(layer);
}
}
}
private class SwipeChangeListener extends AbstractLayerListener {
@Override
public void handleLayerPropertyChanged(Layer layer, PropertyChangeEvent event) {
if("swipePercent".equals(event.getPropertyName())) {
updateLayerStyleUI(layer);
}
}
}
private class LayerSelectionListener implements TreeSelectionListener {
private Layer selectedLayer;
@Override
public void valueChanged(TreeSelectionEvent event) {
if (selectedLayer != null) {
removeTransparencyChangeListener(selectedLayer);
removeSwipeChangeListener(selectedLayer);
}
selectedLayer = getLayer(event.getNewLeadSelectionPath());
if (selectedLayer != null) {
installTransparencyChangeListener(selectedLayer);
installSwipeChangeListener(selectedLayer);
}
if(parentComponent.getSelectedProductSceneView() != null) {
parentComponent.getSelectedProductSceneView().setSelectedLayer(selectedLayer);
}
}
}
private class CheckBoxTreeSelectionListener implements TreeSelectionListener {
@Override
public void valueChanged(TreeSelectionEvent event) {
if (!adjusting) {
TreePath path = event.getPath();
Layer layer = getLayer(path);
if (layer.getParent() != null) {
boolean pathSelected = ((TreeSelectionModel) event.getSource()).isPathSelected(path);
layer.setVisible(pathSelected);
}
}
}
}
}
| 21,242 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerDownAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/MoveLayerDownAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.UIUtils;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
/**
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
class MoveLayerDownAction extends AbstractAction {
MoveLayerDownAction() {
super("Move Layer Down", UIUtils.loadImageIcon("icons/Down24.gif"));
putValue(Action.ACTION_COMMAND_KEY, getClass().getName());
}
@Override
public void actionPerformed(ActionEvent e) {
Layer selectedLayer = SnapApp.getDefault().getSelectedProductSceneView().getSelectedLayer();
Layer rootLayer = SnapApp.getDefault().getSelectedProductSceneView().getRootLayer();
if (selectedLayer != null && rootLayer != selectedLayer) {
moveDown(selectedLayer);
}
}
void moveDown(Layer layer) {
if (canMove(layer)) {
final Layer parentLayer = layer.getParent();
final int layerIndex = parentLayer.getChildIndex(layer.getId());
parentLayer.getChildren().remove(layer);
parentLayer.getChildren().add(layerIndex + 1, layer);
}
}
public boolean canMove(Layer layer) {
final Layer parentLayer = layer.getParent();
final int layerIndex = parentLayer.getChildIndex(layer.getId());
final int lastIndex = parentLayer.getChildren().size() - 1;
return layerIndex != lastIndex;
}
}
| 2,275 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerTreeModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/LayerTreeModel.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.support.AbstractLayerListener;
import com.bc.ceres.glayer.support.LayerUtils;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.util.WeakHashMap;
class LayerTreeModel implements TreeModel {
private final Layer rootLayer;
private final WeakHashMap<TreeModelListener, Object> treeModelListeners;
LayerTreeModel(final Layer rootLayer) {
this.rootLayer = rootLayer;
this.rootLayer.addListener(new LayerListener());
treeModelListeners = new WeakHashMap<>();
}
///////////////////////////////////////////////////////////////////////////
// TreeModel interface
@Override
public Object getRoot() {
return rootLayer;
}
@Override
public Object getChild(Object parent, int index) {
return ((Layer) parent).getChildren().get(index);
}
@Override
public int getChildCount(Object parent) {
return ((Layer) parent).getChildren().size();
}
@Override
public boolean isLeaf(Object node) {
return ((Layer) node).getChildren().isEmpty();
}
@Override
public void valueForPathChanged(TreePath path, Object newValue) {
if (newValue instanceof String) {
Layer layer = (Layer) path.getLastPathComponent();
String oldName = layer.getName();
String newName = (String) newValue;
if (!oldName.equals(newName)) {
layer.setName(newName);
fireTreeNodeChanged(layer);
}
}
}
@Override
public int getIndexOfChild(Object parent, Object child) {
return ((Layer) parent).getChildren().indexOf(child);
}
@Override
public void addTreeModelListener(TreeModelListener l) {
treeModelListeners.put(l, "");
}
@Override
public void removeTreeModelListener(TreeModelListener l) {
treeModelListeners.remove(l);
}
// TreeModel interface
///////////////////////////////////////////////////////////////////////////
public Layer getRootLayer() {
return rootLayer;
}
protected void fireTreeNodeChanged(Layer layer) {
TreeModelEvent event = createTreeModelEvent(layer);
if (event == null) {
return;
}
for (TreeModelListener treeModelListener : treeModelListeners.keySet()) {
treeModelListener.treeNodesChanged(event);
}
}
protected void fireTreeStructureChanged(Layer parentLayer) {
TreeModelEvent event = createTreeModelEvent(parentLayer);
if (event == null) {
return;
}
for (TreeModelListener treeModelListener : treeModelListeners.keySet()) {
treeModelListener.treeStructureChanged(event);
}
}
protected void fireTreeNodesInserted(Layer parentLayer) {
TreeModelEvent event = createTreeModelEvent(parentLayer);
if (event == null) {
return;
}
for (TreeModelListener treeModelListener : treeModelListeners.keySet()) {
treeModelListener.treeNodesInserted(event);
}
}
protected void fireTreeNodesRemoved(Layer parentLayer) {
TreeModelEvent event = createTreeModelEvent(parentLayer);
if (event == null) {
return;
}
for (TreeModelListener treeModelListener : treeModelListeners.keySet()) {
treeModelListener.treeNodesRemoved(event);
}
}
private TreeModelEvent createTreeModelEvent(Layer layer) {
Layer[] parentPath = LayerUtils.getLayerPath(rootLayer, layer);
if (parentPath.length > 0) {
return new TreeModelEvent(this, parentPath);
} else {
return null;
}
}
private class LayerListener extends AbstractLayerListener {
@Override
public void handleLayerPropertyChanged(Layer layer, PropertyChangeEvent event) {
SwingUtilities.invokeLater(() -> fireTreeNodeChanged(layer));
}
@Override
public void handleLayerDataChanged(Layer layer, Rectangle2D modelRegion) {
SwingUtilities.invokeLater(() -> fireTreeNodeChanged(layer));
}
@Override
public void handleLayersAdded(Layer parentLayer, Layer[] childLayers) {
SwingUtilities.invokeLater(() -> fireTreeStructureChanged(parentLayer));
}
@Override
public void handleLayersRemoved(Layer parentLayer, Layer[] childLayers) {
SwingUtilities.invokeLater(() -> fireTreeStructureChanged(parentLayer));
}
}
} | 5,595 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerUpAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/MoveLayerUpAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.UIUtils;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
/**
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
class MoveLayerUpAction extends AbstractAction {
MoveLayerUpAction() {
super("Move Layer Up", UIUtils.loadImageIcon("icons/Up24.gif"));
putValue(Action.ACTION_COMMAND_KEY, getClass().getName());
}
@Override
public void actionPerformed(ActionEvent e) {
final Layer selectedLayer = SnapApp.getDefault().getSelectedProductSceneView().getSelectedLayer();
Layer rootLayer = SnapApp.getDefault().getSelectedProductSceneView().getRootLayer();
if (selectedLayer != null && rootLayer != selectedLayer) {
moveUp(selectedLayer);
}
}
void moveUp(Layer layer) {
if (canMove(layer)) {
final Layer parentLayer = layer.getParent();
final int layerIndex = layer.getParent().getChildIndex(layer.getId());
parentLayer.getChildren().remove(layer);
parentLayer.getChildren().add(layerIndex - 1, layer);
}
}
public boolean canMove(Layer layer) {
final Layer parentLayer = layer.getParent();
if (parentLayer == null) {
return false;
}
final int layerIndex = parentLayer.getChildIndex(layer.getId());
return layerIndex > 0;
}
}
| 2,267 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RemoveLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/RemoveLayerAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.UIUtils;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
/**
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
class RemoveLayerAction extends AbstractAction {
RemoveLayerAction() {
super("Remove Layer", UIUtils.loadImageIcon("icons/Minus24.gif"));
putValue(Action.ACTION_COMMAND_KEY, RemoveLayerAction.class.getName());
}
@Override
public void actionPerformed(ActionEvent e) {
Layer selectedLayer = SnapApp.getDefault().getSelectedProductSceneView().getSelectedLayer();
if (selectedLayer != null) {
selectedLayer.getParent().getChildren().remove(selectedLayer);
selectedLayer.dispose();
}
}
}
| 1,616 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerRightAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/MoveLayerRightAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.UIUtils;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
/**
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
class MoveLayerRightAction extends AbstractAction {
MoveLayerRightAction() {
super("Move Layer Right", UIUtils.loadImageIcon("icons/Right24.gif"));
putValue(Action.ACTION_COMMAND_KEY, getClass().getName());
}
@Override
public void actionPerformed(ActionEvent e) {
final Layer selectedLayer = SnapApp.getDefault().getSelectedProductSceneView().getSelectedLayer();
Layer rootLayer = SnapApp.getDefault().getSelectedProductSceneView().getRootLayer();
if (selectedLayer != null && rootLayer != selectedLayer) {
moveRight(selectedLayer);
}
}
void moveRight(Layer layer) {
if (canMove(layer)) {
final Layer parentLayer = layer.getParent();
final int layerIndex = parentLayer.getChildIndex(layer.getId());
final Layer targetLayer = parentLayer.getChildren().get(layerIndex - 1);
parentLayer.getChildren().remove(layer);
targetLayer.getChildren().add(layer);
}
}
public boolean canMove(Layer layer) {
final Layer parentLayer = layer.getParent();
final int layerIndex = parentLayer.getChildIndex(layer.getId());
if (layerIndex > 0) {
final Layer targetLayer = parentLayer.getChildren().get(layerIndex - 1);
if (targetLayer.isCollectionLayer()) {
return true;
}
}
return false;
}
}
| 2,487 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractLayerTopComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/AbstractLayerTopComponent.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.rcp.windows.ToolTopComponent;
import org.esa.snap.ui.product.ProductSceneView;
import org.netbeans.api.annotations.common.NonNull;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Layer manager tool view.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*/
public abstract class AbstractLayerTopComponent extends ToolTopComponent {
private ProductSceneView selectedView;
private Layer selectedLayer;
private final SelectedLayerPCL selectedLayerPCL;
protected AbstractLayerTopComponent() {
selectedLayerPCL = new SelectedLayerPCL();
initUI();
}
protected ProductSceneView getSelectedView() {
return selectedView;
}
protected Layer getSelectedLayer() {
return selectedLayer;
}
protected abstract String getTitle();
protected abstract String getHelpId();
protected void initUI() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(4, 4, 4, 4));
setDisplayName(getTitle());
setSelectedView(getSelectedProductSceneView());
}
/**
* A view opened.
*
* @param view The view.
*/
protected void viewOpened(ProductSceneView view) {
}
/**
* A view closed.
*
* @param view The view.
*/
protected void viewClosed(ProductSceneView view) {
}
/**
* The selected view changed.
*
* @param oldView The old selected view. May be null.
* @param newView The new selected view. May be null.
*/
protected void viewSelectionChanged(ProductSceneView oldView, ProductSceneView newView) {
}
/**
* The selected layer changed.
*
* @param oldLayer The old selected layer. May be null.
* @param newLayer The new selected layer. May be null.
*/
protected void layerSelectionChanged(Layer oldLayer, Layer newLayer) {
}
private void setSelectedView(final ProductSceneView newView) {
ProductSceneView oldView = selectedView;
if (newView != oldView) {
if (oldView != null) {
oldView.removePropertyChangeListener("selectedLayer", selectedLayerPCL);
}
if (newView != null) {
newView.addPropertyChangeListener("selectedLayer", selectedLayerPCL);
}
selectedView = newView;
viewSelectionChanged(oldView, newView);
setSelectedLayer(newView != null ? newView.getSelectedLayer() : null);
}
}
protected void setSelectedLayer(final Layer newLayer) {
Layer oldLayer = selectedLayer;
if (newLayer != oldLayer) {
selectedLayer = newLayer;
layerSelectionChanged(oldLayer, newLayer);
}
}
@Override
protected void productSceneViewSelected(@NonNull ProductSceneView view) {
setSelectedView(view);
viewOpened(view);
}
@Override
protected void productSceneViewDeselected(@NonNull ProductSceneView view) {
setSelectedView(null);
}
private class SelectedLayerPCL implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (getSelectedView() != null) {
setSelectedLayer(getSelectedView().getSelectedLayer());
}
}
}
}
| 4,300 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MoveLayerLeftAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/MoveLayerLeftAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.UIUtils;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
/**
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
class MoveLayerLeftAction extends AbstractAction {
MoveLayerLeftAction() {
super("Move Layer Left", UIUtils.loadImageIcon("icons/Left24.gif"));
putValue(Action.ACTION_COMMAND_KEY, getClass().getName());
}
@Override
public void actionPerformed(ActionEvent e) {
final Layer selectedLayer = SnapApp.getDefault().getSelectedProductSceneView().getSelectedLayer();
Layer rootLayer = SnapApp.getDefault().getSelectedProductSceneView().getRootLayer();
if (selectedLayer != null && rootLayer != selectedLayer) {
moveLeft(selectedLayer);
}
}
void moveLeft(Layer layer) {
if (canMove(layer)) {
Layer parentLayer = layer.getParent();
final Layer parentsParentLayer = parentLayer.getParent();
parentLayer.getChildren().remove(layer);
final int parentIndex = parentsParentLayer.getChildIndex(parentLayer.getId());
if (parentIndex < parentsParentLayer.getChildren().size() - 1) {
parentsParentLayer.getChildren().add(parentIndex + 1, layer);
} else {
parentsParentLayer.getChildren().add(layer);
}
}
}
public boolean canMove(Layer layer) {
Layer parentLayer = layer.getParent();
final Layer parentsParentLayer = parentLayer.getParent();
return parentsParentLayer != null;
}
}
| 2,464 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerManager.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/LayerManager.java | package org.esa.snap.rcp.layermanager;
import com.bc.ceres.core.Assert;
import com.bc.ceres.core.ExtensionFactory;
import com.bc.ceres.core.ExtensionManager;
import com.bc.ceres.core.SingleTypeExtensionFactory;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerType;
import org.esa.snap.ui.layer.DefaultLayerSourceDescriptor;
import org.esa.snap.ui.layer.LayerEditor;
import org.esa.snap.ui.layer.LayerSource;
import org.esa.snap.ui.layer.LayerSourceDescriptor;
import org.openide.filesystems.FileObject;
import org.openide.filesystems.FileUtil;
import org.openide.modules.ModuleInfo;
import org.openide.modules.OnStart;
import org.openide.util.Lookup;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Either 'editor' or 'editorFactory' must be given:
* <ul>
* <li>'editor' must be a <code>LayerEditor</code></li>
* <li>'editorFactory' must be a <code>com.bc.ceres.core.ExtensionFactory</code> that produces
* instances of <code>LayerEditor</code>.</li>
* </ul>
* <pre>
* <editor field="layerEditorClass" type="java.lang.Class"/>
* <editorFactory field="layerEditorFactoryClass" type="java.lang.Class"/>
* </pre>
* At least 'layer' or 'layerType' must be given:
* <ul>
* <li>'layer' must be a <code>com.bc.ceres.glayer.Layer</code></li>
* <li>'layerType' must be a <code>com.bc.ceres.glayer.LayerType</code>.</li>
* </ul>
* <pre>
* <layer field="layerClass" type="java.lang.Class"/>
* <layerType field="layerTypeClass" type="java.lang.Class"/>
* </pre>
*
* @author Norman Fomferra
*/
public class LayerManager {
public static final Logger LOG = Logger.getLogger(LayerManager.class.getName());
private static LayerManager layerManager;
private final Map<String, LayerSourceDescriptor> layerSourceDescriptors;
public static LayerManager getDefault() {
if (layerManager == null) {
layerManager = new LayerManager();
}
return layerManager;
}
public Map<String, LayerSourceDescriptor> getLayerSourceDescriptors() {
return Collections.unmodifiableMap(layerSourceDescriptors);
}
protected LayerManager() {
registerLayerEditors();
this.layerSourceDescriptors = lookupLayerSourceDescriptors();
}
private static Map<String, LayerSourceDescriptor> lookupLayerSourceDescriptors() {
Map<String, LayerSourceDescriptor> layerSourceDescriptors = new LinkedHashMap<>();
FileObject[] files = FileUtil.getConfigFile("LayerSources").getChildren();
//System.out.println("Files in SNAP/LayerSources: " + Arrays.toString(files));
List<FileObject> orderedFiles = FileUtil.getOrder(Arrays.asList(files), true);
for (FileObject file : orderedFiles) {
LayerSourceDescriptor layerSourceDescriptor = null;
try {
layerSourceDescriptor = createLayerSourceDescriptor(file);
} catch (Exception e) {
LOG.log(Level.SEVERE, String.format("Failed to create layer source from layer.xml path '%s'", file.getPath()), e);
}
if (layerSourceDescriptor != null) {
layerSourceDescriptors.put(layerSourceDescriptor.getId(), layerSourceDescriptor);
LOG.info(String.format("New layer source added from layer.xml path '%s': %s",
file.getPath(), layerSourceDescriptor.getName()));
}
}
return layerSourceDescriptors;
}
public static DefaultLayerSourceDescriptor createLayerSourceDescriptor(FileObject fileObject) {
String id = fileObject.getName();
String name = (String) fileObject.getAttribute("displayName");
String description = (String) fileObject.getAttribute("description");
Class<? extends LayerSource> layerSourceClass = getClassAttribute(fileObject, "layerSourceClass", LayerSource.class, false);
String layerTypeClassName = (String) fileObject.getAttribute("layerTypeClass");
Assert.argument(name != null && !name.isEmpty(), "Missing attribute 'displayName'");
Assert.argument(layerSourceClass != null || layerTypeClassName != null, "Either attribute 'class' or 'layerType' must be provided");
if (layerSourceClass != null) {
return new DefaultLayerSourceDescriptor(id, name, description, layerSourceClass);
} else {
return new DefaultLayerSourceDescriptor(id, name, description, layerTypeClassName);
}
}
private static void registerLayerEditors() {
FileObject[] files = FileUtil.getConfigFile("LayerEditors").getChildren();
//System.out.println("Files in SNAP/LayerEditors: " + Arrays.toString(files));
List<FileObject> orderedFiles = FileUtil.getOrder(Arrays.asList(files), true);
for (FileObject file : orderedFiles) {
try {
registerLayerEditorDescriptor(file);
LOG.info(String.format("New layer editor registered from layer.xml path '%s'", file.getPath()));
} catch (Exception e) {
LOG.log(Level.SEVERE, String.format("Failed to register layer editor from layer.xml path '%s'", file.getPath()), e);
}
}
}
public static void registerLayerEditorDescriptor(FileObject fileObject) throws Exception {
Class<? extends LayerEditor> editorClass = getClassAttribute(fileObject, "editorClass", LayerEditor.class, false);
Class<? extends ExtensionFactory> editorFactoryClass = getClassAttribute(fileObject, "editorFactoryClass", ExtensionFactory.class, false);
Assert.argument(editorClass != null || editorFactoryClass != null,
"Either 'editorClass' or 'editorFactoryClass' attributes must be given");
Class<? extends Layer> layerClass = getClassAttribute(fileObject, "layerClass", Layer.class, false);
Class<? extends LayerType> layerTypeClass = getClassAttribute(fileObject, "layerTypeClass", LayerType.class, false);
Assert.argument(layerClass != null || layerTypeClass != null,
"Either 'layerClass' or 'layerTypeClass' attributes must be given");
if (layerClass != null) {
ExtensionManager.getInstance().register(layerClass, createExtensionFactory(editorClass, editorFactoryClass));
} else {
ExtensionManager.getInstance().register(layerTypeClass, createExtensionFactory(editorClass, editorFactoryClass));
}
}
public static <T> Class<T> getClassAttribute(FileObject fileObject,
String attributeName,
Class<T> expectedType,
boolean required) {
String className = (String) fileObject.getAttribute(attributeName);
if (className == null || className.isEmpty()) {
if (required) {
throw new IllegalArgumentException(String.format("Missing attribute '%s' of type %s",
attributeName, expectedType.getName()));
}
return null;
}
Collection<? extends ModuleInfo> modules = Lookup.getDefault().lookupAll(ModuleInfo.class);
for (ModuleInfo module : modules) {
if (module.isEnabled()) {
try {
Class<?> implClass = module.getClassLoader().loadClass(className);
if (expectedType.isAssignableFrom(implClass)) {
//noinspection unchecked
return (Class<T>) implClass;
} else {
throw new IllegalArgumentException(String.format("Value %s of attribute '%s' must be a %s",
implClass.getName(),
attributeName,
expectedType.getName()));
}
} catch (ClassNotFoundException e) {
// it's ok, continue
}
}
}
return null;
}
/**
* Creates an extension factory that maps an instances of a {@link com.bc.ceres.glayer.Layer} or
* a {@link com.bc.ceres.glayer.LayerType} to an instance of a {@link LayerEditor}.
*/
private static ExtensionFactory createExtensionFactory(Class<? extends LayerEditor> editorClass, Class<? extends ExtensionFactory> editorFactoryClass) throws Exception {
if (editorClass != null) {
return new SingleTypeExtensionFactory<LayerType, LayerEditor>(LayerEditor.class, editorClass);
}
if (editorFactoryClass != null) {
try {
return editorFactoryClass.newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
// should never get here
throw new IllegalStateException();
}
@SuppressWarnings("UnusedDeclaration")
@OnStart
public static class Runner implements Runnable {
@Override
public void run() {
// test!
LayerManager.getDefault();
}
}
}
| 9,506 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerEditorTopComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/LayerEditorTopComponent.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.support.AbstractLayerListener;
import org.esa.snap.ui.layer.LayerEditor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import java.awt.BorderLayout;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
@TopComponent.Description(
preferredID = "LayerEditorTopComponent",
iconBase = "org/esa/snap/rcp/icons/LayerEditor.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(
mode = "navigator",
openAtStartup = false,
position = 1
)
@ActionID(category = "Window", id = "org.esa.snap.rcp.layermanager.LayerEditorTopComponent")
@ActionReferences({
@ActionReference(path = "Menu/View/Tool Windows", position = 11),
@ActionReference(path = "Menu/Layer", position = 410)
})
@TopComponent.OpenActionRegistration(
displayName = "#CTL_LayerEditorTopComponent_Name",
preferredID = "LayerEditorTopComponent"
)
@NbBundle.Messages({
"CTL_LayerEditorTopComponent_Name=Layer Editor",
"CTL_LayerEditorTopComponent_HelpId=showLayerEditorWnd"
})
/**
* Layer manager tool view.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*
* @author Norman Fomferra
*/
public class LayerEditorTopComponent extends AbstractLayerTopComponent {
private LayerEditor activeEditor;
private LayerHandler layerHandler;
@Override
protected String getTitle() {
return Bundle.CTL_LayerEditorTopComponent_Name();
}
@Override
protected String getHelpId() {
return Bundle.CTL_LayerEditorTopComponent_HelpId();
}
protected void initUI() {
layerHandler = new LayerHandler();
super.initUI();
// add(activeEditor.createControl(newLayer), BorderLayout.CENTER);
}
@Override
protected void layerSelectionChanged(Layer oldLayer, Layer newLayer) {
if (oldLayer != null) {
oldLayer.removeListener(layerHandler);
}
if (getComponentCount() > 0) {
remove(0);
}
LayerEditor oldEditor = activeEditor;
if (newLayer != null) {
activeEditor = getLayerEditor(newLayer);
setDisplayName("Layer Editor - " + newLayer.getName());
} else {
activeEditor = LayerEditor.EMPTY;
setDisplayName("Layer Editor");
}
if (oldEditor != null) {
oldEditor.handleEditorDetached();
}
add(activeEditor.createControl(newLayer), BorderLayout.CENTER);
activeEditor.handleEditorAttached();
activeEditor.handleLayerContentChanged();
validate();
repaint();
if (newLayer != null) {
newLayer.addListener(layerHandler);
}
}
private LayerEditor getLayerEditor(Layer layer) {
LayerEditor layerEditor = layer.getExtension(LayerEditor.class);
if (layerEditor != null) {
return layerEditor;
}
layerEditor = layer.getLayerType().getExtension(LayerEditor.class);
if (layerEditor != null) {
return layerEditor;
}
return LayerEditor.EMPTY;
}
private class LayerHandler extends AbstractLayerListener {
@Override
public void handleLayerPropertyChanged(Layer layer, PropertyChangeEvent event) {
activeEditor.handleLayerContentChanged();
}
@Override
public void handleLayerDataChanged(Layer layer, Rectangle2D modelRegion) {
activeEditor.handleLayerContentChanged();
}
@Override
public void handleLayersAdded(Layer parentLayer, Layer[] childLayers) {
activeEditor.handleLayerContentChanged();
}
@Override
public void handleLayersRemoved(Layer parentLayer, Layer[] childLayers) {
activeEditor.handleLayerContentChanged();
}
}
} | 4,889 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractLayerForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/AbstractLayerForm.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import javax.swing.JComponent;
/**
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*/
interface AbstractLayerForm {
JComponent getFormControl();
void updateFormControl();
}
| 1,011 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ZoomToLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/ZoomToLayerAction.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.grender.Viewport;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneView;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
/**
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
class ZoomToLayerAction extends AbstractAction {
ZoomToLayerAction() {
super("Zoom to Layer", UIUtils.loadImageIcon("icons/ZoomTo24.gif"));
putValue(Action.ACTION_COMMAND_KEY, getClass().getName());
}
@Override
public void actionPerformed(ActionEvent e) {
final ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView();
final Layer selectedLayer = sceneView.getSelectedLayer();
Rectangle2D modelBounds = selectedLayer.getModelBounds();
if (modelBounds != null) {
final Viewport viewport = sceneView.getLayerCanvas().getViewport();
final AffineTransform m2vTransform = viewport.getModelToViewTransform();
final AffineTransform v2mTransform = viewport.getViewToModelTransform();
final Rectangle2D viewBounds = m2vTransform.createTransformedShape(modelBounds).getBounds2D();
viewBounds.setFrameFromDiagonal(viewBounds.getMinX() - 10, viewBounds.getMinY() - 10,
viewBounds.getMaxX() + 10, viewBounds.getMaxY() + 10);
final Shape transformedModelBounds = v2mTransform.createTransformedShape(viewBounds);
sceneView.zoom(transformedModelBounds.getBounds2D());
}
}
}
| 2,517 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerManagerTopComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/LayerManagerTopComponent.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.swing.selection.AbstractSelectionContext;
import com.bc.ceres.swing.selection.Selection;
import com.bc.ceres.swing.selection.support.DefaultSelection;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import java.awt.BorderLayout;
import java.util.WeakHashMap;
@TopComponent.Description(
preferredID = "LayerManagerTopComponent",
iconBase = "org/esa/snap/rcp/icons/LayerManager.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define
)
@TopComponent.Registration(
mode = "rightSlidingSide",
openAtStartup = true,
position = 10
)
@ActionID(category = "Window", id = "org.esa.snap.rcp.layermanager.LayerManagerTopComponent")
@ActionReferences({
@ActionReference(path = "Menu/Layer", position = 400, separatorBefore = 399),
@ActionReference(path = "Menu/View/Tool Windows", position = 10),
@ActionReference(path = "Toolbars/Tool Windows")
})
@TopComponent.OpenActionRegistration(
displayName = "#CTL_LayerManagerTopComponent_Name",
preferredID = "LayerManagerTopComponent"
)
@NbBundle.Messages({
"CTL_LayerManagerTopComponent_Name=Layer Manager",
"CTL_LayerManagerTopComponent_HelpId=showLayerManagerWnd"
})
/**
* Layer manager tool view.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*
* @author Norman Fomferra
*/
public class LayerManagerTopComponent extends AbstractLayerTopComponent {
private WeakHashMap<ProductSceneView, LayerManagerForm> layerManagerMap;
private LayerManagerForm activeForm;
private LayerSelectionContext selectionContext;
@Override
protected void initUI() {
layerManagerMap = new WeakHashMap<>();
selectionContext = new LayerSelectionContext();
super.initUI();
}
@Override
protected void viewClosed(ProductSceneView view) {
layerManagerMap.remove(view);
}
@Override
protected void viewSelectionChanged(ProductSceneView oldView, ProductSceneView newView) {
realizeActiveForm();
}
@Override
protected void layerSelectionChanged(Layer oldLayer, Layer selectedLayer) {
if (activeForm != null) {
activeForm.updateFormControl();
selectionContext.fireSelectionChange(new DefaultSelection<>(selectedLayer));
}
}
@Override
protected String getTitle() {
return Bundle.CTL_LayerManagerTopComponent_Name();
}
@Override
protected String getHelpId() {
return Bundle.CTL_LayerManagerTopComponent_HelpId();
}
private void realizeActiveForm() {
if (getComponentCount() > 0) {
remove(0);
}
if (getSelectedView() != null) {
activeForm = getOrCreateActiveForm(getSelectedView());
add(activeForm.getFormControl(), BorderLayout.CENTER);
} else {
activeForm = null;
}
validate();
repaint();
}
protected LayerManagerForm getOrCreateActiveForm(ProductSceneView view) {
if (layerManagerMap.containsKey(view)) {
activeForm = layerManagerMap.get(view);
} else {
activeForm = new LayerManagerForm(this);
layerManagerMap.put(view, activeForm);
}
return activeForm;
}
private class LayerSelectionContext extends AbstractSelectionContext {
@Override
public void setSelection(Selection selection) {
Object selectedValue = selection.getSelectedValue();
if (selectedValue instanceof Layer) {
setSelectedLayer((Layer) selectedValue);
}
}
@Override
public Selection getSelection() {
Layer selectedLayer = getSelectedLayer();
if (selectedLayer != null) {
return new DefaultSelection<>(selectedLayer);
} else {
return DefaultSelection.EMPTY;
}
}
@Override
protected void fireSelectionChange(Selection selection) {
super.fireSelectionChange(selection);
}
}
}
| 5,150 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerTreeTransferHandler.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/LayerTreeTransferHandler.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager;
import com.bc.ceres.glayer.Layer;
import org.esa.snap.ui.product.ProductSceneView;
import javax.swing.JComponent;
import javax.swing.JTree;
import javax.swing.TransferHandler;
import javax.swing.tree.TreePath;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.util.List;
/**
* Class that enables the support for Drag & Drop.
* <p>
* Limitations:
* This handler only supports {@link JTree} with an {@link javax.swing.tree.TreeModel model}
* which is backed by {@link Layer layer}.
*
* @author Marco Peters
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
class LayerTreeTransferHandler extends TransferHandler {
private static final DataFlavor layerFlavor = new DataFlavor(LayerContainer.class, "LayerContainer");
private final ProductSceneView view;
private final JTree tree;
LayerTreeTransferHandler(ProductSceneView view, JTree tree) {
this.view = view;
this.tree = tree;
}
@Override
public boolean canImport(TransferSupport support) {
JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
TreePath treePath = dropLocation.getPath();
Layer targetLayer = (Layer) treePath.getLastPathComponent();
int targetIndex = dropLocation.getChildIndex();
boolean moveAllowed = true;
if (targetIndex == -1) { // -1 indicates move into other layer
moveAllowed = targetLayer.isCollectionLayer();
}
return support.isDataFlavorSupported(layerFlavor) &&
support.isDrop() &&
support.getComponent() == tree &&
moveAllowed;
}
@Override
public boolean importData(TransferSupport support) {
if (support.getComponent() != tree) {
return false;
}
final Transferable transferable = support.getTransferable();
final LayerContainer transferLayer;
try {
transferLayer = (LayerContainer) transferable.getTransferData(layerFlavor);
} catch (UnsupportedFlavorException ignore) {
return false;
} catch (IOException ignore) {
return false;
}
if (!isValidDrag(support, transferLayer)) {
return false;
}
// remove and add for Drag&Drop
// cannot use exportDone(Transferable); layer has to be removed first and then added,
// because the parent of the layer is set to null when removing
removeLayer(transferLayer);
addLayer(transferLayer, support);
return true;
}
@Override
public int getSourceActions(JComponent component) {
return component == tree ? MOVE : NONE;
}
@Override
protected Transferable createTransferable(JComponent component) {
if (component == tree) {
final Layer draggedLayer = view.getSelectedLayer();
final Layer oldParentLayer = draggedLayer.getParent();
final int oldChildIndex = oldParentLayer.getChildIndex(draggedLayer.getId());
return new LayerTransferable(draggedLayer, oldParentLayer, oldChildIndex);
}
return null;
}
private void addLayer(LayerContainer layerContainer, TransferSupport support) {
Layer transferLayer = layerContainer.getDraggedLayer();
JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
TreePath treePath = dropLocation.getPath();
Layer targetLayer = (Layer) treePath.getLastPathComponent();
List<Layer> targetList = targetLayer.getChildren();
int targetIndex = dropLocation.getChildIndex();
if (targetIndex == -1) { // moving into target layer
targetIndex = 0; // insert at the beginning
}
if (targetList.size() <= targetIndex) {
targetList.add(transferLayer);
} else {
targetList.add(targetIndex, transferLayer);
}
final TreePath newTreePath = treePath.pathByAddingChild(transferLayer);
tree.makeVisible(newTreePath);
tree.scrollPathToVisible(newTreePath);
}
private static void removeLayer(LayerContainer layerContainer) {
final Layer oldParentayer = layerContainer.getOldParentLayer();
final int oldIndex = layerContainer.getOldChildIndex();
oldParentayer.getChildren().remove(oldIndex);
}
private static boolean isValidDrag(TransferSupport support, LayerContainer layerContainer) {
JTree.DropLocation dropLocation = (JTree.DropLocation) support.getDropLocation();
TreePath treePath = dropLocation.getPath();
final Object[] path = treePath.getPath();
for (Object o : path) {
final Layer layer = (Layer) o;
if (layer == layerContainer.getDraggedLayer()) {
return false;
}
}
Layer targetLayer = (Layer) treePath.getLastPathComponent();
int targetIndex = dropLocation.getChildIndex();
if (targetIndex == -1) { // -1 indicates move into other layer
return targetLayer.isCollectionLayer();
}
return true;
}
private static class LayerTransferable implements Transferable {
private LayerContainer layerContainer;
private LayerTransferable(Layer draggedLayer, Layer oldParentLayer, int oldChildIndex) {
layerContainer = new LayerContainer(draggedLayer, oldParentLayer, oldChildIndex);
}
@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{layerFlavor};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return flavor.equals(layerFlavor);
}
@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
if (!flavor.equals(layerFlavor)) {
throw new UnsupportedFlavorException(flavor);
}
return layerContainer;
}
}
private static class LayerContainer {
private final Layer draggedLayer;
private final Layer oldParentLayer;
private final int oldChildIndex;
private LayerContainer(Layer draggedLayer, Layer oldParentLayer, int oldChildIndex) {
this.draggedLayer = draggedLayer;
this.oldParentLayer = oldParentLayer;
this.oldChildIndex = oldChildIndex;
}
public Layer getDraggedLayer() {
return draggedLayer;
}
public Layer getOldParentLayer() {
return oldParentLayer;
}
public int getOldChildIndex() {
return oldChildIndex;
}
}
}
| 7,614 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImageLayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/editors/ImageLayerEditor.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.editors;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.glayer.support.ImageLayer;
import org.esa.snap.ui.layer.AbstractLayerConfigurationEditor;
import java.awt.Color;
/**
* Basic editor for image layers.
*
* @author Ralf Quast
* @version $ Revision: $ $ Date: $
* @since BEAM 4.6
*/
public class ImageLayerEditor extends AbstractLayerConfigurationEditor {
@Override
protected void addEditablePropertyDescriptors() {
addDescriptor(ImageLayer.PROPERTY_NAME_BORDER_SHOWN, Boolean.class, ImageLayer.DEFAULT_BORDER_SHOWN, "Show image border");
addDescriptor(ImageLayer.PROPERTY_NAME_BORDER_COLOR, Color.class, ImageLayer.DEFAULT_BORDER_COLOR, "Image border colour");
addDescriptor(ImageLayer.PROPERTY_NAME_BORDER_WIDTH, Double.class, ImageLayer.DEFAULT_BORDER_WIDTH, "Image border size");
addDescriptor(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_SHOWN, Boolean.class, ImageLayer.DEFAULT_PIXEL_BORDER_SHOWN, "Show pixel borders");
addDescriptor(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_COLOR, Color.class, ImageLayer.DEFAULT_PIXEL_BORDER_COLOR, "Pixel border colour");
addDescriptor(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_WIDTH, Double.class, ImageLayer.DEFAULT_PIXEL_BORDER_WIDTH, "Pixel border size");
}
private void addDescriptor(String name, Class<?> type, Object defaultValue, String displayName) {
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, type);
propertyDescriptor.setDefaultValue(defaultValue);
propertyDescriptor.setDisplayName(displayName);
propertyDescriptor.setDefaultConverter();
addPropertyDescriptor(propertyDescriptor);
}
}
| 2,456 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataLayerEditorFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/editors/VectorDataLayerEditorFactory.java | package org.esa.snap.rcp.layermanager.editors;
import com.bc.ceres.core.ExtensionFactory;
import org.esa.snap.ui.layer.LayerEditor;
import org.esa.snap.ui.product.VectorDataLayer;
/**
* Experimental code: A factory that creates a specific {@link LayerEditor} for a given {@link VectorDataLayer}.
*
* @author Norman Fomferra
* @since BEAM 4.10
*/
public class VectorDataLayerEditorFactory implements ExtensionFactory {
@Override
public LayerEditor getExtension(Object object, Class<?> extensionType) {
if (object instanceof VectorDataLayer) {
// todo - special TrackPointEditor: work on this after 4.10 (nf)
/*
VectorDataLayer vectorDataLayer = (VectorDataLayer) object;
String featureTypeName = vectorDataLayer.getVectorDataNode().getFeatureType().getTypeName();
if (TrackLayerType.isTrackPointNode(vectorDataLayer.getVectorDataNode())) {
return new TrackLayerEditor();
} else {
return new VectorDataLayerEditor();
}
*/
return new VectorDataLayerEditor();
}
return null;
}
@Override
public Class<?>[] getExtensionTypes() {
return new Class<?>[]{LayerEditor.class};
}
}
| 1,274 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FeatureLayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/editors/FeatureLayerEditor.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.editors;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.rcp.layermanager.layersrc.shapefile.FeatureLayer;
import org.esa.snap.ui.layer.AbstractLayerEditor;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.Font;
import java.util.Hashtable;
/**
* Editor for placemark layers.
*
* @author Ralf Quast
* @author Marco Zühlke
* @author Marco Peters
* @version $Revision$ $Date$
* @since BEAM 4.6
*/
public class FeatureLayerEditor extends AbstractLayerEditor {
private JSlider polyFillTransparency;
private JSlider polyStrokeTransparency;
private JSlider textTransparency;
@Override
protected FeatureLayer getCurrentLayer() {
return (FeatureLayer) super.getCurrentLayer();
}
@Override
public JComponent createControl() {
Hashtable<Integer, JLabel> sliderLabelTable = new Hashtable<Integer, JLabel>();
sliderLabelTable.put(0, createSliderLabel("0%"));
sliderLabelTable.put(127, createSliderLabel("50%"));
sliderLabelTable.put(255, createSliderLabel("100%"));
TableLayout tableLayout = new TableLayout(2);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST);
tableLayout.setColumnWeightX(0, 0.4);
tableLayout.setColumnWeightX(1, 0.6);
tableLayout.setRowWeightY(3, 1.0);
tableLayout.setTablePadding(4, 4);
JPanel control = new JPanel(tableLayout);
JLabel fillLabel = new JLabel("Fill transparency:");
control.add(fillLabel);
polyFillTransparency = new JSlider(0, 255, 255);
polyFillTransparency.setToolTipText("Set the opacity of fillings");
polyFillTransparency.setLabelTable(sliderLabelTable);
polyFillTransparency.setPaintLabels(true);
polyFillTransparency.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
getCurrentLayer().setPolyFillOpacity(1.0 - polyFillTransparency.getValue() / 255.0);
}
});
control.add(polyFillTransparency);
JLabel lineLabel = new JLabel("Line transparency:");
control.add(lineLabel);
polyStrokeTransparency = new JSlider(0, 255, 255);
polyStrokeTransparency.setToolTipText("Set the transparency of lines");
polyStrokeTransparency.setLabelTable(sliderLabelTable);
polyStrokeTransparency.setPaintLabels(true);
polyStrokeTransparency.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
getCurrentLayer().setPolyStrokeOpacity(1.0 - polyStrokeTransparency.getValue() / 255.0);
}
});
control.add(polyStrokeTransparency);
JLabel labelLabel = new JLabel("Label transparency:");
control.add(labelLabel);
textTransparency = new JSlider(0, 255, 255);
textTransparency.setToolTipText("Set the transparency of labels");
textTransparency.setLabelTable(sliderLabelTable);
textTransparency.setPaintLabels(true);
textTransparency.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent e) {
getCurrentLayer().setTextOpacity(1.0 - textTransparency.getValue() / 255.0);
}
});
control.add(textTransparency);
control.add(new JPanel()); // filler
return control;
}
private JLabel createSliderLabel(String text) {
JLabel label = new JLabel(text);
Font oldFont = label.getFont();
Font newFont = oldFont.deriveFont(oldFont.getSize2D() * 0.85f);
label.setFont(newFont);
return label;
}
@Override
public void handleLayerContentChanged() {
polyFillTransparency.setValue((int) Math.round((1.0 - getCurrentLayer().getPolyFillOpacity()) * 255));
polyStrokeTransparency.setValue((int) Math.round((1.0 - getCurrentLayer().getPolyStrokeOpacity()) * 255));
textTransparency.setValue((int) Math.round((1.0 - getCurrentLayer().getTextOpacity()) * 255));
}
}
| 5,082 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataLayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/editors/VectorDataLayerEditor.java | /*
* Copyright (C) 2012 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.editors;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.FigureEditor;
import com.bc.ceres.swing.figure.FigureStyle;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import com.bc.ceres.swing.figure.support.NamedSymbol;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import org.esa.snap.core.datamodel.Placemark;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.ObjectUtils;
import org.esa.snap.ui.layer.AbstractLayerConfigurationEditor;
import org.esa.snap.ui.layer.LayerEditor;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.SimpleFeatureFigure;
import org.esa.snap.ui.product.VectorDataFigureEditor;
import org.esa.snap.ui.product.VectorDataLayer;
import org.openide.util.Utilities;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Customizable {@link LayerEditor} for {@link VectorDataNode}s.
*
* @author Marco Peters
* @author Norman Fomferra
*/
public class VectorDataLayerEditor extends AbstractLayerConfigurationEditor {
private static final String FILL_COLOR_NAME = DefaultFigureStyle.FILL_COLOR.getName();
private static final String FILL_OPACITY_NAME = DefaultFigureStyle.FILL_OPACITY.getName();
private static final String STROKE_COLOR_NAME = DefaultFigureStyle.STROKE_COLOR.getName();
private static final String STROKE_OPACITY_NAME = DefaultFigureStyle.STROKE_OPACITY.getName();
private static final String STROKE_WIDTH_NAME = DefaultFigureStyle.STROKE_WIDTH.getName();
private static final String SYMBOL_NAME_NAME = DefaultFigureStyle.SYMBOL_NAME.getName();
private static final SimpleFeatureFigure[] NO_SIMPLE_FEATURE_FIGURES = new SimpleFeatureFigure[0];
private static final ValueSet SYMBOL_VALUE_SET = new ValueSet(new String[]{
NamedSymbol.PLUS.getName(),
NamedSymbol.CROSS.getName(),
NamedSymbol.STAR.getName(),
NamedSymbol.SQUARE.getName(),
NamedSymbol.CIRCLE.getName(),
NamedSymbol.PIN.getName()
});
private final SelectionChangeHandler selectionChangeHandler;
private final StyleUpdater styleUpdater;
private final AtomicBoolean isAdjusting;
public VectorDataLayerEditor() {
selectionChangeHandler = new SelectionChangeHandler();
styleUpdater = new StyleUpdater();
isAdjusting = new AtomicBoolean(false);
}
@Override
protected void addEditablePropertyDescriptors() {
final Figure[] figures = getFigures(false);
final PropertyDescriptor fillColor = new PropertyDescriptor(DefaultFigureStyle.FILL_COLOR);
fillColor.setDefaultValue(getCommonStylePropertyValue(figures, FILL_COLOR_NAME));
addPropertyDescriptor(fillColor);
final PropertyDescriptor fillOpacity = new PropertyDescriptor(DefaultFigureStyle.FILL_OPACITY);
fillOpacity.setDefaultValue(getCommonStylePropertyValue(figures, FILL_OPACITY_NAME));
addPropertyDescriptor(fillOpacity);
final PropertyDescriptor strokeColor = new PropertyDescriptor(DefaultFigureStyle.STROKE_COLOR);
strokeColor.setDefaultValue(getCommonStylePropertyValue(figures, STROKE_COLOR_NAME));
addPropertyDescriptor(strokeColor);
final PropertyDescriptor strokeOpacity = new PropertyDescriptor(DefaultFigureStyle.STROKE_OPACITY);
strokeOpacity.setDefaultValue(getCommonStylePropertyValue(figures, STROKE_OPACITY_NAME));
addPropertyDescriptor(strokeOpacity);
final PropertyDescriptor strokeWidth = new PropertyDescriptor(DefaultFigureStyle.STROKE_WIDTH);
strokeWidth.setDefaultValue(getCommonStylePropertyValue(figures, STROKE_WIDTH_NAME));
addPropertyDescriptor(strokeWidth);
final PropertyDescriptor symbolName = new PropertyDescriptor(DefaultFigureStyle.SYMBOL_NAME);
symbolName.setDefaultValue(getCommonStylePropertyValue(figures, SYMBOL_NAME_NAME));
symbolName.setValueSet(SYMBOL_VALUE_SET);
symbolName.setNotNull(false);
addPropertyDescriptor(symbolName);
getBindingContext().bindEnabledState(SYMBOL_NAME_NAME, false, SYMBOL_NAME_NAME, null);
}
@Override
public void handleLayerContentChanged() {
if (isAdjusting.compareAndSet(false, true)) {
try {
updateProperties(getFigures(false), getBindingContext());
} finally {
isAdjusting.set(false);
}
}
}
@Override
public void handleEditorAttached() {
FigureEditor figureEditor = getFigureEditor();
if (figureEditor != null) {
figureEditor.addSelectionChangeListener(selectionChangeHandler);
}
getBindingContext().addPropertyChangeListener(styleUpdater);
}
@Override
public void handleEditorDetached() {
FigureEditor figureEditor = getFigureEditor();
if (figureEditor != null) {
figureEditor.removeSelectionChangeListener(selectionChangeHandler);
}
getBindingContext().removePropertyChangeListener(styleUpdater);
}
private VectorDataNode getVectorDataNode() {
final FigureEditor figureEditor = getFigureEditor();
if (figureEditor instanceof VectorDataFigureEditor) {
VectorDataFigureEditor editor = (VectorDataFigureEditor) figureEditor;
return editor.getVectorDataNode();
} else {
return null;
}
}
protected void updateProperties(SimpleFeatureFigure[] selectedFigures, BindingContext bindingContext) {
updateProperty(bindingContext, FILL_COLOR_NAME, getCommonStylePropertyValue(selectedFigures, FILL_COLOR_NAME));
updateProperty(bindingContext, FILL_OPACITY_NAME, getCommonStylePropertyValue(selectedFigures, FILL_OPACITY_NAME));
updateProperty(bindingContext, STROKE_COLOR_NAME, getCommonStylePropertyValue(selectedFigures, STROKE_COLOR_NAME));
updateProperty(bindingContext, STROKE_OPACITY_NAME, getCommonStylePropertyValue(selectedFigures, STROKE_OPACITY_NAME));
updateProperty(bindingContext, STROKE_WIDTH_NAME, getCommonStylePropertyValue(selectedFigures, STROKE_WIDTH_NAME));
final Object styleProperty = getCommonStylePropertyValue(selectedFigures, SYMBOL_NAME_NAME);
if (styleProperty != null) {
updateProperty(bindingContext, SYMBOL_NAME_NAME, styleProperty);
}
}
protected void updateProperty(BindingContext bindingContext, String propertyName, Object styleValue) {
PropertySet propertySet = bindingContext.getPropertySet();
if (propertySet.isPropertyDefined(propertyName)) {
final Object oldValue = propertySet.getValue(propertyName);
if (!ObjectUtils.equalObjects(oldValue, styleValue)) {
propertySet.setValue(propertyName, styleValue);
}
}
}
protected void updateStyle(BindingContext bindingContext, String propertyName, FigureStyle style) {
final Object value = bindingContext.getPropertySet().getValue(propertyName);
if (value != null) {
style.setValue(propertyName, value);
}
}
private void updateColorAndOpacity(String colorPropertyName, String opacityPropertyName) {
PropertySet propertySet = getBindingContext().getPropertySet();
Color color = propertySet.getValue(colorPropertyName);
boolean isTransparent = color != null && color.getAlpha() == 0;
if (isTransparent) {
propertySet.setValue(opacityPropertyName, 0.0);
} else {
Double transparency = propertySet.getValue(opacityPropertyName);
if (transparency != null && transparency == 0.0) {
propertySet.setValue(opacityPropertyName, 0.5);
}
}
getBindingContext().setComponentsEnabled(opacityPropertyName, !isTransparent);
}
private Object getCommonStylePropertyValue(Figure[] figures, String propertyName) {
Object commonValue = null;
for (Figure figure : figures) {
final Object value = figure.getNormalStyle().getValue(propertyName);
if (commonValue == null) {
commonValue = value;
} else {
if (!commonValue.equals(value)) {
return null;
}
}
}
return commonValue;
}
private VectorDataLayer getVectorDataLayer() {
Layer selectedLayer = getSelectedLayer();
if (selectedLayer instanceof VectorDataLayer) {
return (VectorDataLayer) selectedLayer;
} else {
return null;
}
}
private ProductSceneView getSelectedProductSceneView() {
return Utilities.actionsGlobalContext().lookup(ProductSceneView.class);
}
private FigureEditor getFigureEditor() {
final ProductSceneView view = getSelectedProductSceneView();
return view != null ? view.getFigureEditor() : null;
}
private Layer getSelectedLayer() {
final ProductSceneView view = getSelectedProductSceneView();
return view != null ? view.getSelectedLayer() : null;
}
private SimpleFeatureFigure[] getFigures(boolean selectedOnly) {
final ProductSceneView sceneView = getSelectedProductSceneView();
final SimpleFeatureFigure[] featureFigures = sceneView.getFeatureFigures(selectedOnly);
if (featureFigures.length > 0) {
return featureFigures;
}
return NO_SIMPLE_FEATURE_FIGURES;
}
private boolean areFiguresSelected() {
final ProductSceneView sceneView = getSelectedProductSceneView();
return sceneView.getFigureEditor().getFigureSelection().isEmpty();
}
private class SelectionChangeHandler extends AbstractSelectionChangeListener {
@Override
public void selectionChanged(SelectionChangeEvent event) {
handleLayerContentChanged();
}
}
/**
* Used to update the figure style, whenever users change style values using the editor.
*/
private class StyleUpdater implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
Debug.trace(String.format("VectorDataLayerEditor$StyleUpdater (1): property change: name=%s, oldValue=%s, newValue=%s",
evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()));
if (evt.getNewValue() == null) {
return;
}
String propertyName = evt.getPropertyName();
if (FILL_COLOR_NAME.equals(propertyName)) {
updateColorAndOpacity(FILL_COLOR_NAME, FILL_OPACITY_NAME);
} else if (STROKE_COLOR_NAME.equals(propertyName)) {
updateColorAndOpacity(STROKE_COLOR_NAME, STROKE_OPACITY_NAME);
}
if (isAdjusting.compareAndSet(false, true)) {
try {
SimpleFeatureFigure[] figures = getFigures(true);
if (figures.length == 0) {
figures = getFigures(false);
// todo - implement the following (nf)
// DefaultFigureStyle figureStyle = new DefaultFigureStyle("");
// default values are the common style values of all features
// figureStyle.setValue(FILL_COLOR_NAME, getCommonStylePropertyValue(figures, FILL_COLOR_NAME));
// figureStyle.setValue(FILL_OPACITY_NAME, getCommonStylePropertyValue(figures, FILL_OPACITY_NAME));
// figureStyle.setValue(STROKE_COLOR_NAME, getCommonStylePropertyValue(figures, STROKE_COLOR_NAME));
// ...
// figureStyle.setValue(evt.getPropertyName(), evt.getNewValue());
// String styleCss = figureStyle.toCssString();
// this will fire a "styleCss" product node change, which VectorDataLayer will receive
// in order to set the layer style.
// final VectorDataNode vectorDataNode = getVectorDataNode();
// if (vectorDataNode != null) {
// vectorDataNode.setStyleCss(styleCss);
// }
}
for (SimpleFeatureFigure figure : figures) {
final Object oldFigureValue = figure.getNormalStyle().getValue(propertyName);
final Object newValue = evt.getNewValue();
if (!newValue.equals(oldFigureValue)) {
Debug.trace(String.format("VectorDataLayerEditor$StyleUpdater (2): about to apply change: name=%s, oldValue=%s, newValue=%s",
propertyName, oldFigureValue, evt.getNewValue()));
// Transfer new style to affected figure.
final FigureStyle origStyle = figure.getNormalStyle();
final FigureStyle style = new DefaultFigureStyle();
style.fromCssString(origStyle.toCssString());
updateStyle(getBindingContext(), evt.getPropertyName(), style);
figure.setNormalStyle(style);
// todo - Actually figure.setNormalStyle(style); --> should fire event, so that associated
// placemark can save the new style. (nf 2011-11-23)
setFeatureStyleCss(figure, style);
}
}
} finally {
isAdjusting.set(false);
}
}
}
private void setFeatureStyleCss(SimpleFeatureFigure selectedFigure, FigureStyle style) {
final VectorDataNode vectorDataNode = getVectorDataNode();
if (vectorDataNode != null) {
// Transfer new style to associated placemark. Awful code :-(
final Placemark placemark = vectorDataNode.getPlacemarkGroup().getPlacemark(selectedFigure.getSimpleFeature());
if (placemark != null) {
placemark.setStyleCss(style.toCssString());
} else {
final int index = selectedFigure.getSimpleFeature().getFeatureType().indexOf(Placemark.PROPERTY_NAME_STYLE_CSS);
if (index != -1) {
selectedFigure.getSimpleFeature().setAttribute(index, style.toCssString());
}
}
}
}
}
}
| 15,903 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
NoDataLayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/editors/NoDataLayerEditor.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.editors;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.glayer.support.ImageLayer;
import org.esa.snap.core.layer.NoDataLayerType;
import org.esa.snap.ui.layer.AbstractLayerConfigurationEditor;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* @author Marco Peters
* @version $ Revision: $ Date: $
* @since BEAM 4.6
*/
public class NoDataLayerEditor extends AbstractLayerConfigurationEditor {
@Override
protected void addEditablePropertyDescriptors() {
PropertyDescriptor vd = new PropertyDescriptor(NoDataLayerType.PROPERTY_NAME_COLOR, Color.class);
vd.setDefaultValue(Color.ORANGE);
vd.setDisplayName("No-data colour");
vd.setDefaultConverter();
addPropertyDescriptor(vd);
getBindingContext().getPropertySet().addPropertyChangeListener(NoDataLayerType.PROPERTY_NAME_COLOR,
new UpdateImagePropertyChangeListener());
}
private class UpdateImagePropertyChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (getCurrentLayer() != null) {
final Color newColor = (Color) evt.getNewValue();
final ImageLayer layer = (ImageLayer) getCurrentLayer();
NoDataLayerType.renewMultiLevelSource(layer, newColor);
}
}
}
}
| 2,260 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TrackLayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/editors/TrackLayerEditor.java | package org.esa.snap.rcp.layermanager.editors;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.ui.product.SimpleFeatureFigure;
import java.awt.Color;
// todo - implement TrackLayerEditor (nf)
/**
* @author Norman Fomferra
*/
public class TrackLayerEditor extends VectorDataLayerEditor {
@Override
protected void addEditablePropertyDescriptors() {
super.addEditablePropertyDescriptors();
final PropertyDescriptor connectionLineWidth = new PropertyDescriptor("line-width", Double.class);
connectionLineWidth.setDefaultValue(1.0);
connectionLineWidth.setDefaultConverter(); // why this???
addPropertyDescriptor(connectionLineWidth);
final PropertyDescriptor connectionLineOpacity = new PropertyDescriptor("line-opacity", Double.class);
connectionLineOpacity.setDefaultValue(0.7);
connectionLineOpacity.setDefaultConverter(); // why this???
addPropertyDescriptor(connectionLineOpacity);
final PropertyDescriptor connectionLineColor = new PropertyDescriptor("line-color", Color.class);
connectionLineOpacity.setDefaultValue(Color.ORANGE);
connectionLineOpacity.setDefaultConverter(); // why this???
addPropertyDescriptor(connectionLineColor);
}
@Override
protected void updateProperties(SimpleFeatureFigure[] selectedFigures, BindingContext bindingContext) {
super.updateProperties(selectedFigures, bindingContext);
// todo - implement this (nf)
//updateProperty(bindingContext, "line-width", ...);
//updateProperty(bindingContext, "line-opacity", ...);
//updateProperty(bindingContext, "line-color", ...);
}
}
| 1,759 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GraticuleLayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/editors/GraticuleLayerEditor.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.rcp.layermanager.editors;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValueRange;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.swing.binding.BindingContext;
import org.esa.snap.core.layer.GraticuleLayerType;
import org.esa.snap.ui.layer.AbstractLayerConfigurationEditor;
import java.awt.*;
/**
* Editor for graticule layer.
*
* @author Marco Zuehlke
* @author Daniel Knowles
* @version $Revision$ $Date$
* @since BEAM 4.6
*/
//SEP2018 - Daniel Knowles - adds numerous new properties and related binding contexts.
//JAN2018 - Daniel Knowles - updated with SeaDAS gridline revisions
public class GraticuleLayerEditor extends AbstractLayerConfigurationEditor {
@Override
protected void addEditablePropertyDescriptors() {
// Grid Spacing Section
addSectionBreak(GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_NAME,
GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_LABEL,
GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_TOOLTIP);
PropertyDescriptor gridSpacingLatPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_NAME, Double.class);
gridSpacingLatPD.setDefaultValue(GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_DEFAULT);
gridSpacingLatPD.setValueRange(new ValueRange(0.0, 90.00));
gridSpacingLatPD.setDisplayName(GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_LABEL);
gridSpacingLatPD.setDescription(GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_TOOLTIP);
gridSpacingLatPD.setDefaultConverter();
addPropertyDescriptor(gridSpacingLatPD);
PropertyDescriptor gridSpacingLonPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_GRID_SPACING_LON_NAME, Double.class);
gridSpacingLonPD.setDefaultValue(GraticuleLayerType.PROPERTY_GRID_SPACING_LON_DEFAULT);
gridSpacingLonPD.setValueRange(new ValueRange(0.0, 180.00));
gridSpacingLonPD.setDisplayName(GraticuleLayerType.PROPERTY_GRID_SPACING_LON_LABEL);
gridSpacingLonPD.setDescription(GraticuleLayerType.PROPERTY_GRID_SPACING_LON_TOOLTIP);
gridSpacingLonPD.setDefaultConverter();
addPropertyDescriptor(gridSpacingLonPD);
// Labels Section
addSectionBreak(GraticuleLayerType.PROPERTY_LABELS_SECTION_NAME,
GraticuleLayerType.PROPERTY_LABELS_SECTION_LABEL,
GraticuleLayerType.PROPERTY_LABELS_SECTION_TOOLTIP);
PropertyDescriptor labelsNorthPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_NORTH_NAME, Boolean.class);
labelsNorthPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_NORTH_DEFAULT);
labelsNorthPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_NORTH_LABEL);
labelsNorthPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_NORTH_TOOLTIP);
labelsNorthPD.setDefaultConverter();
addPropertyDescriptor(labelsNorthPD);
PropertyDescriptor labelsSouthPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_SOUTH_NAME, Boolean.class);
labelsSouthPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_SOUTH_DEFAULT);
labelsSouthPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_SOUTH_LABEL);
labelsSouthPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_SOUTH_TOOLTIP);
labelsSouthPD.setDefaultConverter();
addPropertyDescriptor(labelsSouthPD);
PropertyDescriptor labelsWestPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_WEST_NAME, Boolean.class);
labelsWestPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_WEST_DEFAULT);
labelsWestPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_WEST_LABEL);
labelsWestPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_WEST_TOOLTIP);
labelsWestPD.setDefaultConverter();
addPropertyDescriptor(labelsWestPD);
PropertyDescriptor labelsEastPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_EAST_NAME, Boolean.class);
labelsEastPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_EAST_DEFAULT);
labelsEastPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_EAST_LABEL);
labelsEastPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_EAST_TOOLTIP);
labelsEastPD.setDefaultConverter();
addPropertyDescriptor(labelsEastPD);
PropertyDescriptor labelsSuffixPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_NAME, Boolean.class);
labelsSuffixPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_DEFAULT);
labelsSuffixPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_LABEL);
labelsSuffixPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_TOOLTIP);
labelsSuffixPD.setDefaultConverter();
addPropertyDescriptor(labelsSuffixPD);
PropertyDescriptor labelsDecimalPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_NAME, Boolean.class);
labelsDecimalPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_DEFAULT);
labelsDecimalPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_LABEL);
labelsDecimalPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_TOOLTIP);
labelsDecimalPD.setDefaultConverter();
addPropertyDescriptor(labelsDecimalPD);
PropertyDescriptor labelsInsidePD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, Boolean.class);
labelsInsidePD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_INSIDE_DEFAULT);
labelsInsidePD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_INSIDE_LABEL);
labelsInsidePD.setDescription(GraticuleLayerType.PROPERTY_LABELS_INSIDE_TOOLTIP);
labelsInsidePD.setDefaultConverter();
addPropertyDescriptor(labelsInsidePD);
PropertyDescriptor labelsItalicsPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_ITALIC_NAME, Boolean.class);
labelsItalicsPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_ITALIC_DEFAULT);
labelsItalicsPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_ITALIC_LABEL);
labelsItalicsPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_ITALIC_TOOLTIP);
labelsItalicsPD.setDefaultConverter();
addPropertyDescriptor(labelsItalicsPD);
PropertyDescriptor labelsBoldPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_BOLD_NAME, Boolean.class);
labelsBoldPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_BOLD_DEFAULT);
labelsBoldPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_BOLD_LABEL);
labelsBoldPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_BOLD_TOOLTIP);
labelsBoldPD.setDefaultConverter();
addPropertyDescriptor(labelsBoldPD);
PropertyDescriptor labelsRotationLatPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_NAME, Double.class);
labelsRotationLatPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_DEFAULT);
labelsRotationLatPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_LABEL);
labelsRotationLatPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_TOOLTIP);
labelsRotationLatPD.setDefaultConverter();
labelsRotationLatPD.setValueRange(new ValueRange(0, 90));
addPropertyDescriptor(labelsRotationLatPD);
PropertyDescriptor labelsRotationLonPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_NAME, Double.class);
labelsRotationLonPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_DEFAULT);
labelsRotationLonPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_LABEL);
labelsRotationLonPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_TOOLTIP);
labelsRotationLonPD.setDefaultConverter();
labelsRotationLonPD.setValueRange(new ValueRange(0, 90));
addPropertyDescriptor(labelsRotationLonPD);
PropertyDescriptor labelsFontPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_FONT_NAME, String.class);
labelsFontPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_FONT_DEFAULT);
labelsFontPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_FONT_LABEL);
labelsFontPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_FONT_TOOLTIP);
labelsFontPD.setValueSet(new ValueSet(GraticuleLayerType.PROPERTY_LABELS_FONT_VALUE_SET));
labelsFontPD.setDefaultConverter();
addPropertyDescriptor(labelsFontPD);
PropertyDescriptor labelSizePD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_SIZE_NAME, Integer.class);
labelSizePD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_SIZE_DEFAULT);
labelSizePD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_SIZE_LABEL);
labelSizePD.setDescription(GraticuleLayerType.PROPERTY_LABELS_SIZE_TOOLTIP);
labelSizePD.setValueRange(new ValueRange(GraticuleLayerType.PROPERTY_LABELS_SIZE_VALUE_MIN, GraticuleLayerType.PROPERTY_LABELS_SIZE_VALUE_MAX));
labelSizePD.setDefaultConverter();
addPropertyDescriptor(labelSizePD);
PropertyDescriptor labelColorPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_LABELS_COLOR_NAME, Color.class);
labelColorPD.setDefaultValue(GraticuleLayerType.PROPERTY_LABELS_COLOR_DEFAULT);
labelColorPD.setDisplayName(GraticuleLayerType.PROPERTY_LABELS_COLOR_LABEL);
labelColorPD.setDescription(GraticuleLayerType.PROPERTY_LABELS_COLOR_TOOLTIP);
labelColorPD.setDefaultConverter();
addPropertyDescriptor(labelColorPD);
// Gridlines Section
addSectionBreak(GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_NAME,
GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_LABEL,
GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_TOOLTIP);
PropertyDescriptor gridlinesShowPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, Boolean.class);
gridlinesShowPD.setDefaultValue(GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_DEFAULT);
gridlinesShowPD.setDisplayName(GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_LABEL);
gridlinesShowPD.setDescription(GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_TOOLTIP);
gridlinesShowPD.setDefaultConverter();
addPropertyDescriptor(gridlinesShowPD);
PropertyDescriptor girdlinesWidthPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_NAME, Double.class);
girdlinesWidthPD.setDefaultValue(GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_DEFAULT);
girdlinesWidthPD.setDisplayName(GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_LABEL);
girdlinesWidthPD.setDescription(GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_TOOLTIP);
girdlinesWidthPD.setDefaultConverter();
addPropertyDescriptor(girdlinesWidthPD);
PropertyDescriptor gridlinesDashedPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_NAME, Double.class);
gridlinesDashedPD.setDefaultValue(GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_DEFAULT);
gridlinesDashedPD.setDisplayName(GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_LABEL);
gridlinesDashedPD.setDescription(GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_TOOLTIP);
gridlinesDashedPD.setDefaultConverter();
addPropertyDescriptor(gridlinesDashedPD);
PropertyDescriptor gridlinesTransparencyPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_NAME, Double.class);
gridlinesTransparencyPD.setDefaultValue(GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_DEFAULT);
gridlinesTransparencyPD.setValueRange(new ValueRange(0, 1));
gridlinesTransparencyPD.setDisplayName(GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_LABEL);
gridlinesTransparencyPD.setDescription(GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_TOOLTIP);
gridlinesTransparencyPD.setDefaultConverter();
addPropertyDescriptor(gridlinesTransparencyPD);
PropertyDescriptor gridlinesColorPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_NAME, Color.class);
gridlinesColorPD.setDefaultValue(GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_DEFAULT);
gridlinesColorPD.setDisplayName(GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_LABEL);
gridlinesColorPD.setDescription(GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_TOOLTIP);
gridlinesColorPD.setDefaultConverter();
addPropertyDescriptor(gridlinesColorPD);
// Border Section
addSectionBreak(GraticuleLayerType.PROPERTY_BORDER_SECTION_NAME,
GraticuleLayerType.PROPERTY_BORDER_SECTION_LABEL,
GraticuleLayerType.PROPERTY_BORDER_SECTION_TOOLTIP);
PropertyDescriptor borderShowPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME, Boolean.class);
borderShowPD.setDefaultValue(GraticuleLayerType.PROPERTY_BORDER_SHOW_DEFAULT);
borderShowPD.setDisplayName(GraticuleLayerType.PROPERTY_BORDER_SHOW_LABEL);
borderShowPD.setDescription(GraticuleLayerType.PROPERTY_BORDER_SHOW_TOOLTIP);
borderShowPD.setDefaultConverter();
addPropertyDescriptor(borderShowPD);
PropertyDescriptor borderWidthPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_BORDER_WIDTH_NAME, Double.class);
borderWidthPD.setDefaultValue(GraticuleLayerType.PROPERTY_BORDER_WIDTH_DEFAULT);
borderWidthPD.setDisplayName(GraticuleLayerType.PROPERTY_BORDER_WIDTH_LABEL);
borderWidthPD.setDescription(GraticuleLayerType.PROPERTY_BORDER_WIDTH_TOOLTIP);
borderWidthPD.setDefaultConverter();
addPropertyDescriptor(borderWidthPD);
PropertyDescriptor borderColorPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_BORDER_COLOR_NAME, Color.class);
borderColorPD.setDefaultValue(GraticuleLayerType.PROPERTY_BORDER_COLOR_DEFAULT);
borderColorPD.setDisplayName(GraticuleLayerType.PROPERTY_BORDER_COLOR_LABEL);
borderColorPD.setDescription(GraticuleLayerType.PROPERTY_BORDER_COLOR_TOOLTIP);
borderColorPD.setDefaultConverter();
addPropertyDescriptor(borderColorPD);
// Tickmark Section
addSectionBreak(GraticuleLayerType.PROPERTY_TICKMARKS_SECTION_NAME,
GraticuleLayerType.PROPERTY_TICKMARKS_SECTION_LABEL,
GraticuleLayerType.PROPERTY_TICKMARKS_SECTION_TOOLTIP);
PropertyDescriptor tickmarksShowPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, Boolean.class);
tickmarksShowPD.setDefaultValue(GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_DEFAULT);
tickmarksShowPD.setDisplayName(GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_LABEL);
tickmarksShowPD.setDescription(GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_TOOLTIP);
tickmarksShowPD.setDefaultConverter();
addPropertyDescriptor(tickmarksShowPD);
PropertyDescriptor tickmarksInsidePD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_NAME, Boolean.class);
tickmarksInsidePD.setDefaultValue(GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_DEFAULT);
tickmarksInsidePD.setDisplayName(GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_LABEL);
tickmarksInsidePD.setDescription(GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_TOOLTIP);
tickmarksInsidePD.setDefaultConverter();
addPropertyDescriptor(tickmarksInsidePD);
PropertyDescriptor tickmarksLengthPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_NAME, Double.class);
tickmarksLengthPD.setDefaultValue(GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_DEFAULT);
tickmarksLengthPD.setDisplayName(GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_LABEL);
tickmarksLengthPD.setDescription(GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_TOOLTIP);
tickmarksLengthPD.setDefaultConverter();
addPropertyDescriptor(tickmarksLengthPD);
PropertyDescriptor tickmarksColorPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_NAME, Color.class);
tickmarksColorPD.setDefaultValue(GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_DEFAULT);
tickmarksColorPD.setDisplayName(GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_LABEL);
tickmarksColorPD.setDescription(GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_TOOLTIP);
tickmarksColorPD.setDefaultConverter();
addPropertyDescriptor(tickmarksColorPD);
// Corner Label Section
addSectionBreak(GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_NAME,
GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_LABEL,
GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_TOOLTIP);
PropertyDescriptor cornerLabelsNorthPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_NAME, Boolean.class);
cornerLabelsNorthPD.setDefaultValue(GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_DEFAULT);
cornerLabelsNorthPD.setDisplayName(GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_LABEL);
cornerLabelsNorthPD.setDescription(GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_TOOLTIP);
cornerLabelsNorthPD.setDefaultConverter();
addPropertyDescriptor(cornerLabelsNorthPD);
PropertyDescriptor cornerLabelsSouthPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_NAME, Boolean.class);
cornerLabelsSouthPD.setDefaultValue(GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_DEFAULT);
cornerLabelsSouthPD.setDisplayName(GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_LABEL);
cornerLabelsSouthPD.setDescription(GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_TOOLTIP);
cornerLabelsSouthPD.setDefaultConverter();
addPropertyDescriptor(cornerLabelsSouthPD);
PropertyDescriptor cornerLabelsWestPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_NAME, Boolean.class);
cornerLabelsWestPD.setDefaultValue(GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_DEFAULT);
cornerLabelsWestPD.setDisplayName(GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_LABEL);
cornerLabelsWestPD.setDescription(GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_TOOLTIP);
cornerLabelsWestPD.setDefaultConverter();
addPropertyDescriptor(cornerLabelsWestPD);
PropertyDescriptor cornerLabelsEastPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_NAME, Boolean.class);
cornerLabelsEastPD.setDefaultValue(GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_DEFAULT);
cornerLabelsEastPD.setDisplayName(GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_LABEL);
cornerLabelsEastPD.setDescription(GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_TOOLTIP);
cornerLabelsEastPD.setDefaultConverter();
addPropertyDescriptor(cornerLabelsEastPD);
// Inner Labels Section
addSectionBreak(GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_NAME,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_LABEL,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_TOOLTIP);
PropertyDescriptor innerLabelsBgTransparencyPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_NAME, Double.class);
innerLabelsBgTransparencyPD.setDefaultValue(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_DEFAULT);
innerLabelsBgTransparencyPD.setValueRange(new ValueRange(0, 1));
innerLabelsBgTransparencyPD.setDisplayName(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_LABEL);
innerLabelsBgTransparencyPD.setDescription(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_TOOLTIP);
innerLabelsBgTransparencyPD.setDefaultConverter();
addPropertyDescriptor(innerLabelsBgTransparencyPD);
PropertyDescriptor innerLabelsBgColorPD = new PropertyDescriptor(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_NAME, Color.class);
innerLabelsBgColorPD.setDefaultValue(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_DEFAULT);
innerLabelsBgColorPD.setDisplayName(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_LABEL);
innerLabelsBgColorPD.setDescription(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_TOOLTIP);
innerLabelsBgColorPD.setDefaultConverter();
addPropertyDescriptor(innerLabelsBgColorPD);
BindingContext bindingContext = getBindingContext();
boolean lineEnabled = (Boolean) bindingContext.getPropertySet().getValue(
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_NAME, lineEnabled,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, lineEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_NAME, lineEnabled,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, lineEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_NAME, lineEnabled,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, lineEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_NAME, lineEnabled,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, lineEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_NAME, lineEnabled,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, lineEnabled);
boolean borderEnabled = (Boolean) bindingContext.getPropertySet().getValue(
GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_BORDER_COLOR_NAME, borderEnabled,
GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME, borderEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_BORDER_WIDTH_NAME, borderEnabled,
GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME, borderEnabled);
// Set enablement associated with "Labels Inside" checkbox
boolean textInsideEnabled = (Boolean) bindingContext.getPropertySet().getValue(
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_NAME, textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_NAME, textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_NAME, !textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_NAME, !textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_NAME, !textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_NAME, !textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_NAME, !textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_NAME, !textInsideEnabled,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, textInsideEnabled);
boolean tickMarkEnabled = (Boolean) bindingContext.getPropertySet().getValue(
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_NAME, tickMarkEnabled,
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, tickMarkEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_NAME, tickMarkEnabled,
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, tickMarkEnabled);
bindingContext.bindEnabledState(GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_NAME, tickMarkEnabled,
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, tickMarkEnabled);
}
private void addSectionBreak(String name, String label, String toolTip) {
PropertyDescriptor descriptor = new PropertyDescriptor(name, Boolean.class);
descriptor.setDisplayName(label);
descriptor.setDescription(toolTip);
addPropertyDescriptor(descriptor);
}
}
| 25,974 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.