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 |
---|---|---|---|---|---|---|---|---|---|---|---|
OpenHSVImageViewAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/window/OpenHSVImageViewAction.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.rcp.actions.window;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.core.SubProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.util.PreferencesPropertyMap;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.HSVImageProfilePane;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneImage;
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.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.prefs.Preferences;
/**
* This action opens an HSV image view on the currently selected Product.
*/
@ActionID(category = "View", id = "OpenHSVImageViewAction")
@ActionRegistration(
displayName = "#CTL_OpenHSVImageViewAction_MenuText",
popupText = "#CTL_OpenHSVImageViewAction_MenuText",
iconBase = "org/esa/snap/rcp/icons/ImageView.gif",
lazy = true
)
@ActionReferences({
@ActionReference(path = "Menu/Window", position = 115),
@ActionReference(path = "Context/Product/Product", position = 50, separatorAfter = 55),
})
@NbBundle.Messages({
"CTL_OpenHSVImageViewAction_MenuText=Open HSV Image Window",
"CTL_OpenHSVImageViewAction_ShortDescription=Open an HSV image view for the selected product"
})
public class OpenHSVImageViewAction extends AbstractAction implements HelpCtx.Provider {
private static final String HELP_ID = "hsvImageProfile";
private static final String r = "min(round( (floor((6*(h))%6)==0?(v): (floor((6*(h))%6)==1?((1-((s)*((6*(h))%6)-floor((6*(h))%6)))*(v)): (floor((6*(h))%6)==2?((1-(s))*(v)): (floor((6*(h))%6)==3?((1-(s))*(v)): (floor((6*(h))%6)==4?((1-((s)*(1-((6*(h))%6)-floor((6*(h))%6))))*(v)): (floor((6*(h))%6)==5?(v):0)))))) *256), 255)";
private static final String g = "min(round( (floor((6*(h))%6)==0?((1-((s)*(1-((6*(h))%6)-floor((6*(h))%6))))*(v)): (floor((6*(h))%6)==1?(v): (floor((6*(h))%6)==2?(v): (floor((6*(h))%6)==3?((1-((s)*((6*(h))%6)-floor((6*(h))%6)))*(v)): (floor((6*(h))%6)==4?((1-(s))*(v)): (floor((6*(h))%6)==5?((1-(s))*(v)):0)))))) *256), 255)";
private static final String b = "min(round( (floor((6*(h))%6)==0?((1-(s))*(v)): (floor((6*(h))%6)==1?((1-(s))*(v)): (floor((6*(h))%6)==2?((1-((s)*(1-((6*(h))%6)-floor((6*(h))%6))))*(v)): (floor((6*(h))%6)==3?(v): (floor((6*(h))%6)==4?(v): (floor((6*(h))%6)==5?((1-((s)*((6*(h))%6)-floor((6*(h))%6)))*(v)):0)))))) *256), 255)";
private final Product product;
public OpenHSVImageViewAction(ProductNode node) {
super(Bundle.CTL_OpenHSVImageViewAction_MenuText());
product = node.getProduct();
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_OpenHSVImageViewAction_ShortDescription());
}
private static ProductSceneImage createProductSceneImageHSV(final String name, final Product product,
final String[] hsvExpressions,
final ProgressMonitor pm) {
Band[] rgbBands = null;
boolean errorOccured = false;
ProductSceneImage productSceneImage = null;
try {
pm.beginTask("Creating HSV image...", 2);
final String[] rgbaExpressions = convertHSVToRGBExpressions(hsvExpressions);
rgbBands = OpenRGBImageViewAction.allocateRgbBands(product, rgbaExpressions);
final Preferences preferences = SnapApp.getDefault().getPreferences();
final PreferencesPropertyMap configuration = new PreferencesPropertyMap(preferences);
productSceneImage = new ProductSceneImage(name,
rgbBands[0],
rgbBands[1],
rgbBands[2],
configuration,
SubProgressMonitor.create(pm, 1));
productSceneImage.initVectorDataCollectionLayer();
productSceneImage.initMaskCollectionLayer();
} catch (Exception e) {
errorOccured = true;
throw e;
} finally {
pm.done();
if (rgbBands != null) {
OpenRGBImageViewAction.releaseRgbBands(rgbBands, errorOccured);
}
}
return productSceneImage;
}
private static void nomalizeHSVExpressions(final Product product, String[] hsvExpressions) {
// normalize
//range = max - min;
//normvalue = min(max(((v- min)/range),0), 1);
boolean modified = product.isModified();
final Product[] products = SnapApp.getDefault().getProductManager().getProducts();
int i = 0;
for (String exp : hsvExpressions) {
if (exp.isEmpty()) continue;
final String checkForNoDataValue = "";//getCheckForNoDataExpression(product, exp);
final Band virtBand = createVirtualBand(product, products, exp, "tmpVirtBand" + i);
final Stx stx = virtBand.getStx(false, ProgressMonitor.NULL);
if (stx != null) {
final double min = stx.getMinimum();
final double range = stx.getMaximum() - min;
hsvExpressions[i] = checkForNoDataValue + "min(max((((" + exp + ")- " + min + ")/" + range + "), 0), 1)";
}
product.removeBand(virtBand);
++i;
}
product.setModified(modified);
}
private static String getCheckForNoDataExpression(final Product product, final String exp) {
final String[] bandNames = product.getBandNames();
StringBuilder checkForNoData = new StringBuilder("(" + exp + " == NaN");
if (StringUtils.contains(bandNames, exp)) {
double nodatavalue = product.getBand(exp).getNoDataValue();
checkForNoData.append(" or " + exp + " == " + nodatavalue);
}
checkForNoData.append(") ? NaN : ");
return checkForNoData.toString();
}
private static Band createVirtualBand(final Product product, final Product[] products, final String expression, final String name) {
int width = product.getSceneRasterWidth();
int height = product.getSceneRasterHeight();
try {
final RasterDataNode[] refRasters = BandArithmetic.getRefRasters(expression, products);
if (refRasters.length > 0) {
width = refRasters[0].getRasterWidth();
height = refRasters[0].getRasterHeight();
}
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid expression: " + expression);
}
final VirtualBand virtBand = new VirtualBand(name,
ProductData.TYPE_FLOAT64,
width,
height,
expression);
virtBand.setNoDataValueUsed(true);
product.addBand(virtBand);
return virtBand;
}
private static String[] convertHSVToRGBExpressions(final String[] hsvExpressions) {
final String h = hsvExpressions[0].isEmpty() ? "0" : hsvExpressions[0];
final String s = hsvExpressions[1].isEmpty() ? "0" : hsvExpressions[1];
final String v = hsvExpressions[2].isEmpty() ? "0" : hsvExpressions[2];
// h,s,v in [0,1]
/* float rr = 0, gg = 0, bb = 0;
float hh = (6 * h) % 6;
int c1 = (int) hh; // floor((6*(h))%6)
float c2 = hh - c1; // ((6*(h))%6)-floor((6*(h))%6)
float x = (1 - s) * v; // ((1-(s))*(v))
float y = (1 - (s * c2)) * v; // ((1-((s)*((6*(h))%6)-floor((6*(h))%6)))*(v))
float z = (1 - (s * (1 - c2))) * v; // ((1-((s)*(1-((6*(h))%6)-floor((6*(h))%6))))*(v))
switch (c1) {
case 0: rr=v; gg=z; bb=x; break;
case 1: rr=y; gg=v; bb=x; break;
case 2: rr=x; gg=v; bb=z; break;
case 3: rr=x; gg=y; bb=v; break;
case 4: rr=z; gg=x; bb=v; break;
case 5: rr=v; gg=x; bb=y; break;
}
int N = 256;
int r = Math.min(Math.round(rr*N),N-1);
int g = Math.min(Math.round(gg*N),N-1);
int b = Math.min(Math.round(bb*N),N-1);
*/
final String[] rgbExpressions = new String[3];
rgbExpressions[0] = r.replace("(h)", '(' + h + ')').replace("(s)", '(' + s + ')').replace("(v)", '(' + v + ')');
rgbExpressions[1] = g.replace("(h)", '(' + h + ')').replace("(s)", '(' + s + ')').replace("(v)", '(' + v + ')');
rgbExpressions[2] = b.replace("(h)", '(' + h + ')').replace("(s)", '(' + s + ')').replace("(v)", '(' + v + ')');
return rgbExpressions;
}
@Override
public void actionPerformed(final ActionEvent event) {
if (product != null) {
openProductSceneViewHSV(product, HELP_ID);
}
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
public void openProductSceneViewHSV(Product hsvProduct, final String helpId) {
final Product[] openedProducts = SnapApp.getDefault().getProductManager().getProducts();
final int[] defaultBandIndices = OpenRGBImageViewAction.getDefaultBandIndices(hsvProduct);
final Preferences preferences = SnapApp.getDefault().getPreferences();
final HSVImageProfilePane profilePane = new HSVImageProfilePane(new PreferencesPropertyMap(preferences),
hsvProduct,
openedProducts, defaultBandIndices);
final String title = "Select HSV-Image Channels";
final boolean ok = profilePane.showDialog(SnapApp.getDefault().getMainFrame(), title, helpId);
if (!ok) {
return;
}
final String[] hsvExpressions = profilePane.getRgbaExpressions();
nomalizeHSVExpressions(hsvProduct, hsvExpressions);
if (profilePane.getStoreProfileInProduct()) {
RGBImageProfile.storeRgbaExpressions(hsvProduct, hsvExpressions, HSVImageProfilePane.HSV_COMP_NAMES);
}
final String sceneName = OpenRGBImageViewAction.createSceneName(hsvProduct, profilePane.getSelectedProfile(), "HSV");
openProductSceneViewHSV(sceneName, hsvProduct, hsvExpressions);
}
/**
* Creates product scene view using the given HSV expressions.
*/
public void openProductSceneViewHSV(final String name, final Product product, final String[] hsvExpressions) {
final SwingWorker<ProductSceneImage, Object> worker = new ProgressMonitorSwingWorker<>(
SnapApp.getDefault().getMainFrame(),
SnapApp.getDefault().getInstanceName() + " - Creating image for '" + name + '\'') {
@Override
protected ProductSceneImage doInBackground(ProgressMonitor pm) {
return createProductSceneImageHSV(name, product, hsvExpressions, pm);
}
@Override
protected void done() {
SnapApp.getDefault().getMainFrame().setCursor(Cursor.getDefaultCursor());
String errorMsg = "The HSV image view could not be created.";
try {
final ProductSceneView productSceneView = new ProductSceneView(get());
OpenRGBImageViewAction.openDocumentWindow(productSceneView);
} catch (OutOfMemoryError e) {
Dialogs.showOutOfMemoryError(errorMsg);
return;
} catch (Exception e) {
SnapApp.getDefault().handleError(errorMsg, e);
return;
}
SnapApp.getDefault().setStatusBarMessage("");
}
};
SnapApp.getDefault().setStatusBarMessage("Creating HSV image view..."); /*I18N*/
UIUtils.setRootFrameWaitCursor(SnapApp.getDefault().getMainFrame());
worker.execute();
}
}
| 12,860 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OpenRGBImageViewAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/window/OpenRGBImageViewAction.java | /*
* Copyright (C) 2014 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.actions.window;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.core.SubProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import eu.esa.snap.netbeans.docwin.DocumentWindowManager;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.util.ArrayUtils;
import org.esa.snap.core.util.PreferencesPropertyMap;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.windows.ProductSceneViewTopComponent;
import org.esa.snap.ui.RGBImageProfilePane;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneImage;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.awt.*;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import java.util.prefs.Preferences;
import java.util.stream.Collectors;
/**
* This action opens an RGB image view on the currently selected Product.
*
* @author Marco Peters
*/
@ActionID(category = "View", id = "OpenRGBImageViewAction")
@ActionRegistration(
displayName = "#CTL_OpenRGBImageViewAction_MenuText",
popupText = "#CTL_OpenRGBImageViewAction_MenuText",
iconBase = "org/esa/snap/rcp/icons/ImageView.gif",
lazy = true
)
@ActionReferences({
@ActionReference(path = "Menu/Window", position = 110),
@ActionReference(path = "Context/Product/Product", position = 40, separatorBefore = 35),
})
@NbBundle.Messages({
"CTL_OpenRGBImageViewAction_MenuText=Open RGB Image Window",
"CTL_OpenRGBImageViewAction_ShortDescription=Open an RGB image view for the selected product"
})
public class OpenRGBImageViewAction extends AbstractAction implements HelpCtx.Provider {
private static final String HELP_ID = "rgbImageProfile";
private final Product product;
public OpenRGBImageViewAction(ProductNode node) {
super(Bundle.CTL_OpenRGBImageViewAction_MenuText());
product = node.getProduct();
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_OpenRGBImageViewAction_ShortDescription());
}
public static int[] getDefaultBandIndices(final Product product) {
int[] bandIndices = null;
final Band[] bands = product.getBands();
if (bands.length == 1) {
return new int[]{0};
} else if (bands.length == 2) {
return new int[]{0, 1};
} else if (bands.length > 2) {
bandIndices = new int[3];
int cnt = 0, i = 0;
for (Band band : product.getBands()) {
final String unit = band.getUnit();
if (unit != null && unit.contains("intensity")) {
bandIndices[i++] = cnt;
}
if (i >= bandIndices.length)
break;
++cnt;
}
if (i == 0) {
while (i < 3) {
bandIndices[i] = i++;
}
}
if (i == 1) {
return new int[]{bandIndices[0]};
} else if (i == 2) {
return new int[]{bandIndices[0], bandIndices[1]};
}
}
return bandIndices;
}
public static ProductSceneViewTopComponent openDocumentWindow(final ProductSceneView view) {
UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(view.getProduct());
ProductSceneViewTopComponent psvTopComponent = new ProductSceneViewTopComponent(view, undoManager);
DocumentWindowManager.getDefault().openWindow(psvTopComponent);
psvTopComponent.requestSelected();
return psvTopComponent;
}
static RGBChannelDef mergeRgbChannelDefs(RGBImageProfile rgbImageProfile, Band[] rgbBands) {
final RGBChannelDef defFromProfile = rgbImageProfile.getRgbChannelDef();
for (int i = 0; i < rgbBands.length; i++) {
final ImageInfo bandImageInfo = rgbBands[i].getImageInfo();
final double min = defFromProfile.getMinDisplaySample(i);
if (Double.isNaN(min)) {
final RGBChannelDef rgbChannelDef = bandImageInfo.getRgbChannelDef();
if (rgbChannelDef != null) {
defFromProfile.setMinDisplaySample(i, rgbChannelDef.getMinDisplaySample(i));
} else {
final double minColorPalette = bandImageInfo.getColorPaletteDef().getFirstPoint().getSample();
defFromProfile.setMinDisplaySample(i, minColorPalette);
}
}
final double max = defFromProfile.getMaxDisplaySample(i);
if (Double.isNaN(max)) {
final RGBChannelDef rgbChannelDef = bandImageInfo.getRgbChannelDef();
if (rgbChannelDef != null) {
defFromProfile.setMaxDisplaySample(i, rgbChannelDef.getMaxDisplaySample(i));
} else {
final double maxColorPalette = bandImageInfo.getColorPaletteDef().getLastPoint().getSample();
defFromProfile.setMaxDisplaySample(i, maxColorPalette);
}
}
}
return defFromProfile;
}
public static Band[] allocateRgbBands(final Product product, final String[] rgbaExpressions) {
final Band[] rgbBands = new Band[3]; // todo - set to [4] as soon as we support alpha
final boolean productModificationState = product.isModified();
final Product[] products = SnapApp.getDefault().getProductManager().getProducts();
final int elementIndex = ArrayUtils.getElementIndex(product, products);
try {
//if (!BandArithmetic.areRastersEqualInSize(product, rgbaExpressions)) {
// If there are multiple product references, the call should consider all the products
if (!BandArithmetic.areRastersEqualInSize(products, elementIndex, rgbaExpressions)) {
throw new IllegalArgumentException("Referenced rasters are not of the same size");
}
} catch (ParseException e) {
throw new IllegalArgumentException("Expressions are invalid");
}
// if more than 1 products referenced, then don't get the band of the context product
final Set<Product> referencedProducts = new HashSet<>();
Arrays.stream(rgbaExpressions).forEach(e -> {
try {
referencedProducts.addAll(
Arrays.stream(BandArithmetic.getRefRasters(e, products))
.map(ProductNode::getProduct)
.collect(Collectors.toList())
);
} catch (ParseException pex) {
SystemUtils.LOG.warning(pex.getMessage());
}
});
boolean moreProductsReferences = referencedProducts.size() > 1;
for (int i = 0; i < rgbBands.length; i++) {
String expression = rgbaExpressions[i].isEmpty() ? "0" : rgbaExpressions[i];
Band rgbBand = moreProductsReferences ? null : product.getBand(expression);
if (rgbBand == null) {
rgbBand = new ProductSceneView.RGBChannel(product,
determineWidth(expression, products, elementIndex),
determineHeight(expression, products, elementIndex),
RGBImageProfile.RGB_BAND_NAMES[i],
expression, products);
}
rgbBands[i] = rgbBand;
}
product.setModified(productModificationState);
return rgbBands;
}
private static int determineWidth(String expression, Product[] products, int index) {
int width = products[index].getSceneRasterWidth();
try {
final RasterDataNode[] refRasters = BandArithmetic.getRefRasters(expression, products, index);
if (refRasters.length > 0) {
width = refRasters[0].getRasterWidth();
}
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid expression: " + expression);
}
return width;
}
private static int determineHeight(String expression, Product[] products, int index) {
int height = products[index].getSceneRasterHeight();
try {
final RasterDataNode[] refRasters = BandArithmetic.getRefRasters(expression, products, index);
if (refRasters.length > 0) {
height = refRasters[0].getRasterHeight();
}
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid expression: " + expression);
}
return height;
}
public static void releaseRgbBands(Band[] rgbBands, boolean errorOccurred) {
for (int i = 0; i < rgbBands.length; i++) {
Band rgbBand = rgbBands[i];
if (rgbBand != null) {
if (rgbBand instanceof ProductSceneView.RGBChannel) {
if (errorOccurred) {
rgbBand.dispose();
}
}
}
rgbBands[i] = null;
}
}
public static String createSceneName(Product product, RGBImageProfile rgbImageProfile, String operation) {
final StringBuilder nameBuilder = new StringBuilder();
final String productRef = product.getProductRefString();
if (productRef != null) {
nameBuilder.append(productRef);
nameBuilder.append(" ");
}
if (rgbImageProfile != null) {
nameBuilder.append(rgbImageProfile.getName().replace("_", " "));
nameBuilder.append(" ");
}
nameBuilder.append(operation);
return nameBuilder.toString();
}
@Override
public void actionPerformed(ActionEvent e) {
if (product != null) {
openProductSceneViewRGB(product, HELP_ID);
}
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
public void openProductSceneViewRGB(Product rgbProduct, final String helpId) {
final Product[] openedProducts = SnapApp.getDefault().getProductManager().getProducts();
final int[] defaultBandIndices = getDefaultBandIndices(rgbProduct);
final Preferences preferences = SnapApp.getDefault().getPreferences();
final PreferencesPropertyMap preferencesPropertyMap = new PreferencesPropertyMap(preferences);
final RGBImageProfilePane profilePane = new RGBImageProfilePane(preferencesPropertyMap, rgbProduct,
openedProducts, defaultBandIndices);
final String title = "Select RGB-Image Channels";
final boolean ok = profilePane.showDialog(SnapApp.getDefault().getMainFrame(), title, helpId);
if (!ok) {
return;
}
final RGBImageProfile rgbProfile = profilePane.getRgbProfile();
if (profilePane.getStoreProfileInProduct()) {
RGBImageProfile.storeRgbaExpressions(rgbProduct, rgbProfile.getRgbaExpressions());
}
final String sceneName = createSceneName(rgbProduct, profilePane.getSelectedProfile(), "RGB");
openProductSceneViewRGB(sceneName, rgbProduct, rgbProfile);
}
private void openProductSceneViewRGB(final String name, final Product product, final RGBImageProfile rgbImageProfile) {
final SwingWorker<ProductSceneImage, Object> worker = new ProgressMonitorSwingWorker<ProductSceneImage, Object>(
SnapApp.getDefault().getMainFrame(),
SnapApp.getDefault().getInstanceName() + " - Creating image for '" + name + "'") {
@Override
protected ProductSceneImage doInBackground(ProgressMonitor pm) throws Exception {
return createProductSceneImageRGB(name, product, rgbImageProfile, pm);
}
@Override
protected void done() {
SnapApp.getDefault().getMainFrame().setCursor(Cursor.getDefaultCursor());
String errorMsg = "The RGB image view could not be created.";
try {
ProductSceneView productSceneView = new ProductSceneView(get());
openDocumentWindow(productSceneView);
} catch (OutOfMemoryError e) {
Dialogs.showOutOfMemoryError(errorMsg);
return;
} catch (Exception e) {
SnapApp.getDefault().handleError(errorMsg, e);
return;
}
SnapApp.getDefault().setStatusBarMessage("");
}
};
SnapApp.getDefault().setStatusBarMessage("Creating RGB image view..."); /*I18N*/
UIUtils.setRootFrameWaitCursor(SnapApp.getDefault().getMainFrame());
worker.execute();
}
private ProductSceneImage createProductSceneImageRGB(String name, final Product product, RGBImageProfile rgbImageProfile,
ProgressMonitor pm) {
Band[] rgbBands = null;
boolean errorOccurred = false;
ProductSceneImage productSceneImage = null;
try {
pm.beginTask("Creating RGB image...", 2);
final Preferences preferences = SnapApp.getDefault().getPreferences();
final PreferencesPropertyMap preferencesPropertyMap = new PreferencesPropertyMap(preferences);
rgbBands = allocateRgbBands(product, rgbImageProfile.getRgbaExpressions());
productSceneImage = new ProductSceneImage(name, rgbBands[0],
rgbBands[1],
rgbBands[2],
preferencesPropertyMap,
SubProgressMonitor.create(pm, 1));
productSceneImage.initVectorDataCollectionLayer();
productSceneImage.initMaskCollectionLayer();
final RGBChannelDef userRgbChannelDef = mergeRgbChannelDefs(rgbImageProfile, rgbBands);
final ImageInfo imageInfo = new ImageInfo(userRgbChannelDef);
productSceneImage.setImageInfo(imageInfo);
} catch (Exception e) {
errorOccurred = true;
throw e;
} finally {
pm.done();
if (rgbBands != null) {
releaseRgbBands(rgbBands, errorOccurred);
}
}
return productSceneImage;
}
}
| 15,361 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OpenQuicklookViewAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/window/OpenQuicklookViewAction.java | /*
* Copyright (C) 2016 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.rcp.actions.window;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.quicklooks.Quicklook;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.quicklooks.QuicklookToolView;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import org.openide.windows.WindowManager;
import javax.swing.*;
import java.awt.event.ActionEvent;
import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.EXPLORER;
/**
* This action opens a Quicklook View of the currently selected Quicklook Node
*/
@ActionID(category = "File", id = "OpenQuicklookViewAction" )
@ActionRegistration(displayName = "#CTL_OpenQuicklookViewAction_MenuText" )
@ActionReferences({
@ActionReference(path = "Context/Product/Quicklook", position = 100),
@ActionReference(path = "Menu/Window", position = 130)
})
@NbBundle.Messages("CTL_OpenQuicklookViewAction_MenuText=Open Quicklook Window")
public class OpenQuicklookViewAction extends AbstractAction implements ContextAwareAction, LookupListener {
private Lookup lookup;
private final Lookup.Result<ProductNode> result;
public OpenQuicklookViewAction() {
this(Utilities.actionsGlobalContext());
}
public OpenQuicklookViewAction(Lookup lookup) {
this.lookup = lookup;
result = lookup.lookupResult(ProductNode.class);
result.addLookupListener(
WeakListeners.create(LookupListener.class, this, result));
setEnableState();
putValue(Action.NAME, Bundle.CTL_OpenQuicklookViewAction_MenuText());
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new OpenQuicklookViewAction(lookup);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnableState();
}
private void setEnableState() {
ProductNode productNode = lookup.lookup(ProductNode.class);
setEnabled(productNode != null && productNode instanceof Quicklook);
}
@Override
public void actionPerformed(ActionEvent e) {
openQuicklookView((Quicklook) SnapApp.getDefault().getSelectedProductNode(EXPLORER));
}
public void openQuicklookView(final Quicklook ql) {
openDocumentWindow(ql);
}
private void openDocumentWindow(final Quicklook ql) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
final QuicklookToolView window = (QuicklookToolView)WindowManager.getDefault().findTopComponent("QuicklookToolView");
if(window != null) {
window.open();
window.requestActive();
window.setSelectedQuicklook(ql);
}
}
});
}
}
| 3,846 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ShowTutorialsPageAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/help/ShowTutorialsPageAction.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/
*/
package org.esa.snap.rcp.actions.help;
import org.esa.snap.runtime.Config;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
/**
* This action launches the default browser to display the project tutorials.
*/
@ActionID(category = "Help", id = "ShowTutorialsPageAction" )
@ActionRegistration(
displayName = "#CTL_ShowTutorialsPageAction_MenuText",
popupText = "#CTL_ShowTutorialsPageAction_MenuText")
@ActionReference(path = "Menu/Help", position = 310)
@NbBundle.Messages({
"CTL_ShowTutorialsPageAction_MenuText=Tutorials",
"CTL_ShowTutorialsPageAction_ShortDescription=Browse the SNAP Toolboxes tutorials web page"
})
public class ShowTutorialsPageAction extends AbstractAction {
private static final String DEFAULT_PAGE_URL = "https://step.esa.int/main/tutorials";
/**
* Launches the default browser to display the tutorials.
* Invoked when a command action is performed.
*
* @param event the command event.
*/
@Override
public void actionPerformed(ActionEvent event) {
DesktopHelper.browse(Config.instance().preferences().get("snap.tutorialsPageUrl", DEFAULT_PAGE_URL));
}
}
| 2,060 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DesktopHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/help/DesktopHelper.java | package org.esa.snap.rcp.actions.help;
import org.esa.snap.rcp.util.Dialogs;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created by Norman on 30.05.2015.
*/
class DesktopHelper {
public static void browse(String uriString) {
final Desktop desktop = Desktop.getDesktop();
URI uri;
try {
uri = new URI(uriString);
} catch (URISyntaxException e) {
Dialogs.showError(String.format("Internal error: Invalid URI:\n%s", uriString));
return;
}
try {
desktop.browse(uri);
} catch (IOException e) {
Dialogs.showError(String.format("<html>Failed to open URL in browser:<br><a href=\"%s\">%s</a>",
uriString, uriString));
} catch (UnsupportedOperationException e) {
Dialogs.showError("Sorry, it seems that there is no browser available.");
}
}
}
| 1,011 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ShowHomePageAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/help/ShowHomePageAction.java | /*
* Copyright (C) 2014 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.rcp.actions.help;
import org.esa.snap.runtime.Config;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
/**
* This action launches the default browser to display the project web page.
*/
@ActionID(category = "Help", id = "ShowHomePageAction")
@ActionRegistration(
displayName = "#CTL_ShowHomePageAction_MenuText",
popupText = "#CTL_ShowHomePageAction_MenuText")
@ActionReference(path = "Menu/Help", position = 300)
@NbBundle.Messages({
"CTL_ShowHomePageAction_MenuText=STEP Home Page",
"CTL_ShowHomePageAction_ShortDescription=Browse the STEP home page"
})
public class ShowHomePageAction extends AbstractAction {
private static final String DEFAULT_PAGE_URL = "https://step.esa.int";
/**
* Launches the default browser to display the web site.
* Invoked when a command action is performed.
*
* @param event the command event.
*/
@Override
public void actionPerformed(ActionEvent event) {
DesktopHelper.browse(Config.instance().preferences().get("snap.homePageUrl", DEFAULT_PAGE_URL));
}
}
| 1,995 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReportIssueAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/help/ReportIssueAction.java | /*
* Copyright (C) 2014 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.rcp.actions.help;
import org.esa.snap.runtime.Config;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
/**
* This action launches the default browser to display the web page explaining how to best report an issue.
*/
@ActionID(category = "Help", id = "ReportIssueAction")
@ActionRegistration(
displayName = "#CTL_ReportIssueAction_MenuText",
popupText = "#CTL_ReportIssueAction_MenuText"
)
@ActionReference(path = "Menu/Help", position = 305)
@NbBundle.Messages({
"CTL_ReportIssueAction_MenuText=Report an Issue",
"CTL_ReportIssueAction_ShortDescription=Opens a web page explaining how to report an issue"
})
public class ReportIssueAction extends AbstractAction {
private static final String DEFAULT_REPORT_ISSUE_PAGE_URL = "https://step.esa.int/main/community/issue-reporting/";
/**
* Launches the default browser to display the web page.
* Invoked when a command action is performed.
*
* @param event the command event.
*/
@Override
public void actionPerformed(ActionEvent event) {
DesktopHelper.browse(Config.instance().preferences().get("snap.reportIssuePageUrl", DEFAULT_REPORT_ISSUE_PAGE_URL));
}
}
| 2,112 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ShowOnlineHelpAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/help/ShowOnlineHelpAction.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/
*/
package org.esa.snap.rcp.actions.help;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.runtime.Config;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.*;
import java.awt.event.ActionEvent;
/**
* This action launches the default browser to display the online help.
*/
@ActionID(category = "Help", id = "ShowOnlineHelpAction" )
@ActionRegistration(
displayName = "#CTL_ShowOnlineHelpAction_MenuText",
popupText = "#CTL_ShowOnlineHelpAction_MenuText")
@ActionReference(path = "Menu/Help", position = 205)
@NbBundle.Messages({
"CTL_ShowOnlineHelpAction_MenuText=Online Help",
"CTL_ShowOnlineHelpAction_ShortDescription=Browse the SNAP Toolboxes online help"
})
public class ShowOnlineHelpAction extends AbstractAction {
/** URl for the online help. */
private static final String DEFAULT_ONLINE_HELP_URL = "https://step.esa.int/main/doc/online-help";
/**
* Launches the default browser to display the tutorials.
* Invoked when a command action is performed.
*
* @param event the command event.
*/
@Override
public void actionPerformed(ActionEvent event) {
final String url = Config.instance().preferences().get("snap.online.help.url", DEFAULT_ONLINE_HELP_URL);
DesktopHelper.browse(url + "?version=" + SystemUtils.getReleaseVersion());
}
}
| 2,196 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ShowLogInExplorer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/help/ShowLogInExplorer.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.actions.help;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.util.Dialogs;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* @author muhammad.bc.
*/
@ActionID(category = "Help", id = "ShowLogFileInExplorerAction")
@ActionRegistration(displayName = "#CTL_ShowLogFileInExplorerAction_MenuText")
@ActionReference(path = "Menu/Help", position = 400)
@NbBundle.Messages({"CTL_ShowLogFileInExplorerAction_MenuText=Show Log Directory"})
public class ShowLogInExplorer extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
openLogFile();
}
private void openLogFile() {
String os = System.getProperty("os.name").toLowerCase();
Path userHomeDir = SystemUtils.getUserHomeDir().toPath();
Path logDir = null;
if (isLinuxOrMac(os)) {
logDir = userHomeDir.resolve(".snap/system/var/log");
} else if (os.startsWith("windows")) {
logDir = userHomeDir.resolve("AppData/Roaming/SNAP/var/log");
}
if (logDir != null && Files.exists(logDir)) {
try {
Desktop.getDesktop().open(logDir.toFile());
} catch (IOException e) {
Dialogs.showError("Could not open log directory!");
}
}
}
private boolean isLinuxOrMac(String os) {
return os.startsWith("darwin") || os.startsWith("mac") || os.startsWith("linux");
}
}
| 2,515 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
HelpAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/help/HelpAction.java | package org.esa.snap.rcp.actions.help;
import org.esa.snap.tango.TangoIcons;
import org.esa.snap.ui.help.HelpDisplayer;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
/**
* Basic help action.
*
* @author Norman Fomferra
*/
@NbBundle.Messages({
"CTL_HelpActionText=Help",
"CTL_HelpActionToolTip=Invokes the help system."
})
public class HelpAction extends AbstractAction implements HelpCtx.Provider {
private final HelpCtx helpCtx;
private final HelpCtx.Provider delegateHelpCtx;
public HelpAction() {
this(HelpCtx.DEFAULT_HELP);
}
public HelpAction(HelpCtx.Provider delegateHelpCtx) {
this.delegateHelpCtx = delegateHelpCtx;
this.helpCtx = null;
initProperties();
}
public HelpAction(HelpCtx helpCtx) {
this.helpCtx = helpCtx;
this.delegateHelpCtx = null;
initProperties();
}
private void initProperties() {
putValue(ACTION_COMMAND_KEY, "help");
putValue(NAME, Bundle.CTL_HelpActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_HelpActionToolTip());
putValue(SMALL_ICON, TangoIcons.apps_help_browser(TangoIcons.Res.R16));
putValue(LARGE_ICON_KEY, TangoIcons.apps_help_browser(TangoIcons.Res.R22));
}
@Override
public HelpCtx getHelpCtx() {
return delegateHelpCtx != null ? delegateHelpCtx.getHelpCtx() : helpCtx;
}
@Override
public void actionPerformed(ActionEvent e) {
HelpDisplayer.show(getHelpCtx());
}
}
| 1,606 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
StatusbarAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/view/StatusbarAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.view;
import org.esa.snap.rcp.util.BooleanPreferenceKeyAction;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
/**
* @author Norman
*/
@ActionID(category = "View", id = "StatusbarAction" )
@ActionRegistration(displayName = "#CTL_StatusbarAction_Text", lazy = false)
@ActionReference(path = "Menu/View", position = 301)
@NbBundle.Messages({
"CTL_StatusbarAction_Text=Statusbar",
"CTL_StatusbarAction_ToolTip=Change visibility of the Statusbar."
})
public final class StatusbarAction extends BooleanPreferenceKeyAction {
public static final String PREFERENCE_KEY = "statusbar_visibility";
public static final boolean PREFERENCE_DEFAULT_VALUE = true;
public StatusbarAction() {
super(PREFERENCE_KEY, PREFERENCE_DEFAULT_VALUE);
putValue(NAME, Bundle.CTL_StatusbarAction_Text());
putValue(SHORT_DESCRIPTION, Bundle.CTL_StatusbarAction_ToolTip());
}
}
| 1,228 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DetachPixelGeoCodingAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/tools/DetachPixelGeoCodingAction.java | /*
* Copyright (C) 2014 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.actions.tools;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.BasicPixelGeoCoding;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.UIUtils;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.awt.UndoRedo;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingWorker;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import java.awt.event.ActionEvent;
@ActionID(
category = "Tools",
id = "DetachPixelGeoCodingAction"
)
@ActionRegistration(
displayName = "#CTL_DetachPixelGeoCodingActionText",
popupText = "#CTL_DetachPixelGeoCodingActionText",
lazy = false
)
@ActionReference(path = "Menu/Tools", position = 220)
@Messages({
"CTL_DetachPixelGeoCodingActionText=Detach Pixel Geo-Coding...",
"CTL_DetachPixelGeoCodingDialogTitle=Detach Pixel Geo-Coding"
})
public class DetachPixelGeoCodingAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final Lookup lookup;
public DetachPixelGeoCodingAction() {
this(Utilities.actionsGlobalContext());
}
public DetachPixelGeoCodingAction(Lookup lkp) {
super(Bundle.CTL_DetachPixelGeoCodingActionText());
this.lookup = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
putValue(Action.SHORT_DESCRIPTION, "Detach a pixel based geo-coding from the selected product");
setEnableState();
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
detachPixelGeoCoding(lookup.lookup(ProductNode.class).getProduct());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new DetachPixelGeoCodingAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
private static void detachPixelGeoCoding(final Product product) {
final SwingWorker swingWorker = new SwingWorker<Throwable, Object>() {
@Override
protected Throwable doInBackground() throws Exception {
try {
GeoCoding geoCoding = product.getSceneGeoCoding();
if (geoCoding instanceof BasicPixelGeoCoding) {
final BasicPixelGeoCoding pixelGeoCoding = (BasicPixelGeoCoding) geoCoding;
final GeoCoding delegate = pixelGeoCoding.getPixelPosEstimator();
product.setSceneGeoCoding(delegate);
UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product);
if (undoManager != null) {
undoManager.addEdit(new UndoableDetachGeoCoding<>(product, pixelGeoCoding));
}
}
} catch (Throwable e) {
return e;
}
return null;
}
@Override
public void done() {
try {
Throwable value;
try {
value = get();
} catch (Exception e) {
value = e;
}
String dialogTitle = Bundle.CTL_DetachPixelGeoCodingDialogTitle();
if (value != null) {
Dialogs.showError(dialogTitle, "An internal error occurred:\n" + value.getMessage());
} else {
Dialogs.showInformation(dialogTitle, "Pixel geo-coding has been detached.", null);
}
} finally {
UIUtils.setRootFrameDefaultCursor(SnapApp.getDefault().getMainFrame());
}
}
};
UIUtils.setRootFrameWaitCursor(SnapApp.getDefault().getMainFrame());
swingWorker.execute();
}
private void setEnableState() {
ProductNode productNode = lookup.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
Product product = productNode.getProduct();
if (product != null) {
state = product.getSceneGeoCoding() instanceof BasicPixelGeoCoding;
}
}
setEnabled(state);
}
private static class UndoableDetachGeoCoding<T extends BasicPixelGeoCoding> extends AbstractUndoableEdit {
private Product product;
private T pixelGeoCoding;
public UndoableDetachGeoCoding(Product product, T pixelGeoCoding) {
Assert.notNull(product, "product");
Assert.notNull(pixelGeoCoding, "pixelGeoCoding");
this.product = product;
this.pixelGeoCoding = pixelGeoCoding;
}
@Override
public String getPresentationName() {
return Bundle.CTL_DetachPixelGeoCodingDialogTitle();
}
@Override
public void undo() throws CannotUndoException {
super.undo();
product.setSceneGeoCoding(pixelGeoCoding);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
if (product.getSceneGeoCoding() == pixelGeoCoding) {
product.setSceneGeoCoding(pixelGeoCoding.getPixelPosEstimator());
}
}
@Override
public void die() {
pixelGeoCoding = null;
product = null;
}
}
}
| 6,965 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SyncImageViewsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/tools/SyncImageViewsAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.tools;
import org.esa.snap.rcp.util.BooleanPreferenceKeyAction;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
/**
* @author Norman
*/
@ActionID(category = "View", id = "SyncImageViewsAction" )
@ActionRegistration(displayName = "#CTL_SyncImageViewsActionName", lazy = false )
@ActionReference(path = "Menu/View", position = 319, separatorAfter = 320 )
@NbBundle.Messages({
"CTL_SyncImageViewsActionName=Synchronise Image Views",
"CTL_SyncImageViewsActionToolTip=Synchronises views across multiple image windows."
})
public final class SyncImageViewsAction extends BooleanPreferenceKeyAction {
public static final String PREFERENCE_KEY = "auto_sync_image_views";
public static final boolean PREFERENCE_DEFAULT_VALUE = false;
public SyncImageViewsAction() {
super(PREFERENCE_KEY, PREFERENCE_DEFAULT_VALUE);
putValue(NAME, Bundle.CTL_SyncImageViewsActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/SyncViews24.png", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_SyncImageViewsActionToolTip());
}
}
| 1,467 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CopyPixelInfoToClipboardAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/tools/CopyPixelInfoToClipboardAction.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.actions.tools;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.util.MultiSizeIssue;
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.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import java.awt.event.ActionEvent;
@ActionID(category = "Tools", id = "org.esa.snap.rcp.actions.tools.CopyPixelInfoToClipboardAction")
@ActionRegistration(
displayName = "#CTL_CopyPixelInfoToClipboardAction_MenuText",
popupText = "#CTL_CopyPixelInfoToClipboardAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/Raster/Export", position = 300),
@ActionReference(path = "Context/ProductSceneView", position = 110)
})
@NbBundle.Messages({
"CTL_CopyPixelInfoToClipboardAction_MenuText=Pixel-Info to Clipboard",
"CTL_CopyPixelInfoToClipboardAction_PopupText=Copy Pixel-Info to Clipboard",
"CTL_CopyPixelInfoToClipboardAction_DialogTitle=Copy Pixel-Info to Clipboard",
"CTL_CopyPixelInfoToClipboardAction_ShortDescription=Copy Pixel-Info to Clipboard."
})
public class CopyPixelInfoToClipboardAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final Lookup.Result<ProductSceneView> result;
public CopyPixelInfoToClipboardAction() {
this(Utilities.actionsGlobalContext());
}
public CopyPixelInfoToClipboardAction(Lookup lkp) {
super(Bundle.CTL_CopyPixelInfoToClipboardAction_MenuText());
putValue("popupText", Bundle.CTL_CopyPixelInfoToClipboardAction_PopupText());
result = lkp.lookupResult(ProductSceneView.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
updateEnableState(getCurrentSceneView());
}
/**
* Invoked when a command action is performed.
*
* @param event the command event
*/
@Override
public void actionPerformed(ActionEvent event) {
copyPixelInfoStringToClipboard();
}
@Override
public Action createContextAwareInstance(Lookup lkp) {
return new CopyPixelInfoToClipboardAction(lkp);
}
@Override
public void resultChanged(LookupEvent le) {
updateEnableState(getCurrentSceneView());
}
private void copyPixelInfoStringToClipboard() {
final ProductSceneView view = getCurrentSceneView();
if (view != null) {
Product product = view.getProduct();
if (product != null) {
final RasterDataNode viewRaster = view.getRaster();
SystemUtils.copyToClipboard(product.createPixelInfoString(view.getCurrentPixelX(), view.getCurrentPixelY(),
viewRaster));
}
}
}
private ProductSceneView getCurrentSceneView() {
return result.allInstances().stream().findFirst().orElse(null);
}
private void updateEnableState(ProductSceneView sceneView) {
setEnabled(sceneView != null);
}
}
| 4,294 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SyncImageCursorsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/tools/SyncImageCursorsAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.tools;
import org.esa.snap.rcp.util.BooleanPreferenceKeyAction;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
/**
* @author Norman
*/
@ActionID(category = "View", id = "SyncImageCursorsAction" )
@ActionRegistration(displayName = "#CTL_SyncImageCursorsActionName", lazy = false )
@ActionReference(path = "Menu/View", position = 311, separatorBefore = 310 )
@NbBundle.Messages({
"CTL_SyncImageCursorsActionName=Synchronise Image Cursors",
"CTL_SyncImageCursorsActionToolTip=Synchronises cursor positions across multiple image windows."
})
public final class SyncImageCursorsAction extends BooleanPreferenceKeyAction {
public static final String PREFERENCE_KEY = "auto_sync_image_cursors";
public static final boolean PREFERENCE_DEFAULT_VALUE = false;
public SyncImageCursorsAction() {
super(PREFERENCE_KEY, PREFERENCE_DEFAULT_VALUE);
putValue(NAME, Bundle.CTL_SyncImageCursorsActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/SyncCursor24.png", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_SyncImageCursorsActionToolTip());
}
}
| 1,500 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AttachPixelGeoCodingAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/tools/AttachPixelGeoCodingAction.java | /*
* Copyright (C) 2014 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.actions.tools;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.core.dataio.geocoding.*;
import org.esa.snap.core.dataio.geocoding.forward.PixelForward;
import org.esa.snap.core.dataio.geocoding.forward.PixelInterpolatingForward;
import org.esa.snap.core.dataio.geocoding.inverse.PixelQuadTreeInverse;
import org.esa.snap.core.dataio.geocoding.util.RasterUtils;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.runtime.Config;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.awt.UndoRedo;
import org.openide.util.*;
import org.openide.util.NbBundle.Messages;
import javax.swing.*;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.prefs.Preferences;
import static org.esa.snap.core.dataio.geocoding.ComponentGeoCoding.SYSPROP_SNAP_PIXEL_CODING_FRACTION_ACCURACY;
@ActionID(
category = "Tools",
id = "AttachPixelGeoCodingAction"
)
@ActionRegistration(
displayName = "#CTL_AttachPixelGeoCodingActionText",
popupText = "#CTL_AttachPixelGeoCodingActionText",
lazy = false
)
@ActionReference(path = "Menu/Tools", position = 210, separatorBefore = 200)
@Messages({
"CTL_AttachPixelGeoCodingActionText=Attach Pixel Geo-Coding...",
"CTL_AttachPixelGeoCodingDialogTitle=Attach Pixel Geo-Coding",
"CTL_AttachPixelGeoCodingDialogDescription=Attach a pixel based geo-coding to the selected product"
})
public class AttachPixelGeoCodingAction extends AbstractAction implements ContextAwareAction, LookupListener {
private static final String HELP_ID = "pixelGeoCodingSetup";
private static final int ONE_MB = 1024 * 1024;
private final Lookup lkp;
public AttachPixelGeoCodingAction() {
this(Utilities.actionsGlobalContext());
}
private AttachPixelGeoCodingAction(Lookup lkp) {
super(Bundle.CTL_AttachPixelGeoCodingActionText());
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_AttachPixelGeoCodingDialogDescription());
setEnableState();
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new AttachPixelGeoCodingAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
final Product selectedProduct = lkp.lookup(ProductNode.class).getProduct();
final int validBandCount = getValidBandCount(selectedProduct);
if (validBandCount < 2) {
Dialogs.showError("Pixel Geo-Coding cannot be attached: Too few bands of product scene size");
return;
}
attachPixelGeoCoding(selectedProduct);
}
static int getValidBandCount(Product product) {
final Band[] bands = product.getBands();
int validBandsCount = 0;
for (Band band : bands) {
if (band.getRasterSize().equals(product.getSceneRasterSize())) {
validBandsCount++;
if (validBandsCount == 2) {
break;
}
}
}
return validBandsCount;
}
static long getRequiredMemory(Product product) {
final int width = product.getSceneRasterWidth();
final int height = product.getSceneRasterHeight();
final int sizeOfDouble = 8;
return width * height * 2 * sizeOfDouble;
}
private void setEnableState() {
ProductNode productNode = lkp.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
Product product = productNode.getProduct();
if (product != null) {
state = product.getNumBands() >= 2;
}
}
setEnabled(state);
}
private static void attachPixelGeoCoding(final Product product) {
final SnapApp snapApp = SnapApp.getDefault();
final Window mainFrame = snapApp.getMainFrame();
final String dialogTitle = Bundle.CTL_AttachPixelGeoCodingDialogTitle();
final PixelGeoCodingSetupDialog setupDialog = new PixelGeoCodingSetupDialog(mainFrame,
dialogTitle,
HELP_ID,
product);
if (setupDialog.show() != ModalDialog.ID_OK) {
return;
}
final Band lonBand = setupDialog.getSelectedLonBand();
final Band latBand = setupDialog.getSelectedLatBand();
final String groundResString = setupDialog.getGroundResString();
final double groundResInKm = Double.parseDouble(groundResString);
final String msgPattern = "New Pixel Geo-Coding: lon = ''{0}'' ; lat = ''{1}'' ; ground resolution=''{2}''";
snapApp.getLogger().log(Level.INFO, MessageFormat.format(msgPattern,
lonBand.getName(), latBand.getName(),
groundResString));
final long requiredBytes = getRequiredMemory(product);
final long requiredMegas = requiredBytes / ONE_MB;
final long freeMegas = Runtime.getRuntime().freeMemory() / ONE_MB;
if (freeMegas < requiredMegas) {
final String message = MessageFormat.format("This operation requires to load at least {0} M\n" +
"of additional data into memory.\n\n" +
"Do you really want to continue?",
requiredMegas);
final Dialogs.Answer answer = Dialogs.requestDecision(dialogTitle, message, false, "load_latlon_band_data");
if (answer != Dialogs.Answer.YES) {
return;
}
}
UIUtils.setRootFrameWaitCursor(mainFrame);
final ProgressMonitorSwingWorker<Void, Void> swingWorker = new ProgressMonitorSwingWorker<Void, Void>(mainFrame, dialogTitle) {
@Override
protected Void doInBackground(ProgressMonitor pm) throws Exception {
final double[] longitudes = RasterUtils.loadDataScaled(lonBand);
final double[] latitudes = RasterUtils.loadDataScaled(latBand);
final GeoRaster geoRaster = new GeoRaster(longitudes, latitudes, lonBand.getName(), latBand.getName(),
product.getSceneRasterWidth(), product.getSceneRasterHeight(), groundResInKm);
final Preferences preferences = Config.instance("snap").preferences();
final boolean useFractAccuracy = preferences.getBoolean(SYSPROP_SNAP_PIXEL_CODING_FRACTION_ACCURACY, false);
final ForwardCoding forward;
final InverseCoding inverse;
if (useFractAccuracy) {
forward = ComponentFactory.getForward(PixelInterpolatingForward.KEY);
inverse = ComponentFactory.getInverse(PixelQuadTreeInverse.KEY_INTERPOLATING);
} else {
forward = ComponentFactory.getForward(PixelForward.KEY);
inverse = ComponentFactory.getInverse(PixelQuadTreeInverse.KEY);
}
final ComponentGeoCoding geoCoding = new ComponentGeoCoding(geoRaster, forward, inverse, GeoChecks.POLES);
geoCoding.initialize();
final GeoCoding oldGeoCoding = product.getSceneGeoCoding();
product.setSceneGeoCoding(geoCoding);
UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product);
if (undoManager != null) {
undoManager.addEdit(new UndoableAttachGeoCoding(product, geoCoding, oldGeoCoding));
}
return null;
}
@Override
public void done() {
try {
get();
Dialogs.showInformation(dialogTitle, "Pixel geo-coding has been attached.", null);
} catch (Exception e) {
Throwable cause = e;
if (e instanceof ExecutionException) {
cause = e.getCause();
}
String msg = "An internal error occurred:\n" + e.getMessage();
if (cause instanceof IOException) {
msg = "An I/O error occurred:\n" + e.getMessage();
}
Dialogs.showError(dialogTitle, msg);
} finally {
UIUtils.setRootFrameDefaultCursor(mainFrame);
}
}
};
swingWorker.executeWithBlocking();
}
private static class PixelGeoCodingSetupDialog extends ModalDialog {
private Product product;
private String selectedLonBand;
private String selectedLatBand;
private String[] bandNames;
private JComboBox<String> lonBox;
private JComboBox<String> latBox;
private JTextField groundResField;
private final double defaultResolution = 1.0;
PixelGeoCodingSetupDialog(final Window parent, final String title,
final String helpID, final Product product) {
super(parent, title, ModalDialog.ID_OK_CANCEL_HELP, helpID);
this.product = product;
final Band[] bands = product.getBands();
if (product.isMultiSize()) {
List<String> bandNameList = new ArrayList<>();
for (Band band : bands) {
if (band.getRasterSize().equals(product.getSceneRasterSize())) {
bandNameList.add(band.getName());
}
}
bandNames = bandNameList.toArray(new String[0]);
} else {
bandNames = Arrays.stream(bands).map(Band::getName).toArray(String[]::new);
}
}
@Override
public int show() {
createUI();
return super.show();
}
Band getSelectedLonBand() {
return product.getBand(selectedLonBand);
}
Band getSelectedLatBand() {
return product.getBand(selectedLatBand);
}
String getGroundResString() {
return groundResField.getText();
}
@Override
protected void onOK() {
final String lonValue = (String) lonBox.getSelectedItem();
selectedLonBand = findBandName(lonValue);
final String latValue = (String) latBox.getSelectedItem();
selectedLatBand = findBandName(latValue);
if (selectedLatBand == null || selectedLonBand == null || Objects.equals(selectedLatBand, selectedLonBand)) {
Dialogs.showWarning(Bundle.CTL_AttachPixelGeoCodingDialogTitle(),
"You have to select two different bands for the pixel geo-coding.",
null);
} else {
super.onOK();
}
}
@Override
protected void onCancel() {
selectedLatBand = null;
selectedLonBand = null;
super.onCancel();
}
private void createUI() {
final JPanel panel = new JPanel(new GridBagLayout());
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
final JLabel lonLabel = new JLabel("Longitude band:");
final JLabel latLabel = new JLabel("Latitude band:");
final JLabel groundResLabel = new JLabel("Ground Resolution in km:");
lonBox = new JComboBox<>(bandNames);
latBox = new JComboBox<>(bandNames);
doPreSelection(lonBox, "lon");
doPreSelection(latBox, "lat");
groundResField = new JTextField(Double.toString(defaultResolution));
groundResField.setCaretPosition(0);
gbc.insets = new Insets(3, 2, 3, 2);
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 0.0;
gbc.gridx = 0;
gbc.gridy = 0;
panel.add(lonLabel, gbc);
gbc.weightx = 1;
gbc.gridx++;
gbc.gridwidth = 1;
panel.add(lonBox, gbc);
gbc.weightx = 0.0;
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 1;
panel.add(latLabel, gbc);
gbc.weightx = 1;
gbc.gridx++;
gbc.gridwidth = 1;
panel.add(latBox, gbc);
gbc.weightx = 0.0;
gbc.gridx = 0;
gbc.gridy++;
gbc.gridwidth = 1;
panel.add(groundResLabel, gbc);
gbc.weightx = 1;
gbc.gridx++;
panel.add(groundResField, gbc);
setContent(panel);
}
private void doPreSelection(final JComboBox comboBox, final String toFind) {
final String bandToSelect = getBandNameContaining(toFind);
if (StringUtils.isNotNullAndNotEmpty(bandToSelect)) {
comboBox.setSelectedItem(bandToSelect);
}
}
private String getBandNameContaining(final String toFind) {
return Arrays.stream(bandNames).filter(s -> s.contains(toFind)).findFirst().orElse(null);
}
private String findBandName(final String bandName) {
return Arrays.stream(bandNames).filter(s -> s.equals(bandName)).findFirst().orElseGet(() -> null);
}
}
private static class UndoableAttachGeoCoding extends AbstractUndoableEdit {
private Product product;
private GeoCoding oldGeoCoding;
private GeoCoding currentGeoCoding;
UndoableAttachGeoCoding(Product product, GeoCoding currentGeoCoding, GeoCoding oldGeoCoding) {
this.product = product;
this.currentGeoCoding = currentGeoCoding;
this.oldGeoCoding = oldGeoCoding;
}
@Override
public String getPresentationName() {
return Bundle.CTL_AttachPixelGeoCodingDialogTitle();
}
@Override
public void undo() throws CannotUndoException {
super.undo();
product.setSceneGeoCoding(oldGeoCoding);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
product.setSceneGeoCoding(currentGeoCoding);
}
@Override
public void die() {
oldGeoCoding = null;
currentGeoCoding = null;
product = null;
}
}
}
| 16,160 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CreateGeoCodingDisplacementBandsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/raster/CreateGeoCodingDisplacementBandsAction.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.actions.raster;
import com.bc.ceres.core.Assert;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.ColorPaletteDef;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.datamodel.PixelPos;
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.VirtualBand;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.preferences.general.UiBehaviorController;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.UIUtils;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.awt.UndoRedo;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
@ActionID(
category = "Tools",
id = "CreateGeoCodingDisplacementBandsAction"
)
@ActionRegistration(
displayName = "#CTL_CreateGeoCodingDisplacementBandsActionText",
popupText = "#CTL_CreateGeoCodingDisplacementBandsActionText"
)
@ActionReference(path = "Menu/Raster", position = 30 )
@NbBundle.Messages({
"CTL_CreateGeoCodingDisplacementBandsActionText=Geo-Coding Displacement Bands...",
"CTL_CreateGeoCodingDisplacementBandsDialogTitle=Geo-Coding Displacement Bands",
"CTL_CreateGeoCodingDisplacementBandsDescription=<html>Computes actual pixel position minus pixel position computed from inverse\n" +
" geo-coding<br/>\n" +
" and adds displacements as new bands (test for geo-coding accuracy)."
})
/**
* An action that lets users add a number of bands that can be used to assess the performance/accuracy
* of the current geo-coding.
*/
public class CreateGeoCodingDisplacementBandsAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final Lookup lookup;
public static final float[][] OFFSETS = new float[][]{
{0.00f, 0.00f},
{0.25f, 0.25f},
{0.50f, 0.50f},
{0.75f, 0.75f},
{0.25f, 0.75f},
{0.75f, 0.25f},
};
public CreateGeoCodingDisplacementBandsAction() {
this(Utilities.actionsGlobalContext());
}
public CreateGeoCodingDisplacementBandsAction(Lookup lookup) {
super(Bundle.CTL_CreateGeoCodingDisplacementBandsActionText());
this.lookup = lookup;
Lookup.Result<ProductNode> lkpContext = lookup.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
setEnableState();
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_CreateGeoCodingDisplacementBandsDescription());
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new CreateGeoCodingDisplacementBandsAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
@Override
public void actionPerformed(ActionEvent event) {
createXYDisplacementBands(lookup.lookup(ProductNode.class).getProduct());
}
private void setEnableState() {
ProductNode productNode = lookup.lookup(ProductNode.class);
boolean state = false;
if (productNode != null) {
Product product = productNode.getProduct();
if (product != null && !product.isMultiSize()) {
state = product.getSceneGeoCoding() != null &&
product.getSceneGeoCoding().canGetGeoPos() &&
product.getSceneGeoCoding().canGetPixelPos();
}
}
setEnabled(state);
}
private void createXYDisplacementBands(Product product) {
final SnapApp snapApp = SnapApp.getDefault();
final Frame mainFrame = snapApp.getMainFrame();
String dialogTitle = Bundle.CTL_CreateGeoCodingDisplacementBandsDialogTitle();
final ProgressMonitorSwingWorker swingWorker = new ProgressMonitorSwingWorker<Band[], Object>(mainFrame, dialogTitle) {
@Override
protected Band[] doInBackground(ProgressMonitor pm) throws Exception {
final Band[] xyDisplacementBands = createXYDisplacementBands(product, pm);
UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product);
if (undoManager != null) {
undoManager.addEdit(new UndoableDisplacementBandsCreation(product, xyDisplacementBands));
}
return xyDisplacementBands;
}
@Override
public void done() {
if (snapApp.getPreferences().getBoolean(UiBehaviorController.PREFERENCE_KEY_AUTO_SHOW_NEW_BANDS, true)) {
try {
Band[] bands = get();
if (bands == null) {
return;
}
for (Band band : bands) {
Band oldBand = product.getBand(band.getName());
if (oldBand != null) {
product.removeBand(oldBand);
}
product.addBand(band);
}
} catch (Exception e) {
Throwable cause = e;
if (e instanceof ExecutionException) {
cause = e.getCause();
}
String msg = "An internal error occurred:\n" + e.getMessage();
if (cause instanceof IOException) {
msg = "An I/O error occurred:\n" + e.getMessage();
}
Dialogs.showError(dialogTitle, msg);
} finally {
UIUtils.setRootFrameDefaultCursor(mainFrame);
}
}
}
};
swingWorker.execute();
}
private static Band[] createXYDisplacementBands(final Product product, ProgressMonitor pm) {
final int width = product.getSceneRasterWidth();
final int height = product.getSceneRasterHeight();
ImageInfo blueToRedGrad = new ImageInfo(new ColorPaletteDef(new ColorPaletteDef.Point[]{
new ColorPaletteDef.Point(-1.0, Color.BLUE),
new ColorPaletteDef.Point(0.0, Color.WHITE),
new ColorPaletteDef.Point(1.0, Color.RED),
}));
ImageInfo amplGrad = new ImageInfo(new ColorPaletteDef(new ColorPaletteDef.Point[]{
new ColorPaletteDef.Point(0.0, Color.WHITE),
new ColorPaletteDef.Point(1.0, Color.RED),
}));
ImageInfo phaseGrad = new ImageInfo(new ColorPaletteDef(new ColorPaletteDef.Point[]{
new ColorPaletteDef.Point(-Math.PI, Color.WHITE),
new ColorPaletteDef.Point(0.0, Color.BLUE),
new ColorPaletteDef.Point(+Math.PI, Color.WHITE),
}));
final Band bandX = new Band("gc_displ_x", ProductData.TYPE_FLOAT64, width, height);
configureBand(bandX, blueToRedGrad.clone(), "pixels", "Geo-coding X-displacement");
final Band bandY = new Band("gc_displ_y", ProductData.TYPE_FLOAT64, width, height);
configureBand(bandY, blueToRedGrad.clone(), "pixels", "Geo-coding Y-displacement");
final Band bandAmpl = new VirtualBand("gc_displ_ampl",
ProductData.TYPE_FLOAT64, width, height,
"ampl(gc_displ_x, gc_displ_y)");
configureBand(bandAmpl, amplGrad.clone(), "pixels", "Geo-coding displacement amplitude");
final Band bandPhase = new VirtualBand("gc_displ_phase",
ProductData.TYPE_FLOAT64, width, height,
"phase(gc_displ_x, gc_displ_y)");
configureBand(bandPhase, phaseGrad.clone(), "radians", "Geo-coding displacement phase");
final double[] dataX = new double[width * height];
final double[] dataY = new double[width * height];
bandX.setRasterData(ProductData.createInstance(dataX));
bandY.setRasterData(ProductData.createInstance(dataY));
pm.beginTask("Computing geo-coding displacements for product '" + product.getName() + "'...", height);
try {
final GeoPos geoPos = new GeoPos();
final PixelPos pixelPos1 = new PixelPos();
final PixelPos pixelPos2 = new PixelPos();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
double maxX = 0;
double maxY = 0;
double valueX = 0;
double valueY = 0;
for (float[] offset : OFFSETS) {
pixelPos1.setLocation(x + offset[0], y + offset[1]);
product.getSceneGeoCoding().getGeoPos(pixelPos1, geoPos);
product.getSceneGeoCoding().getPixelPos(geoPos, pixelPos2);
double dx = pixelPos2.x - pixelPos1.x;
double dy = pixelPos2.y - pixelPos1.y;
if (Math.abs(dx) > maxX) {
maxX = Math.abs(dx);
valueX = dx;
}
if (Math.abs(dy) > maxY) {
maxY = Math.abs(dy);
valueY = dy;
}
}
dataX[y * width + x] = valueX;
dataY[y * width + x] = valueY;
}
if (pm.isCanceled()) {
return null;
}
pm.worked(1);
}
} finally {
pm.done();
}
return new Band[]{bandX, bandY, bandAmpl, bandPhase};
}
private static void configureBand(Band band05X, ImageInfo imageInfo, String unit, String description) {
band05X.setUnit(unit);
band05X.setDescription(description);
band05X.setImageInfo(imageInfo);
band05X.setNoDataValue(Double.NaN);
band05X.setNoDataValueUsed(true);
}
private static class UndoableDisplacementBandsCreation extends AbstractUndoableEdit {
private Band[] displacementBands;
private Product product;
public UndoableDisplacementBandsCreation(Product product, Band[] displacementBands) {
Assert.notNull(product, "product");
Assert.notNull(displacementBands, "displacementBands");
this.product = product;
this.displacementBands = displacementBands;
}
@Override
public String getPresentationName() {
return Bundle.CTL_CreateGeoCodingDisplacementBandsDialogTitle();
}
@Override
public void undo() throws CannotUndoException {
super.undo();
for (Band displacementBand : displacementBands) {
if (product.containsBand(displacementBand.getName())) {
product.removeBand(displacementBand);
}
}
}
@Override
public void redo() throws CannotRedoException {
super.redo();
for (Band displacementBand : displacementBands) {
if (!product.containsBand(displacementBand.getName())) {
product.addBand(displacementBand);
product.fireProductNodeChanged(displacementBand.getName());
}
}
}
@Override
public void die() {
product = null;
displacementBands = null;
}
}
}
| 13,422 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ConvertComputedBandIntoBandAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/raster/ConvertComputedBandIntoBandAction.java | /*
* Copyright (C) 2014 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.actions.raster;
import com.bc.ceres.glevel.MultiLevelImage;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.windows.ProductSceneViewTopComponent;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.EXPLORER;
/**
* Converts a virtual band into a "real" band.
*
* @author marcoz
*/
@ActionID(category = "Tools", id = "ConvertComputedBandIntoBandAction")
@ActionRegistration(
displayName = "#CTL_ConvertComputedBandIntoBandAction_MenuText",
popupText = "#CTL_ConvertComputedBandIntoBandAction_MenuText"
)
@ActionReferences({
@ActionReference(path = "Menu/Raster", position = 20),
@ActionReference(path = "Context/Product/RasterDataNode", position = 30)
})
@NbBundle.Messages({
"CTL_ConvertComputedBandIntoBandAction_MenuText=Convert Band",
"CTL_ConvertComputedBandIntoBandAction_ShortDescription=Computes a \"real\" band from a virtual band or filtered band"
})
public class ConvertComputedBandIntoBandAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final Lookup lookup;
@SuppressWarnings("FieldCanBeLocal")
private final Lookup.Result<VirtualBand> vbResult;
@SuppressWarnings("FieldCanBeLocal")
private final Lookup.Result<FilterBand> fbResult;
public ConvertComputedBandIntoBandAction() {
this(Utilities.actionsGlobalContext());
}
public ConvertComputedBandIntoBandAction(Lookup lookup) {
super(Bundle.CTL_ConvertComputedBandIntoBandAction_MenuText());
this.lookup = lookup;
vbResult = lookup.lookupResult(VirtualBand.class);
vbResult.addLookupListener(WeakListeners.create(LookupListener.class, this, vbResult));
fbResult = lookup.lookupResult(FilterBand.class);
fbResult.addLookupListener(WeakListeners.create(LookupListener.class, this, fbResult));
setEnableState();
}
private void setEnableState() {
VirtualBand virtualBand = lookup.lookup(VirtualBand.class);
FilterBand filterBand = lookup.lookup(FilterBand.class);
setEnabled(virtualBand != null || filterBand != null);
}
@Override
public void actionPerformed(ActionEvent e) {
SnapApp snapApp = SnapApp.getDefault();
ProductNode selectedProductNode = snapApp.getSelectedProductNode(EXPLORER);
if (!isComputedBand(selectedProductNode)) {
return;
}
Band computedBand = (Band) selectedProductNode;
String bandName = computedBand.getName();
int width = computedBand.getRasterWidth();
int height = computedBand.getRasterHeight();
Band realBand = new Band(bandName, computedBand.getDataType(), width, height);
realBand.setDescription(createDescription(computedBand));
realBand.setValidPixelExpression(computedBand.getValidPixelExpression());
realBand.setUnit(computedBand.getUnit());
realBand.setSpectralWavelength(computedBand.getSpectralWavelength());
realBand.setGeophysicalNoDataValue(computedBand.getGeophysicalNoDataValue());
realBand.setNoDataValueUsed(computedBand.isNoDataValueUsed());
if (computedBand.isStxSet()) {
realBand.setStx(computedBand.getStx());
}
ImageInfo imageInfo = computedBand.getImageInfo();
if (imageInfo != null) {
realBand.setImageInfo(imageInfo.clone());
}
//--- Check if all the frame with the raster data are close
Product product = computedBand.getProduct();
ProductSceneViewTopComponent topComponent = getProductSceneViewTopComponent(computedBand);
if (topComponent != null) {
topComponent.close();
}
ProductNodeGroup<Band> bandGroup = product.getBandGroup();
int bandIndex = bandGroup.indexOf(computedBand);
bandGroup.remove(computedBand);
bandGroup.add(bandIndex, realBand);
realBand.setSourceImage(createSourceImage(computedBand, realBand));
realBand.setModified(true);
}
MultiLevelImage createSourceImage(Band computedBand, Band realBand) {
if (computedBand instanceof VirtualBand) {
return VirtualBand.createSourceImage(realBand, ((VirtualBand) computedBand).getExpression());
} else {
return computedBand.getSourceImage();
}
}
private String createDescription(Band computedBand) {
if (computedBand instanceof VirtualBand) {
VirtualBand virtualBand = (VirtualBand) computedBand;
String oldDescription = virtualBand.getDescription();
String newDescription = oldDescription == null ? "" : oldDescription.trim();
String formerExpressionDescription = "(expression was '" + virtualBand.getExpression() + "')";
newDescription = newDescription.isEmpty() ? formerExpressionDescription : newDescription + " " + formerExpressionDescription;
return newDescription;
} else {
return computedBand.getDescription();
}
}
//copied from TimeSeriesManagerForm
private ProductSceneViewTopComponent getProductSceneViewTopComponent(RasterDataNode raster) {
return WindowUtilities.getOpened(ProductSceneViewTopComponent.class)
.filter(topComponent -> raster == topComponent.getView().getRaster())
.findFirst()
.orElse(null);
}
private boolean isComputedBand(ProductNode selectedProductNode) {
return selectedProductNode instanceof VirtualBand || selectedProductNode instanceof FilterBand;
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new ConvertComputedBandIntoBandAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
}
} | 6,915 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractOverlayAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/layer/overlay/AbstractOverlayAction.java | package org.esa.snap.rcp.actions.layer.overlay;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.support.AbstractLayerListener;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.SelectionSupport;
import org.esa.snap.ui.product.ProductSceneView;
import org.netbeans.api.annotations.common.NullAllowed;
import org.openide.util.actions.Presenter;
import javax.swing.AbstractAction;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenuItem;
import javax.swing.JToggleButton;
import java.awt.Component;
import java.awt.event.ActionEvent;
/**
* Monitor the state of overlays to either be enable or disable.
*
* @author Muhammad.bc
* @author Marco Peters
* @author Norman Fomferra
*/
public abstract class AbstractOverlayAction extends AbstractAction
implements Presenter.Toolbar, Presenter.Menu, Presenter.Popup, SelectionSupport.Handler<ProductSceneView>{
private final AbstractLayerListener layerListener = new AbstractLayerListener() {
@Override
public void handleLayersAdded(Layer parentLayer, Layer[] childLayers) {
updateActionState();
}
@Override
public void handleLayersRemoved(Layer parentLayer, Layer[] childLayers) {
updateActionState();
}
};
protected AbstractOverlayAction() {
SnapApp.getDefault().getSelectionSupport(ProductSceneView.class).addHandler(this);
initActionProperties();
updateActionState();
}
protected void updateActionState() {
ProductSceneView view = getSelectedProductSceneView();
if (view != null) {
setEnabled(getActionEnabledState(view));
setSelected(getActionSelectionState(view));
} else {
setEnabled(false);
setSelected(false);
}
}
@Override
public void selectionChange(@NullAllowed ProductSceneView oldValue, @NullAllowed ProductSceneView newValue) {
if (oldValue != null) {
oldValue.getRootLayer().removeListener(layerListener);
}
if (newValue != null) {
newValue.getRootLayer().addListener(layerListener);
}
updateActionState();
}
@Override
public void actionPerformed(ActionEvent e) {
setOverlayEnableState(getSelectedProductSceneView());
updateActionState();
}
@Override
public JMenuItem getMenuPresenter() {
JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(this);
menuItem.setIcon(null);
return menuItem;
}
@Override
public JMenuItem getPopupPresenter() {
return getMenuPresenter();
}
@Override
public Component getToolbarPresenter() {
JToggleButton toggleButton = new JToggleButton(this);
toggleButton.setText(null);
return toggleButton;
}
protected abstract void initActionProperties();
/**
* Compute the state of a ProductSceneView that is selected.
*
* @param view // get the selected productSceneView
* @return // return the state of the Overlay within the ProductSceneView
*/
protected abstract boolean getActionSelectionState(ProductSceneView view);
protected abstract boolean getActionEnabledState(ProductSceneView view);
protected abstract void setOverlayEnableState(ProductSceneView view);
protected ProductSceneView getSelectedProductSceneView() {
return SnapApp.getDefault().getSelectedProductSceneView();
}
protected boolean isSelected() {
return Boolean.TRUE.equals(getValue(SELECTED_KEY));
}
private void setSelected(boolean selected) {
putValue(SELECTED_KEY, selected);
}
}
| 3,691 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OverlayPinLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/layer/overlay/OverlayPinLayerAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.layer.overlay;
import org.esa.snap.core.datamodel.Product;
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.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
/**
* @author Marco Peters
* @author Muhammad.bc
*/
@ActionID(category = "View", id = "OverlayPinLayerAction")
@ActionRegistration(displayName = "#CTL_OverlayPinLayerActionName")
@ActionReferences({
@ActionReference(path = "Menu/Layer", position = 30),
@ActionReference(path = "Toolbars/Overlay", position = 30)
})
@NbBundle.Messages({
"CTL_OverlayPinLayerActionName=Pin Overlay",
"CTL_OverlayPinLayerActionToolTip=Show/hide pin overlay for the selected image"
})
public final class OverlayPinLayerAction extends AbstractOverlayAction {
@Override
protected void initActionProperties() {
putValue(NAME, Bundle.CTL_OverlayPinLayerActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/PinOverlay.gif", false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/PinOverlay24.gif", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayPinLayerActionToolTip());
}
@Override
protected boolean getActionSelectionState(ProductSceneView view) {
return view.isPinOverlayEnabled();
}
@Override
protected boolean getActionEnabledState(ProductSceneView view) {
final Product product = view.getProduct();
return product != null && product.getPinGroup().getNodeCount() > 0;
}
@Override
protected void setOverlayEnableState(ProductSceneView view) {
view.setPinOverlayEnabled(!getActionSelectionState(view));
}
}
| 2,073 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OverlayGeometryLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/layer/overlay/OverlayGeometryLayerAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.layer.overlay;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerFilter;
import com.bc.ceres.glayer.support.LayerUtils;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.VectorDataLayerFilterFactory;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
import java.util.List;
/**
* @author Marco Peters
* @author Norman Fomferra
* @author Muhammad.bc
*/
@ActionID(category = "View", id = "OverlayGeometryLayerAction")
@ActionRegistration(displayName = "#CTL_OverlayGeometryLayerActionName")
@ActionReferences({
@ActionReference(path = "Menu/Layer", position = 10),
@ActionReference(path = "Toolbars/Overlay", position = 10),
})
@NbBundle.Messages({
"CTL_OverlayGeometryLayerActionName=Geometry Overlay",
"CTL_OverlayGeometryLayerActionToolTip=Show/hide geometry overlay for the selected image"
})
public final class OverlayGeometryLayerAction extends AbstractOverlayAction {
private final LayerFilter geometryFilter = VectorDataLayerFilterFactory.createGeometryFilter();
@Override
protected void initActionProperties() {
putValue(NAME, Bundle.CTL_OverlayGeometryLayerActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/ShapeOverlay.gif", false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/ShapeOverlay24.gif", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayGeometryLayerActionToolTip());
}
@Override
protected boolean getActionSelectionState(ProductSceneView view) {
List<Layer> childLayers = getGeometryLayers(view);
return childLayers.stream().filter(Layer::isVisible).findAny().isPresent();
}
@Override
protected boolean getActionEnabledState(ProductSceneView view) {
List<Layer> childLayers = getGeometryLayers(view);
return !childLayers.isEmpty();
}
@Override
protected void setOverlayEnableState(ProductSceneView view) {
if (view != null) {
List<Layer> childLayers = getGeometryLayers(view);
childLayers.stream().forEach(layer -> layer.setVisible(isSelected()));
}
}
private List<Layer> getGeometryLayers(ProductSceneView sceneView) {
return LayerUtils.getChildLayers(sceneView.getRootLayer(), LayerUtils.SEARCH_DEEP, geometryFilter);
}
}
| 2,789 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OverlayNoDataLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/layer/overlay/OverlayNoDataLayerAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.layer.overlay;
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.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
/**
* @author Marco Peters
* @author Muhammad.bc
*/
@ActionID(category = "View", id = "OverlayNoDataLayerAction")
@ActionRegistration(displayName = "#CTL_OverlayNoDataLayerActionName")
@ActionReferences({
@ActionReference(path = "Menu/Layer", position = 0),
@ActionReference(path = "Toolbars/Overlay", position = 0)
})
@NbBundle.Messages({
"CTL_OverlayNoDataLayerActionName=No-Data Overlay",
"CTL_OverlayNoDataLayerActionToolTip=Show/hide no-data overlay for the selected image"
})
public final class OverlayNoDataLayerAction extends AbstractOverlayAction {
@Override
protected void initActionProperties() {
putValue(NAME, Bundle.CTL_OverlayNoDataLayerActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/NoDataOverlay.gif", false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/NoDataOverlay24.gif", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayNoDataLayerActionToolTip());
}
@Override
protected boolean getActionSelectionState(ProductSceneView view) {
return view.isNoDataOverlayEnabled();
}
@Override
protected boolean getActionEnabledState(ProductSceneView view) {
return view.getRaster().isValidMaskUsed();
}
@Override
protected void setOverlayEnableState(ProductSceneView view) {
view.setNoDataOverlayEnabled(!getActionSelectionState(view));
}
}
| 1,990 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OverlayGcpLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/layer/overlay/OverlayGcpLayerAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.layer.overlay;
import org.esa.snap.core.datamodel.Product;
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.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
/**
* @author Marco Peters
*/
@ActionID(category = "View", id = "OverlayGcpLayerAction")
@ActionRegistration(displayName = "#CTL_OverlayGcpLayerActionName")
@ActionReferences({
@ActionReference(path = "Menu/Layer", position = 40),
@ActionReference(path = "Toolbars/Overlay", position = 40)
})
@NbBundle.Messages({
"CTL_OverlayGcpLayerActionName=GCP Overlay",
"CTL_OverlayGcpLayerActionToolTip=Show/hide GCP overlay for the selected image"
})
public final class OverlayGcpLayerAction extends AbstractOverlayAction {
@Override
protected void initActionProperties() {
putValue(NAME, Bundle.CTL_OverlayGcpLayerActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/GcpOverlay.gif", false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/GcpOverlay24.gif", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayGcpLayerActionToolTip());
}
@Override
protected boolean getActionSelectionState(ProductSceneView view) {
return view.isGcpOverlayEnabled();
}
@Override
protected boolean getActionEnabledState(ProductSceneView view) {
Product product = view.getProduct();
return product != null && product.getGcpGroup().getNodeCount() > 0;
}
@Override
protected void setOverlayEnableState(ProductSceneView view) {
view.setGcpOverlayEnabled(!getActionSelectionState(view));
}
}
| 2,041 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OverlayGraticuleLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/layer/overlay/OverlayGraticuleLayerAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.layer.overlay;
import org.esa.snap.core.util.ProductUtils;
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.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
/**
* @author Marco Peters
* @author Muhammad.bc
*/
@ActionID(category = "View", id = "OverlayGraticuleLayerAction")
@ActionRegistration(displayName = "#CTL_OverlayGraticuleLayerActionName")
@ActionReferences({
@ActionReference(path = "Menu/Layer", position = 20),
@ActionReference(path = "Toolbars/Overlay", position = 20)
})
@NbBundle.Messages({
"CTL_OverlayGraticuleLayerActionName=Graticule Overlay",
"CTL_OverlayGraticuleLayerActionToolTip=Show/hide graticule overlay for the selected image"
})
public final class OverlayGraticuleLayerAction extends AbstractOverlayAction {
@Override
protected void initActionProperties() {
putValue(NAME, Bundle.CTL_OverlayGraticuleLayerActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/GraticuleOverlay.gif", false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/GraticuleOverlay24.gif", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayGraticuleLayerActionToolTip());
}
@Override
protected boolean getActionSelectionState(ProductSceneView view) {
return view.isGraticuleOverlayEnabled();
}
@Override
protected boolean getActionEnabledState(ProductSceneView view) {
return ProductUtils.canGetPixelPos(view.getRaster());
}
@Override
protected void setOverlayEnableState(ProductSceneView view) {
view.setGraticuleOverlayEnabled(!getActionSelectionState(view));
}
}
| 2,085 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OverlayWorldMapLayerAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/layer/overlay/OverlayWorldMapLayerAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.layer.overlay;
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 com.bc.ceres.glayer.support.LayerUtils;
import org.esa.snap.core.datamodel.CrsGeoCoding;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.MapGeoCoding;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.dataop.maptransf.IdentityTransformDescriptor;
import org.esa.snap.core.dataop.maptransf.MapTransformDescriptor;
import org.esa.snap.core.layer.WorldMapLayerType;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.product.ProductSceneView;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ImageUtilities;
import org.openide.util.NbBundle;
/**
* @author Marco Peters
* @author Muhammad.bc
*/
@ActionID(category = "View", id = "OverlayWorldMapLayerAction")
@ActionRegistration(displayName = "#CTL_OverlayWorldMapLayerActionName")
@ActionReferences({
@ActionReference(path = "Menu/Layer", position = 50),
@ActionReference(path = "Toolbars/Overlay", position = 50)
})
@NbBundle.Messages({
"CTL_OverlayWorldMapLayerActionName=World Map Overlay",
"CTL_OverlayWorldMapLayerActionToolTip=Show/hide world map overlay for the selected image"
})
public final class OverlayWorldMapLayerAction extends AbstractOverlayAction {
private static final String WORLDMAP_TYPE_PROPERTY_NAME = "worldmap.type";
private static final String DEFAULT_LAYER_TYPE = "BlueMarbleLayerType";
@Override
protected void initActionProperties() {
putValue(NAME, Bundle.CTL_OverlayWorldMapLayerActionName());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/WorldMapOverlay.png", false));
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/WorldMapOverlay24.png", false));
putValue(SHORT_DESCRIPTION, Bundle.CTL_OverlayWorldMapLayerActionToolTip());
}
@Override
protected boolean getActionSelectionState(ProductSceneView view) {
Layer worldMapLayer = findWorldMapLayer(view);
return worldMapLayer != null && worldMapLayer.isVisible();
}
@Override
protected boolean getActionEnabledState(ProductSceneView view) {
RasterDataNode raster = view.getRaster();
return isGeographicLatLon(raster.getGeoCoding());
}
@Override
protected void setOverlayEnableState(ProductSceneView view) {
if (view != null) {
Layer rootLayer = view.getRootLayer();
Layer worldMapLayer = findWorldMapLayer(view);
if (isSelected()) {
if (worldMapLayer == null) {
worldMapLayer = createWorldMapLayer();
rootLayer.getChildren().add(worldMapLayer);
}
worldMapLayer.setVisible(true);
} else {
worldMapLayer.getParent().getChildren().remove(worldMapLayer);
}
}
}
private Layer createWorldMapLayer() {
final LayerType layerType = getWorldMapLayerType();
final PropertySet template = layerType.createLayerConfig(null);
return layerType.createLayer(null, template);
}
private LayerType getWorldMapLayerType() {
final SnapApp visatApp = SnapApp.getDefault();
String layerTypeClassName = visatApp.getPreferences().get(WORLDMAP_TYPE_PROPERTY_NAME, DEFAULT_LAYER_TYPE);
return LayerTypeRegistry.getLayerType(layerTypeClassName);
}
private Layer findWorldMapLayer(ProductSceneView view) {
return LayerUtils.getChildLayer(view.getRootLayer(), LayerUtils.SearchMode.DEEP, layer -> layer.getLayerType() instanceof WorldMapLayerType);
}
private boolean isGeographicLatLon(GeoCoding geoCoding) {
if (geoCoding instanceof MapGeoCoding) {
MapGeoCoding mapGeoCoding = (MapGeoCoding) geoCoding;
MapTransformDescriptor transformDescriptor = mapGeoCoding.getMapInfo()
.getMapProjection().getMapTransform().getDescriptor();
String typeID = transformDescriptor.getTypeID();
if (typeID.equals(IdentityTransformDescriptor.TYPE_ID)) {
return true;
}
} else if (geoCoding instanceof CrsGeoCoding) {
return CRS.equalsIgnoreMetadata(geoCoding.getMapCRS(), DefaultGeographicCRS.WGS84);
}
return false;
}
}
| 4,924 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CloseProductAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/CloseProductAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.file;
import eu.esa.snap.netbeans.docwin.DocumentWindow;
import eu.esa.snap.netbeans.docwin.DocumentWindowManager;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.core.dataio.ProductReader;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* Action which closes a selected product.
*
* @author Norman
*/
@ActionID(
category = "File",
id = "CloseProductAction"
)
@ActionRegistration(
displayName = "#CTL_CloseProductActionName", lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File", position = 20, separatorBefore = 18),
@ActionReference(path = "Context/Product/Product", position = 60)
})
@NbBundle.Messages({
"CTL_CloseProductActionName=Close Product"
})
public final class CloseProductAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final WeakSet<Product> productSet = new WeakSet<>();
private Lookup lkp;
public CloseProductAction() {
this(Utilities.actionsGlobalContext());
}
public CloseProductAction(Lookup actionContext) {
super(Bundle.CTL_CloseProductActionName());
this.lkp = actionContext;
Lookup.Result<ProductNode> productNode = lkp.lookupResult(ProductNode.class);
productNode.addLookupListener(WeakListeners.create(LookupListener.class, this, productNode));
setEnableState();
setActionName();
}
public CloseProductAction(List<Product> products) {
productSet.addAll(products);
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new CloseProductAction(actionContext);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnableState();
setActionName();
}
private Set<Product> getSelectedProducts() {
Collection<? extends ProductNode> selectedNodes = lkp.lookupAll(ProductNode.class);
return selectedNodes.stream().map(ProductNode::getProduct).collect(Collectors.toSet());
}
private void setActionName() {
Set<Product> selectedProducts = getSelectedProducts();
if (selectedProducts.size() > 1) {
this.putValue(Action.NAME, String.format("Close %d Products", selectedProducts.size()));
} else {
this.putValue(Action.NAME, "Close Product");
}
}
@Override
public void actionPerformed(ActionEvent e) {
execute();
}
private void setEnableState() {
setEnabled(lkp.lookup(ProductNode.class) != null);
}
/**
* Executes the action command.
*
* @return {@code Boolean.TRUE} on success, {@code Boolean.FALSE} on failure, or {@code null} on cancellation.
*/
public Boolean execute() {
Boolean status;
if (!productSet.isEmpty()) {
// Case 1: If productSet is not empty, action has been constructed with selected products
status = closeProducts(productSet);
productSet.clear();
} else {
// Case 2: If productSet is empty, default constructor has been called
status = closeProducts(getSelectedProducts());
}
return status;
}
public static Boolean closeProducts(Set<Product> products) {
List<Product> closeList = new ArrayList<>(products);
List<Product> saveList = new ArrayList<>();
HashSet<Product> stillOpenProducts = new HashSet<>(Arrays.asList(SnapApp.getDefault().getProductManager().getProducts()));
stillOpenProducts.removeAll(closeList);
if (!stillOpenProducts.isEmpty()) {
for (Product productToBeClosed : closeList) {
Product firstSourceProduct = findFirstSourceProduct(productToBeClosed, stillOpenProducts);
if (firstSourceProduct != null) {
Dialogs.showInformation("Close Not Possible",
String.format("Can't close product '%s' because it is in use%n" +
"by product '%s'.%n" +
"Please close the latter first.",
productToBeClosed.getName(),
firstSourceProduct.getName()), null);
return false;
}
}
}
for (Product product : products) {
if (product.isModified()) {
Dialogs.Answer answer = Dialogs.requestDecision(Bundle.CTL_OpenProductActionName(),
MessageFormat.format("Product ''{0}'' has been modified.\n" +
"Do you want to save it?",
product.getName()), true, null);
if (answer == Dialogs.Answer.YES) {
saveList.add(product);
} else if (answer == Dialogs.Answer.CANCELLED) {
return null;
}
}
}
for (Product product : saveList) {
Boolean status = new SaveProductAction(product).execute();
if (status == null) {
// cancelled
return null;
}
}
for (Product product : closeList) {
WindowUtilities.getOpened(DocumentWindow.class)
.filter(dw -> (dw.getDocument() instanceof ProductNode) && ((ProductNode) dw.getDocument()).getProduct() == product)
.forEach(dw -> DocumentWindowManager.getDefault().closeWindow(dw));
SnapApp.getDefault().getProductManager().removeProduct(product);
}
closeList.forEach(Product::dispose);
return true;
}
static Product findFirstSourceProduct(Product productToClose, Set<Product> productsStillOpen) {
Product firstSourceProduct = findFirstDirectSourceProduct(productToClose, productsStillOpen);
if (firstSourceProduct != null) {
return firstSourceProduct;
}
return findFirstExpressionSourceProduct(productToClose, productsStillOpen);
}
private static Product findFirstDirectSourceProduct(Product productToBeClosed, Set<Product> productsStillOpen) {
for (Product openProduct : productsStillOpen) {
final ProductReader reader = openProduct.getProductReader();
if (reader != null) {
final Object input = reader.getInput();
if (input instanceof Product) {
Product sourceProduct = (Product) input;
if (productToBeClosed.equals(sourceProduct)) {
return openProduct;
} else {
Product indirectSourceProduct = findFirstDirectSourceProduct(sourceProduct, productsStillOpen);
if (indirectSourceProduct != null && productToBeClosed.equals(indirectSourceProduct)) {
return openProduct;
}
}
} else {
if (input instanceof Product[]) {
for (final Product sourceProduct : (Product[]) input) {
if (productToBeClosed.equals(sourceProduct)) {
return openProduct;
}
Product indirectSourceProduct = findFirstDirectSourceProduct(sourceProduct, productsStillOpen);
if (indirectSourceProduct != null && productToBeClosed.equals(indirectSourceProduct)) {
return openProduct;
}
}
}
}
}
}
return null;
}
static Product findFirstExpressionSourceProduct(Product productToBeClosed, Set<Product> productsStillOpen) {
for (Product openProduct : productsStillOpen) {
Band[] bands = openProduct.getBands();
for (Band band : bands) {
if (band instanceof VirtualBand) {
VirtualBand virtualBand = (VirtualBand) band;
try {
RasterDataNode[] nodes = openProduct.getRefRasterDataNodes(virtualBand.getExpression());
for (RasterDataNode node : nodes) {
if (productToBeClosed.equals(node.getProduct())) {
return openProduct;
}
}
} catch (ParseException e) {
// ok
}
}
}
}
return null;
}
}
| 9,358 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReadProductOperation.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ReadProductOperation.java | package org.esa.snap.rcp.actions.file;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.dataio.ProductSubsetDef;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.netbeans.api.progress.ProgressHandle;
import org.openide.util.Cancellable;
import org.openide.util.RequestProcessor;
import javax.swing.SwingUtilities;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
class ReadProductOperation implements Runnable {
private static final Logger logger = Logger.getLogger(ReadProductOperation.class.getName());
private final File file;
private final String formatName;
private ProgressWrapper ph;
private ProductSubsetDef productSubsetDef = null;
private ProductReaderPlugIn plugin = null;
public ReadProductOperation(File file, String formatName) {
Assert.notNull(file, "file");
Assert.notNull(formatName, "formatName");
this.file = file;
this.formatName = formatName;
ph = PhWrapper.NULL;
}
public File getFile() {
return file;
}
public String getFormatName() {
return formatName;
}
public Cancellable createCancellable(RequestProcessor.Task task) {
return new Cancel(this, task);
}
public void attacheProgressHandle(ProgressHandle handle) {
ph = new PhWrapper(handle);
}
@Override
public void run() {
try {
ph.start();
ph.switchToIndeterminate();
Product product;
if(productSubsetDef==null) {
product = ProductIO.readProduct(file, formatName);
}else{
product = plugin.createReaderInstance().readProductNodes(file,productSubsetDef);
}
boolean interrupted = Thread.interrupted();
if (!interrupted) {
if (product == null) {
SwingUtilities.invokeLater(
() -> Dialogs.showError(Bundle.LBL_NoReaderFoundText() + String.format("%nFile '%s' can not be opened.", file)));
} else {
OpenProductAction.getRecentProductPaths().add(file.getPath());
SwingUtilities.invokeLater(() -> SnapApp.getDefault().getProductManager().addProduct(product));
}
}
} catch (IOException problem) {
logger.log(Level.SEVERE, "Failed to read the product.", problem);
SwingUtilities.invokeLater(() -> Dialogs.showError(Bundle.CTL_OpenProductActionName(), problem.getMessage()));
} finally {
ph.finish();
}
}
static class Cancel implements Cancellable {
private final ReadProductOperation operation;
private final RequestProcessor.Task task;
public Cancel(ReadProductOperation operation, RequestProcessor.Task task) {
this.operation = operation;
this.task = task;
}
@Override
public boolean cancel() {
task.cancel();
operation.ph.finish();
return true;
}
}
private static abstract class ProgressWrapper {
void start() {
}
void switchToIndeterminate() {
}
void finish() {
}
}
private static class PhWrapper extends ProgressWrapper {
public static ProgressWrapper NULL = new ProgressWrapper() {};
private final ProgressHandle handle;
public PhWrapper(ProgressHandle handle) {
this.handle = handle;
}
@Override
void start() {
handle.start();
}
@Override
void switchToIndeterminate() {
handle.switchToIndeterminate();
}
@Override
void finish() {
handle.finish();
}
}
public void setProductSubsetDef(ProductSubsetDef productSubsetDef) {
this.productSubsetDef = productSubsetDef;
}
public void setProductReaderPlugIn(ProductReaderPlugIn plugin) {
this.plugin = plugin;
}
}
| 4,268 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RecentPaths.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/RecentPaths.java | package org.esa.snap.rcp.actions.file;
import org.esa.snap.vfs.NioPaths;
import java.io.File;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.prefs.BackingStoreException;
import java.util.prefs.Preferences;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Maintains a list of unique, existing file paths in a preferences store.
*
* @author Norman Fomferra
*/
class RecentPaths {
private final Preferences preferences;
private final String key;
private final boolean filterExisting;
public RecentPaths(Preferences preferences, String key, boolean filterExisting) {
this.preferences = preferences;
this.key = key;
this.filterExisting = filterExisting;
}
public List<String> get() {
return getAsStream().collect(Collectors.toList());
}
public void add(String path) {
if (path.isEmpty() || !isPathValid(path)) {
return;
}
String value = Stream
.concat(Stream.of(path), getAsStream().filter(p -> !p.equals(path)))
.collect(Collectors.joining(File.pathSeparator));
preferences.put(key, value);
flush();
}
private boolean isPathValid(String path) {
try {
Paths.get(path);
} catch (InvalidPathException e) {
return false;
}
return true;
}
public void clear() {
preferences.remove(key);
flush();
}
private Stream<String> getAsStream() {
String value = preferences.get(key, null);
if (value == null) {
return Stream.empty();
}
return Arrays
.stream(value.split(File.pathSeparator))
.map(this::convertToPath)
.filter(Objects::nonNull)
.map(Path::toString);
}
private Path convertToPath(String pathAsString) {
try {
return NioPaths.get(pathAsString);
} catch (java.nio.file.InvalidPathException e) {
return null;
}
}
private void flush() {
try {
preferences.flush();
} catch (BackingStoreException e) {
// ignored, may log later
}
}
}
| 2,373 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CloseOtherProductsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/CloseOtherProductsAction.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/
*/
package org.esa.snap.rcp.actions.file;
import java.awt.event.ActionEvent;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import javax.swing.AbstractAction;
import javax.swing.Action;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.rcp.SnapApp;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
/**
* This action closes all opened products other than the one selected.
*/
@ActionID(category = "File", id = "CloseOtherProductsAction")
@ActionRegistration(displayName = "#CTL_CloseAllOthersActionName", lazy = false)
@ActionReferences({
@ActionReference(path = "Menu/File", position = 30),
@ActionReference(path = "Context/Product/Product", position = 80, separatorAfter = 85),
})
@NbBundle.Messages({"CTL_CloseAllOthersActionName=Close Other Products"})
public class CloseOtherProductsAction extends AbstractAction implements ContextAwareAction, LookupListener {
private final Lookup lkp;
private Product[] products;
private static Collection selectedProductList;
public CloseOtherProductsAction() {
this(Utilities.actionsGlobalContext());
}
public CloseOtherProductsAction(Lookup lkp) {
super(Bundle.CTL_CloseAllOthersActionName());
this.lkp = lkp;
Lookup.Result<ProductNode> lkpContext = lkp.lookupResult(ProductNode.class);
lkpContext.addLookupListener(WeakListeners.create(LookupListener.class, this, lkpContext));
ProductManager productManager = SnapApp.getDefault().getProductManager();
productManager.addListener(new CloseOtherProductListener());
setEnableState();
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new CloseOtherProductsAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
setEnableState();
Lookup.Result result = (Lookup.Result) ev.getSource();
selectedProductList = result.allInstances();
}
private void setEnableState() {
products = SnapApp.getDefault().getProductManager().getProducts();
ProductNode productNode = lkp.lookup(ProductNode.class);
setEnabled(productNode != null && products.length > 1);
}
@Override
public void actionPerformed(final ActionEvent event) {
final ProductNode productNode = lkp.lookup(ProductNode.class);
products = SnapApp.getDefault().getProductManager().getProducts();
// final Product selectedProduct = productNode.getProduct();
List<Product> selectedProduct = (List<Product>) selectedProductList.stream().collect(Collectors.toList());
final Set<Product> productsToClose = new HashSet<>();
for (Product product : products) {
if (!selectedProduct.contains(product)) {
productsToClose.add(product);
}
}
CloseProductAction.closeProducts(productsToClose);
setEnableState();
}
private class CloseOtherProductListener implements ProductManager.Listener {
@Override
public void productAdded(ProductManager.Event event) {
updateEnableState();
}
@Override
public void productRemoved(ProductManager.Event event) {
updateEnableState();
}
private void updateEnableState() {
setEnableState();
}
}
}
| 4,637 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductAdvancedDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ProductAdvancedDialog.java | package org.esa.snap.rcp.actions.file;
import org.esa.snap.core.dataio.ProductSubsetDef;
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.metadata.MetadataInspector;
import org.esa.snap.core.subset.AbstractSubsetRegion;
import org.esa.snap.core.subset.GeometrySubsetRegion;
import org.esa.snap.core.subset.PixelSubsetRegion;
import org.esa.snap.core.util.GeoUtils;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.ui.loading.AbstractModalDialog;
import org.esa.snap.ui.loading.LoadingIndicator;
import org.esa.snap.ui.loading.SwingUtils;
import org.locationtech.jts.geom.Geometry;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* Created by jcoravu on 17/2/2020.
* Updated by Denisa Stefanescu on 18/02/2020
* Updated by Oana H. on 18/03/2020 in order to replace the deprecated Parameter API
*/
public class ProductAdvancedDialog extends AbstractModalDialog {
private static final int MIN_SCENE_VALUE = 0;
private final JList bandList;
private final JList maskList;
private JCheckBox copyMetadata;
private final JCheckBox copyMasks;
private final JRadioButton pixelCoordRadio;
private final JRadioButton geoCoordRadio;
private final JPanel pixelPanel;
private final JPanel geoPanel;
private JScrollPane scrollPaneMask;
private MetadataInspector.Metadata readerInspectorExposeParameters;
private AtomicBoolean updatingUI;
private int productWidth;
private int productHeight;
private JSpinner pixelCoordXSpinner;
private JSpinner pixelCoordYSpinner;
private JSpinner pixelCoordWidthSpinner;
private JSpinner pixelCoordHeightSpinner;
private JSpinner geoCoordWestLongSpinner;
private JSpinner geoCoordEastLongSpinner;
private JSpinner geoCoordNorthLatSpinner;
private JSpinner geoCoordSouthLatSpinner;
private MetadataInspector metadataInspector;
private File file;
private ProductSubsetDef productSubsetDef;
public ProductAdvancedDialog(Window parent, String title, MetadataInspector metadataInspector, File file) {
super(parent, title, true, null);
updatingUI = new AtomicBoolean(false);
this.metadataInspector = metadataInspector;
this.file = file;
bandList = new JList();
maskList = new JList();
copyMetadata = new JCheckBox("Copy Metadata", true);
copyMasks = new JCheckBox("Copy Masks", true);
pixelCoordRadio = new JRadioButton("Pixel Coordinates");
geoCoordRadio = new JRadioButton("Geographic Coordinates");
pixelPanel = new JPanel(new GridBagLayout());
geoPanel = new JPanel(new GridBagLayout());
}
@Override
protected void onAboutToShow() {
readProductMetadataAsync();
}
@Override
protected JPanel buildButtonsPanel(ActionListener cancelActionListener) {
ActionListener okActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
okButtonPressed();
}
};
return buildButtonsPanel("Ok", okActionListener, "Cancel", cancelActionListener);
}
@Override
protected JPanel buildContentPanel(int gapBetweenColumns, int gapBetweenRows) {
initPixelCoordUIComponents();
initGeoCoordUIComponents();
copyMasks.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (copyMasks.isSelected()) {
if (!scrollPaneMask.isVisible()) {
scrollPaneMask.setVisible(true);
}
} else {
if (scrollPaneMask.isVisible()) {
maskList.clearSelection();
scrollPaneMask.setVisible(false);
}
}
}
});
scrollPaneMask = new JScrollPane(maskList);
createPixelPanel(gapBetweenColumns, gapBetweenRows);
createGeoCodingPanel(gapBetweenColumns, gapBetweenRows);
pixelCoordRadio.setSelected(true);
pixelCoordRadio.setActionCommand("pixelCoordRadio");
geoCoordRadio.setActionCommand("geoCoordRadio");
ButtonGroup group = new ButtonGroup();
group.add(pixelCoordRadio);
group.add(geoCoordRadio);
pixelCoordRadio.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pixelPanel.setVisible(true);
geoPanel.setVisible(false);
}
});
geoCoordRadio.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
pixelPanel.setVisible(false);
geoPanel.setVisible(true);
}
});
JPanel contentPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, 0, 0);
contentPanel.add(new JLabel("Source Bands:"), gbc);
gbc = SwingUtils.buildConstraints(1, 0, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 1, 1, 0, gapBetweenColumns);
contentPanel.add(new JScrollPane(bandList), gbc);
gbc = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, 0);
contentPanel.add(copyMetadata, gbc);
gbc = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, 0);
contentPanel.add(copyMasks, gbc);
gbc = SwingUtils.buildConstraints(1, 2, GridBagConstraints.BOTH, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows, gapBetweenColumns);
contentPanel.add(scrollPaneMask, gbc);
JPanel regionTypePanel = new JPanel(new GridLayout(1, 2));
regionTypePanel.add(pixelCoordRadio);
regionTypePanel.add(geoCoordRadio);
gbc = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST, 2, 1, gapBetweenRows, 0);
contentPanel.add(regionTypePanel, gbc);
gbc = SwingUtils.buildConstraints(0, 4, GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST, 2, 1, gapBetweenRows, 0);
contentPanel.add(pixelPanel, gbc);
gbc = SwingUtils.buildConstraints(0, 5, GridBagConstraints.HORIZONTAL, GridBagConstraints.NORTHWEST, 2, 1, gapBetweenRows, 0);
contentPanel.add(geoPanel, gbc);
geoPanel.setVisible(false);
return contentPanel;
}
private void createPixelPanel(int gapBetweenColumns, int gapBetweenRows) {
GridBagConstraints pixgbc = SwingUtils.buildConstraints(0, 0, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 1, 1, 0, 0);
pixelPanel.add(new JLabel("SceneX:"), pixgbc);
pixgbc = SwingUtils.buildConstraints(1, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, 0, gapBetweenColumns);
pixelPanel.add(pixelCoordXSpinner, pixgbc);
pixgbc = SwingUtils.buildConstraints(0, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0);
pixelPanel.add(new JLabel("SceneY:"), pixgbc);
pixgbc = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns);
pixelPanel.add(pixelCoordYSpinner, pixgbc);
pixgbc = SwingUtils.buildConstraints(0, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0);
pixelPanel.add(new JLabel("Scene width:"), pixgbc);
pixgbc = SwingUtils.buildConstraints(1, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns);
pixelPanel.add(pixelCoordWidthSpinner, pixgbc);
pixgbc = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0);
pixelPanel.add(new JLabel("Scene height:"), pixgbc);
pixgbc = SwingUtils.buildConstraints(1, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns);
pixelPanel.add(pixelCoordHeightSpinner, pixgbc);
}
private void createGeoCodingPanel(int gapBetweenColumns, int gapBetweenRows) {
GridBagConstraints geobc = SwingUtils.buildConstraints(0, 0, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 1, 1, 0, 0);
geoPanel.add(new JLabel("North latitude bound:"), geobc);
geobc = SwingUtils.buildConstraints(1, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, 0, gapBetweenColumns);
geoPanel.add(geoCoordNorthLatSpinner, geobc);
geobc = SwingUtils.buildConstraints(0, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0);
geoPanel.add(new JLabel("West longitude bound:"), geobc);
geobc = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns);
geoPanel.add(geoCoordWestLongSpinner, geobc);
geobc = SwingUtils.buildConstraints(0, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0);
geoPanel.add(new JLabel("South latitude bound:"), geobc);
geobc = SwingUtils.buildConstraints(1, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns);
geoPanel.add(geoCoordSouthLatSpinner, geobc);
geobc = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0);
geoPanel.add(new JLabel("East longitude bound:"), geobc);
geobc = SwingUtils.buildConstraints(1, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns);
geoPanel.add(geoCoordEastLongSpinner, geobc);
}
/**
* Creates the UI components for the Pixel Coordinates panel
*/
private void initPixelCoordUIComponents(){
pixelCoordXSpinner = new JSpinner(new SpinnerNumberModel(0,0, Integer.MAX_VALUE, 25));
pixelCoordXSpinner.getModel().setValue(MIN_SCENE_VALUE);
pixelCoordXSpinner.setToolTipText("Start X co-ordinate given in pixels");
pixelCoordXSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStatePixelCoordsChanged(event);
}
});
pixelCoordYSpinner = new JSpinner(new SpinnerNumberModel(0,0, Integer.MAX_VALUE, 25));
pixelCoordYSpinner.getModel().setValue(MIN_SCENE_VALUE);
pixelCoordYSpinner.setToolTipText("Start Y co-ordinate given in pixels");
pixelCoordYSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStatePixelCoordsChanged(event);
}
});
pixelCoordWidthSpinner = new JSpinner(new SpinnerNumberModel(0,0, Integer.MAX_VALUE, 25));
pixelCoordWidthSpinner.getModel().setValue(Integer.MAX_VALUE);
pixelCoordWidthSpinner.setToolTipText("Product width");
pixelCoordWidthSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStatePixelCoordsChanged(event);
}
});
pixelCoordHeightSpinner = new JSpinner(new SpinnerNumberModel(0,0, Integer.MAX_VALUE, 25));
pixelCoordHeightSpinner.getModel().setValue(Integer.MAX_VALUE);
pixelCoordHeightSpinner.setToolTipText("Product height");
pixelCoordHeightSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStatePixelCoordsChanged(event);
}
});
}
/**
* Creates the UI components for the Geographical Coordinates panel
*/
private void initGeoCoordUIComponents(){
geoCoordNorthLatSpinner = new JSpinner(new SpinnerNumberModel(0.0,-90.0, 90.0, 1.0));
geoCoordNorthLatSpinner.getModel().setValue(90.0);
geoCoordNorthLatSpinner.setToolTipText("North bound latitude (°)");
geoCoordNorthLatSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStateGeoCoordsChanged(event);
}
});
geoCoordWestLongSpinner = new JSpinner(new SpinnerNumberModel(0.0,-180.0, 180.0, 1.0));
geoCoordWestLongSpinner.getModel().setValue(-180.0);
geoCoordWestLongSpinner.setToolTipText("West bound longitude (°)");
geoCoordWestLongSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStateGeoCoordsChanged(event);
}
});
geoCoordSouthLatSpinner = new JSpinner(new SpinnerNumberModel(0.0,-90.0, 90.0, 1.0));
geoCoordSouthLatSpinner.getModel().setValue(-90.0);
geoCoordSouthLatSpinner.setToolTipText("South bound latitude (°)");
geoCoordSouthLatSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStateGeoCoordsChanged(event);
}
});
geoCoordEastLongSpinner = new JSpinner(new SpinnerNumberModel(0.0,-180.0, 180.0, 1.0));
geoCoordEastLongSpinner.getModel().setValue(180.0);
geoCoordEastLongSpinner.setToolTipText("East bound longitude (°)");
geoCoordEastLongSpinner.addChangeListener(new ChangeListener() {
@Override
public void stateChanged(ChangeEvent event) {
updateUIStateGeoCoordsChanged(event);
}
});
}
private void okButtonPressed() {
createSubsetDef();
getJDialog().dispose();
}
private void readProductMetadataAsync() {
LoadingIndicator loadingIndicator = getLoadingIndicator();
int threadId = getNewCurrentThreadId();
ReadProductInspectorTimerRunnable runnable = new ReadProductInspectorTimerRunnable(loadingIndicator, threadId, metadataInspector, file.toPath()) {
@Override
protected void onSuccessfullyFinish(MetadataInspector.Metadata result) {
onSuccessfullyLoadingProductMetadata(result);
}
@Override
protected void onFailed(Exception exception) {
onFailedLoadingProductMetadata(exception);
}
};
runnable.executeAsync();
}
private void onSuccessfullyLoadingProductMetadata(MetadataInspector.Metadata result){
this.readerInspectorExposeParameters = result;
productWidth = result.getProductWidth();
productHeight = result.getProductHeight();
((SpinnerNumberModel)pixelCoordXSpinner.getModel()).setMaximum(result.getProductWidth() - 1 > 0 ? result.getProductWidth() - 1 : 0);
((SpinnerNumberModel)pixelCoordYSpinner.getModel()).setMaximum(result.getProductHeight() - 1 > 0 ? result.getProductHeight() - 1 : 0);
((SpinnerNumberModel)pixelCoordWidthSpinner.getModel()).setMinimum((Integer) pixelCoordXSpinner.getValue());
((SpinnerNumberModel)pixelCoordWidthSpinner.getModel()).setMaximum(result.getProductWidth());
pixelCoordWidthSpinner.setValue(result.getProductWidth());
((SpinnerNumberModel)pixelCoordHeightSpinner.getModel()).setMinimum((Integer) pixelCoordYSpinner.getValue());
((SpinnerNumberModel)pixelCoordHeightSpinner.getModel()).setMaximum(result.getProductHeight());
pixelCoordHeightSpinner.setValue(result.getProductHeight());
if(this.readerInspectorExposeParameters != null && this.readerInspectorExposeParameters.isHasGeoCoding()) {
syncLatLonWithXYParams();
}else{
geoCoordRadio.setEnabled(false);
geoPanel.setEnabled(false);
}
this.bandList.setListData(result.getBandList().toArray());
this.maskList.setListData(result.getMaskList().toArray());
if (!result.isHasMasks()) {
copyMasks.setSelected(false);
copyMasks.setEnabled(false);
scrollPaneMask.setEnabled(false);
}
}
private void onFailedLoadingProductMetadata(Exception exception) {
showErrorDialog("Failed to load the product metadata", "Loading metadata");
getJDialog().dispose();
}
private void updateUIStatePixelCoordsChanged(ChangeEvent event) {
if (updatingUI.compareAndSet(false, true)) {
try {
if (event != null && pixelCoordRadio.isEnabled()) {
pixelPanelChanged();
syncLatLonWithXYParams();
}
} finally {
updatingUI.set(false);
}
}
}
private void updateUIStateGeoCoordsChanged(ChangeEvent event) {
if (updatingUI.compareAndSet(false, true)) {
try {
if (event != null && geoCoordRadio.isEnabled()) {
geoCodingChange();
}
} finally {
updatingUI.set(false);
}
}
}
public void pixelPanelChanged() {
int x1 = ((Number) pixelCoordXSpinner.getValue()).intValue();
int y1 = ((Number) pixelCoordYSpinner.getValue()).intValue();
int w = ((Number) pixelCoordWidthSpinner.getValue()).intValue();
int h = ((Number) pixelCoordHeightSpinner.getValue()).intValue();
if (x1 < 0) {
x1 = 0;
}
if (x1 > productWidth - 2) {
x1 = productWidth - 2;
}
if (y1 < 0) {
y1 = 0;
}
if (y1 > productHeight - 2) {
y1 = productHeight - 2;
}
if (this.readerInspectorExposeParameters != null) {
if (w > productWidth) {
w = productWidth;
}
if (x1 + w > productWidth) {
if( (w - x1) >= 2) {
w = w - x1;
}
else {
w = productWidth - x1;
}
}
}
if (this.readerInspectorExposeParameters != null) {
if (h > productHeight) {
h = productHeight;
}
if (y1 + h > productHeight) {
if (h - y1 >= 2) {
h = h - y1;
}
else {
h = productHeight - y1;
}
}
}
//reset fields values when the user writes wrong values
pixelCoordXSpinner.setValue(0);
pixelCoordYSpinner.setValue(0);
pixelCoordWidthSpinner.setValue(w);
pixelCoordHeightSpinner.setValue(h);
pixelCoordXSpinner.setValue(x1);
pixelCoordYSpinner.setValue(y1);
pixelCoordWidthSpinner.setValue(w);
pixelCoordHeightSpinner.setValue(h);
}
private void geoCodingChange() {
final GeoPos geoPos1 = new GeoPos((Double) geoCoordNorthLatSpinner.getValue(),
(Double) geoCoordWestLongSpinner.getValue());
final GeoPos geoPos2 = new GeoPos((Double) geoCoordSouthLatSpinner.getValue(),
(Double) geoCoordEastLongSpinner.getValue());
updateXYParams(geoPos1, geoPos2);
}
private void updateXYParams(GeoPos geoPos1, GeoPos geoPos2) {
GeoCoding geoCoding;
if (this.readerInspectorExposeParameters != null && this.readerInspectorExposeParameters.getGeoCoding() != null) {
geoCoding = this.readerInspectorExposeParameters.getGeoCoding();
final PixelPos pixelPos1 = geoCoding.getPixelPos(geoPos1, null);
if (!pixelPos1.isValid()) {
pixelPos1.setLocation(0, 0);
}
final PixelPos pixelPos2 = geoCoding.getPixelPos(geoPos2, null);
if (!pixelPos2.isValid()) {
pixelPos2.setLocation(this.readerInspectorExposeParameters.getProductWidth(),
this.readerInspectorExposeParameters.getProductHeight());
}
final Rectangle.Float region = new Rectangle.Float();
region.setFrameFromDiagonal(pixelPos1.x, pixelPos1.y, pixelPos2.x, pixelPos2.y);
final Rectangle.Float productBounds;
productBounds = new Rectangle.Float(0, 0,
this.readerInspectorExposeParameters.getProductWidth(),
this.readerInspectorExposeParameters.getProductHeight());
Rectangle2D finalRegion = productBounds.createIntersection(region);
if(isValueInNumericSpinnerRange(pixelCoordXSpinner, (int) finalRegion.getMinX())){
pixelCoordXSpinner.setValue((int) finalRegion.getMinX());
}
if(isValueInNumericSpinnerRange(pixelCoordYSpinner, (int) finalRegion.getMinY())){
pixelCoordYSpinner.setValue((int) finalRegion.getMinY());
}
int width = (int)(finalRegion.getMaxX() - finalRegion.getMinX()) + 1;
int height = (int)(finalRegion.getMaxY() - finalRegion.getMinY()) + 1;
if(isValueInNumericSpinnerRange(pixelCoordWidthSpinner, width)){
pixelCoordWidthSpinner.setValue(width);
}
if(isValueInNumericSpinnerRange(pixelCoordHeightSpinner, height)){
pixelCoordHeightSpinner.setValue(height);
}
}
}
private void syncLatLonWithXYParams() {
if (this.readerInspectorExposeParameters != null && this.readerInspectorExposeParameters.getGeoCoding() != null) {
final PixelPos pixelPos1 = new PixelPos((Integer) pixelCoordXSpinner.getValue(), (Integer) pixelCoordYSpinner.getValue());
int paramX2 = (Integer)pixelCoordWidthSpinner.getValue() + (Integer)pixelCoordXSpinner.getValue() - 1;
int paramY2 = (Integer)pixelCoordHeightSpinner.getValue() + (Integer)pixelCoordYSpinner.getValue() - 1;
final PixelPos pixelPos2 = new PixelPos(paramX2, paramY2);
GeoCoding geoCoding = this.readerInspectorExposeParameters.getGeoCoding();
final GeoPos geoPos1 = geoCoding.getGeoPos(pixelPos1, null);
final GeoPos geoPos2 = geoCoding.getGeoPos(pixelPos2, null);
if (geoPos1.isValid()) {
double lat = geoPos1.getLat();
lat = MathUtils.crop(lat, -90.0, 90.0);
geoCoordNorthLatSpinner.setValue(lat);
double lon = geoPos1.getLon();
lon = MathUtils.crop(lon, -180.0, 180.0);
geoCoordWestLongSpinner.setValue(lon);
}
if (geoPos2.isValid()) {
double lat = geoPos2.getLat();
lat = MathUtils.crop(lat, -90.0, 90.0);
geoCoordSouthLatSpinner.setValue(lat);
double lon = geoPos2.getLon();
lon = MathUtils.crop(lon, -180.0, 180.0);
geoCoordEastLongSpinner.setValue(lon);
}
}
}
private boolean isValueInNumericSpinnerRange(JSpinner spinner, Integer value){
final Integer min = (Integer)((SpinnerNumberModel)spinner.getModel()).getMinimum();
final Integer max = (Integer)((SpinnerNumberModel)spinner.getModel()).getMaximum();
if (value >= min && value <= max){
return true;
}
return false;
}
public static JLabel addComponent(JPanel contentPane, GridBagConstraints gbc, String text, JComponent component, int pos) {
gbc.gridx = pos;
gbc.weightx = 0.5;
final JLabel label = new JLabel(text);
contentPane.add(label, gbc);
gbc.gridx = pos + 1;
gbc.weightx = 2.0;
contentPane.add(component, gbc);
gbc.gridx = pos;
gbc.weightx = 1.0;
return label;
}
private void createSubsetDef() {
if (pixelPanel.isVisible()) {
updateSubsetDefNodeNameList(false);
} else if (geoPanel.isVisible() && geoCoordRadio.isEnabled()) {
updateSubsetDefNodeNameList(true);
}
}
/**
* @param geoRegion if <code>true</code>, the geoCoding parameters will be send
*/
private void updateSubsetDefNodeNameList(boolean geoRegion) {
productSubsetDef = new ProductSubsetDef();
//if the user specify the bands that want to be added in the product add only them, else mark the fact that the product must have all the bands
if (!bandList.isSelectionEmpty()) {
productSubsetDef.addNodeNames((String[]) bandList.getSelectedValuesList().stream().toArray(String[]::new));
} else {
if(this.readerInspectorExposeParameters != null && this.readerInspectorExposeParameters.getBandList() != null){
productSubsetDef.addNodeNames(this.readerInspectorExposeParameters.getBandList().stream().toArray(String[]::new));
}
}
//if the user specify the masks that want to be added in the product add only them, else mark the fact that the product must have all the masks
if (!maskList.isSelectionEmpty()) {
productSubsetDef.addNodeNames((String[]) maskList.getSelectedValuesList().stream().toArray(String[]::new));
} else if (copyMasks.isSelected()) {
if(this.readerInspectorExposeParameters != null && this.readerInspectorExposeParameters.getMaskList() != null){
productSubsetDef.addNodeNames(this.readerInspectorExposeParameters.getMaskList().stream().toArray(String[]::new));
}
}
if (!copyMetadata.isSelected()) {
productSubsetDef.setIgnoreMetadata(true);
}
AbstractSubsetRegion subsetRegion = null;
if(geoRegion){
subsetRegion = setGeometry();
}else{
if (pixelCoordXSpinner.getValue() != null && pixelCoordYSpinner.getValue() != null &&
pixelCoordWidthSpinner.getValue() != null && pixelCoordHeightSpinner.getValue() != null) {
subsetRegion = new PixelSubsetRegion(((Integer)pixelCoordXSpinner.getValue()),
((Integer)pixelCoordYSpinner.getValue()),
((Integer)pixelCoordWidthSpinner.getValue()),
((Integer)pixelCoordHeightSpinner.getValue()), 0);
}
}
productSubsetDef.setSubsetRegion(subsetRegion);
}
private AbstractSubsetRegion setGeometry(){
if(this.readerInspectorExposeParameters != null && this.readerInspectorExposeParameters.isHasGeoCoding()) {
final GeoPos geoPos1 = new GeoPos((Double) geoCoordNorthLatSpinner.getValue(),
(Double) geoCoordWestLongSpinner.getValue());
final GeoPos geoPos2 = new GeoPos((Double) geoCoordSouthLatSpinner.getValue(),
(Double) geoCoordEastLongSpinner.getValue());
GeoCoding geoCoding = this.readerInspectorExposeParameters.getGeoCoding();
final PixelPos pixelPos1 = geoCoding.getPixelPos(geoPos1, null);
final PixelPos pixelPos2 = geoCoding.getPixelPos(geoPos2, null);
final Rectangle.Float region = new Rectangle.Float();
region.setFrameFromDiagonal(pixelPos1.x, pixelPos1.y, pixelPos2.x, pixelPos2.y);
final Rectangle.Float productBounds = new Rectangle.Float(0, 0, productWidth, productHeight);
Rectangle2D finalRegion = productBounds.createIntersection(region);
Rectangle bounds = new Rectangle((int)finalRegion.getMinX(), (int)finalRegion.getMinY(), (int)(finalRegion.getMaxX() - finalRegion.getMinX()) + 1, (int)(finalRegion.getMaxY() - finalRegion.getMinY()) + 1);
Geometry geometry = GeoUtils.computeGeometryUsingPixelRegion(geoCoding, bounds);
return new GeometrySubsetRegion(geometry, 0);
}
return null;
}
public ProductSubsetDef getProductSubsetDef() {
return productSubsetDef;
}
}
| 28,662 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductFileChooser.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ProductFileChooser.java | package org.esa.snap.rcp.actions.file;
import org.apache.commons.math3.util.Pair;
import org.esa.snap.core.dataio.DecodeQualification;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.dataio.ProductSubsetDef;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.metadata.MetadataInspector;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.SnapFileChooser;
import org.esa.snap.ui.product.ProductSubsetDialog;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author Marco Peters
* modified 20191009 to support the advanced dialog for readers by Denisa Stefanescu
*/
public class ProductFileChooser extends SnapFileChooser {
private static final Logger logger = Logger.getLogger(ProductFileChooser.class.getName());
private static int numSubsetProducts = 0;
private JButton subsetButton;
private JButton advancedButton;
private Product subsetProduct;
private transient ProductSubsetDef productSubsetDef;
private ProductReaderPlugIn plugin;
private JLabel sizeLabel;
private boolean useSubset;
private boolean useAdvanced;
private Product productToExport;
public ProductFileChooser(File currentDirectory) {
super(currentDirectory);
setDialogType(OPEN_DIALOG);
}
public void setProductToExport(Product product) {
this.productToExport = product;
if (productToExport != null) {
String fileName = productToExport.getName();
if (StringUtils.isNullOrEmpty(fileName) && productToExport.getFileLocation() != null) {
fileName = productToExport.getFileLocation().getName();
}
setCurrentFilename(fileName);
}
}
/**
* File chooser only returns a product, if a product with advanced options was created.
*
* @return the product with advanced options or null
*/
public Product getSubsetProduct() {
return subsetProduct;
}
public boolean isSubsetEnabled() {
return useSubset;
}
public void setSubsetEnabled(boolean useSubset) {
this.useSubset = useSubset;
}
public boolean isAdvancedEnabled() {
return useAdvanced;
}
public void setAdvancedEnabled(boolean useAdvanced) {
this.useAdvanced = useAdvanced;
}
@Override
public int showDialog(Component parent, String approveButtonText) {
initUI();
clearCurrentSubsetProduct();
clearCurrentAdvancedProductOptions();
updateState();
return super.showDialog(parent, approveButtonText);
}
private void initUI() {
if (getDialogType() == OPEN_DIALOG) {
setDialogTitle(SnapApp.getDefault().getInstanceName() + " - Open Product");
if (isSubsetEnabled()) {
setDialogTitle(SnapApp.getDefault().getInstanceName() + " - Import Product");
setApproveButtonText("Import Product");
setApproveButtonMnemonic('I');
setApproveButtonToolTipText("Imports the product.");
}
} else {
setDialogTitle(SnapApp.getDefault().getInstanceName() + " - Save Product");
if (isSubsetEnabled()) {
setDialogTitle(SnapApp.getDefault().getInstanceName() + " - Export Product");
setApproveButtonText("Export Product");
setApproveButtonMnemonic('E');
setApproveButtonToolTipText("Exports the product.");
}
}
if (isSubsetEnabled()) {
addSubsetAcessory();
} else {
if (isAdvancedEnabled()) {
addAdvancedAcessory();
}
}
}
private void addSubsetAcessory() {
subsetButton = new JButton("Subset...");
subsetButton.setMnemonic('S');
subsetButton.addActionListener(e -> openProductSubsetDialog());
subsetButton.setEnabled(getSelectedFile() != null || productToExport != null);
sizeLabel = new JLabel("0 M");
sizeLabel.setHorizontalAlignment(JLabel.RIGHT);
JPanel panel = GridBagUtils.createPanel();
GridBagConstraints gbc = GridBagUtils.createConstraints(
"fill=HORIZONTAL,weightx=1,anchor=NORTHWEST,insets.left=7,insets.right=7,insets.bottom=4");
GridBagUtils.addToPanel(panel, subsetButton, gbc, "gridy=0");
GridBagUtils.addToPanel(panel, sizeLabel, gbc, "gridy=1");
GridBagUtils.addVerticalFiller(panel, gbc);
setAccessory(panel);
addPropertyChangeListener(e -> updateState());
}
private void addAdvancedAcessory() {
advancedButton = new JButton("Advanced");
advancedButton.setMnemonic('A');
advancedButton.addActionListener(e -> openAdvancedDialog());
advancedButton.setEnabled(getSelectedFile() != null);
JPanel panel = GridBagUtils.createPanel();
GridBagConstraints gbc = GridBagUtils.createConstraints(
"fill=HORIZONTAL,weightx=1,anchor=NORTHWEST,insets.left=7,insets.right=7,insets.bottom=4");
GridBagUtils.addToPanel(panel, advancedButton, gbc, "gridy=0");
GridBagUtils.addVerticalFiller(panel, gbc);
setAccessory(panel);
addPropertyChangeListener(e -> updateState());
}
private void updateState() {
if (isSubsetEnabled()) {
subsetButton.setEnabled(getSelectedFile() != null || productToExport != null);
File file = getSelectedFile();
if (file != null && file.isFile()) {
long fileSize = Math.round(file.length() / (1024.0 * 1024.0));
if (fileSize >= 1) {
sizeLabel.setText("File size: " + fileSize + " M");
} else {
sizeLabel.setText("File size: < 1 M");
}
} else {
sizeLabel.setText("");
}
} else {
if (isAdvancedEnabled()) {
advancedButton.setEnabled(getSelectedFile() != null);
}
}
}
private void clearCurrentSubsetProduct() {
subsetProduct = null;
}
private void clearCurrentAdvancedProductOptions() {
productSubsetDef = null;
plugin = null;
}
public ProductSubsetDef getProductSubsetDef() {
return productSubsetDef;
}
public ProductReaderPlugIn getProductReaderPlugin() {
return plugin;
}
private void openProductSubsetDialog() {
Product product = null;
String newProductName = null;
if (getDialogType() == OPEN_DIALOG) {
File file = getSelectedFile();
if (file == null) {
// Should not come here...
return;
}
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final FileFilter fileFilter = getFileFilter();
String formatName = (fileFilter instanceof SnapFileFilter) ? ((SnapFileFilter) fileFilter).getFormatName() : null;
product = ProductIO.readProduct(file, formatName);
if (product == null) {
String msg = "The product could not be read.";
String optionalMsg = file.isDirectory() ? "\nSelection points to a directory." : "";
Dialogs.showError(msg + optionalMsg);
return;
}
newProductName = createNewProductName(product.getName(), numSubsetProducts++);
} catch (IOException e) {
Dialogs.showError("The product could not be read:\n" + e.getMessage());
} finally {
setCursor(Cursor.getDefaultCursor());
}
} else {
product = productToExport;
if (StringUtils.isNotNullAndNotEmpty(getCurrentFilename())) {
newProductName = getCurrentFilename();
} else {
newProductName = createNewProductName(product.getName(), numSubsetProducts++);
}
}
if (product != null) {
boolean approve = openProductSubsetDialog(product, newProductName);
if (approve && getDialogType() == JFileChooser.OPEN_DIALOG) {
approveSelection();
}
}
updateState();
}
private boolean openProductSubsetDialog(Product product, String newProductName) {
clearCurrentSubsetProduct();
if (product != null) {
if (product.isMultiSize()) {
Dialogs.showError("No subset can be created of a multi-size products.");
return false;
}
ProductSubsetDialog productSubsetDialog = new ProductSubsetDialog(SnapApp.getDefault().getMainFrame(), product);
if (productSubsetDialog.show() == ProductSubsetDialog.ID_OK) {
try {
subsetProduct = product.createSubset(productSubsetDialog.getProductSubsetDef(), newProductName, null);
if (getCurrentFilename() != null && !getCurrentFilename().startsWith("subset_")) {
setCurrentFilename("subset_" + getCurrentFilename());
}
return true;
} catch (IOException e) {
Dialogs.showError("Could not create subset:\n" + e.getMessage());
}
}
}
return false;
}
private void openAdvancedDialog() {
clearCurrentAdvancedProductOptions();
File inputFile = getSelectedFile();
boolean canceled = false;
Pair<ProductReaderPlugIn, Boolean> foundPlugin = findPlugins(inputFile);
if(foundPlugin != null){
if(foundPlugin.getKey() == null) {
canceled = foundPlugin.getValue();
}else{
plugin = foundPlugin.getKey();
}
}
boolean addUIComponents = true;
MetadataInspector metadataInspector = null;
if (plugin != null) {
metadataInspector = plugin.getMetadataInspector();
}else{
addUIComponents = false;
}
//if the product does not support Advanced option action
if (addUIComponents && metadataInspector == null) {
int confirm = JOptionPane.showConfirmDialog(null, "The reader does not support the advanced options!\nDo you want to open the product normally?", null, JOptionPane.YES_NO_OPTION);
//if the user want to open the product normally the Advanced Options window will not be displayed
if (confirm == JOptionPane.YES_OPTION) {
addUIComponents = false;
approveSelection();
} else {//if the user choose not to open the product normally the Advanced Option window components are removed
addUIComponents = false;
}
}
if (addUIComponents) {
boolean approve = openAdvancedProduct(metadataInspector, inputFile);
if (approve && getDialogType() == JFileChooser.OPEN_DIALOG) {
approveSelection();
}
updateState();
}else if(plugin == null && !canceled){
Dialogs.showError(Bundle.LBL_NoReaderFoundText() + String.format("%nFile '%s' can not be opened.", inputFile));
}
}
private boolean openAdvancedProduct(MetadataInspector metadataInspector, File file) {
try {
ProductAdvancedDialog advancedDialog = new ProductAdvancedDialog(SnapApp.getDefault().getMainFrame(), "Advanced Options", metadataInspector, file);
advancedDialog.show();
productSubsetDef = advancedDialog.getProductSubsetDef();
if(productSubsetDef != null) {
return true;
}
}catch (Exception e) {
logger.log(Level.SEVERE, "Failed to open the advanced option dialog.", e);
Dialogs.showError("The file " + getSelectedFile() + " could not be opened with advanced options!");
}
return false;
}
private String createNewProductName(String sourceProductName, int productIndex) {
String newNameBase = "";
if (sourceProductName != null && sourceProductName.length() > 0) {
newNameBase = FileUtils.exchangeExtension(sourceProductName, "");
}
String newNamePrefix = "subset";
String newProductName;
if (newNameBase.length() > 0) {
newProductName = newNamePrefix + "_" + productIndex + "_" + newNameBase;
} else {
newProductName = newNamePrefix + "_" + productIndex;
}
return newProductName;
}
public static Path convertInputToPath(Object input) {
if (input == null) {
throw new NullPointerException();
} else if (input instanceof File) {
return ((File) input).toPath();
} else if (input instanceof Path) {
return (Path) input;
} else if (input instanceof String) {
return Paths.get((String) input);
} else {
throw new IllegalArgumentException("Unknown input '" + input + "'.");
}
}
private Pair<ProductReaderPlugIn, Boolean> findPlugins(File file){
Pair<ProductReaderPlugIn, Boolean> result = null;
final Map<DecodeQualification, List<ProductOpener.PluginEntry>> plugins = ProductOpener.getPluginsForFile(file);
final String fileFormatName;
final List<ProductOpener.PluginEntry> intendedPlugIns = plugins.get(DecodeQualification.INTENDED);
final List<ProductOpener.PluginEntry> suitablePlugIns = plugins.get(DecodeQualification.SUITABLE);
if (intendedPlugIns.size() == 1) {
ProductOpener.PluginEntry entry = intendedPlugIns.get(0);
result = new Pair<>(entry.plugin, null);
}else if (intendedPlugIns.isEmpty() && suitablePlugIns.size() == 1) {
ProductOpener.PluginEntry entry = suitablePlugIns.get(0);
result = new Pair<>(entry.plugin, null);
}else if (!intendedPlugIns.isEmpty() || !suitablePlugIns.isEmpty()){
Collections.sort(intendedPlugIns);
Collections.sort(suitablePlugIns);
// ask user to select a desired reader plugin
fileFormatName = ProductOpener.getUserSelection(intendedPlugIns, suitablePlugIns);
if (fileFormatName == null) { // User clicked cancel
result = new Pair<>(null, true);
} else {
if (!suitablePlugIns.isEmpty() && suitablePlugIns.stream()
.anyMatch(entry -> entry.plugin.getFormatNames()[0].equals(fileFormatName))) {
ProductOpener.PluginEntry entry = suitablePlugIns.stream()
.filter(entry1 -> entry1.plugin.getFormatNames()[0].equals(fileFormatName))
.findAny()
.orElse(null);
result = new Pair<>(entry.plugin, false);
} else {
ProductOpener.PluginEntry entry = intendedPlugIns.stream()
.filter(entry1 -> entry1.plugin.getFormatNames()[0].equals(fileFormatName))
.findAny()
.orElse(null);
result = new Pair<>(entry.plugin, false);
}
}
}
return result;
}
}
| 16,014 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductOpener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ProductOpener.java | package org.esa.snap.rcp.actions.file;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.dataio.DecodeQualification;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.dataio.ProductSubsetDef;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.vfs.NioPaths;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;
import org.openide.DialogDisplayer;
import org.openide.NotifyDescriptor;
import org.openide.util.RequestProcessor;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.nio.file.Path;
import java.text.MessageFormat;
import java.util.List;
import java.util.*;
import java.util.prefs.Preferences;
/**
* @author Marco Peters
* modified 20191009 to support the advanced dialog for readers by Denisa Stefanescu
*/
public class ProductOpener {
public static final String PREFERENCES_KEY_LAST_PRODUCT_DIR = "last_product_open_dir";
private static final String PREFERENCES_KEY_PREFIX_ALTERNATIVE_READER = "open_alternative_reader.";
private static final String PREFERENCES_KEY_DONT_SHOW_DIALOG = "multipleReadersDialog.dontShow";
private static final int IMMEDIATELY = 0;
private String fileFormat;
private boolean useAllFileFilter;
private boolean subsetImportEnabled;
private File[] files;
private boolean multiSelectionEnabled;
private ProductSubsetDef productSubsetDef = null;
private ProductReaderPlugIn plugin = null;
public void setFiles(File... files) {
this.files = files;
}
public File[] getFiles() {
return files;
}
void setFileFormat(String format) {
fileFormat = format;
}
public String getFileFormat() {
return fileFormat;
}
void setUseAllFileFilter(boolean useAllFileFilter) {
this.useAllFileFilter = useAllFileFilter;
}
public boolean isUseAllFileFilter() {
return useAllFileFilter;
}
void setSubsetImportEnabled(boolean subsetImportEnabled) {
this.subsetImportEnabled = subsetImportEnabled;
}
public boolean isSubsetImportEnabled() {
return subsetImportEnabled;
}
public void setMultiSelectionEnabled(boolean multiSelectionEnabled) {
this.multiSelectionEnabled = multiSelectionEnabled;
}
public boolean isMultiSelectionEnabled() {
return multiSelectionEnabled;
}
public Boolean openProduct() {
File[] configuredFiles = getFiles();
if (configuredFiles != null) {
return openProductFilesCheckOpened(getFileFormat(), configuredFiles);
}
Iterator<ProductReaderPlugIn> readerPlugIns;
if (getFileFormat() != null) {
readerPlugIns = ProductIOPlugInManager.getInstance().getReaderPlugIns(getFileFormat());
if (!readerPlugIns.hasNext()) {
Dialogs.showError(
Bundle.LBL_NoReaderFoundText() + String.format("%nCan't find reader for the given format '%s'.", getFileFormat()));
return false;
}
} else {
readerPlugIns = ProductIOPlugInManager.getInstance().getAllReaderPlugIns();
}
List<SnapFileFilter> filters = new ArrayList<>();
while (readerPlugIns.hasNext()) {
ProductReaderPlugIn readerPlugIn = readerPlugIns.next();
SnapFileFilter snapFileFilter = readerPlugIn.getProductFileFilter();
if (snapFileFilter != null) {
filters.add(snapFileFilter);
}
}
Collections.sort(filters, (f1, f2) -> {
String d1 = f1.getDescription();
String d2 = f2.getDescription();
return d1 != null ? d1.compareTo(d2) : d2 == null ? 0 : 1;
});
if (filters.isEmpty()) {
Dialogs.showError(Bundle.LBL_NoReaderFoundText());
return false;
}
Preferences preferences = SnapApp.getDefault().getPreferences();
String userHomePath = SystemUtils.getUserHomeDir().getAbsolutePath();
Path recentPath = NioPaths.get(preferences.get(PREFERENCES_KEY_LAST_PRODUCT_DIR, userHomePath));
ProductFileChooser fc = new ProductFileChooser(recentPath.toFile());
fc.setSubsetEnabled(isSubsetImportEnabled());
fc.setAdvancedEnabled(true);
fc.setDialogTitle(SnapApp.getDefault().getInstanceName() + " - " + Bundle.CTL_OpenProductActionName());
fc.setAcceptAllFileFilterUsed(isUseAllFileFilter());
filters.forEach((filter) -> {
fc.addChoosableFileFilter(filter);
if (getFileFormat() != null && getFileFormat().equals(filter.getFormatName())) {
fc.setFileFilter(filter);
}
});
fc.setMultiSelectionEnabled(isMultiSelectionEnabled());
if (filters.size() == 1) {
fc.setFileSelectionMode(filters.get(0).getFileSelectionMode().getValue());
} else {
fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
}
int returnVal = fc.showOpenDialog(SnapApp.getDefault().getMainFrame());
if (returnVal != JFileChooser.APPROVE_OPTION) {
// cancelled
return null;
}
File[] files = getSelectedFiles(fc);
if (files == null || files.length == 0) {
// cancelled
return null;
}
File currentDirectory = fc.getCurrentDirectory();
if (currentDirectory != null) {
preferences.put(PREFERENCES_KEY_LAST_PRODUCT_DIR, currentDirectory.toString());
}
if (fc.getSubsetProduct() != null) {
SnapApp.getDefault().getProductManager().addProduct(fc.getSubsetProduct());
return true;
}
String formatName;
if (fc.getProductSubsetDef() != null || fc.getProductReaderPlugin() != null) {
productSubsetDef = fc.getProductSubsetDef();
plugin = fc.getProductReaderPlugin();
}
formatName = (fc.getFileFilter() instanceof SnapFileFilter)
? ((SnapFileFilter) fc.getFileFilter()).getFormatName()
: null;
return openProductFilesCheckOpened(formatName, files);
}
private File[] getSelectedFiles(ProductFileChooser fc) {
File[] files = new File[0];
if (isMultiSelectionEnabled()) {
files = fc.getSelectedFiles();
} else {
File file = fc.getSelectedFile();
if (file != null) {
files = new File[]{file};
}
}
return files;
}
private Boolean openProductFilesCheckOpened(final String formatName, final File... files) {
List<File> openedFiles = OpenProductAction.getOpenedProductFiles();
List<File> fileList = new ArrayList<>(Arrays.asList(files));
for (File file : files) {
if (!file.exists()) {
fileList.remove(file);
continue;
}
if (openedFiles.contains(file)) {
Dialogs.Answer answer = Dialogs.requestDecision(Bundle.CTL_OpenProductActionName(),
MessageFormat.format("Product\n" +
"{0}\n" +
"is already opened.\n" +
"Do you want to open another instance?", file),
true, null);
if (answer == Dialogs.Answer.NO) {
fileList.remove(file);
} else if (answer == Dialogs.Answer.CANCELLED) {
return null;
}
}
}
RequestProcessor rp = new RequestProcessor("Opening Products", 4, true, true);
for (File file : fileList) {
String fileFormatName;
PluginEntry entry;
if (formatName == null && plugin == null) {
final Map<DecodeQualification, List<PluginEntry>> plugins = getPluginsForFile(file);
if (plugins.isEmpty() || (plugins.get(DecodeQualification.INTENDED).size() == 0 && plugins.get(DecodeQualification.SUITABLE).size() == 0)) {
Dialogs.showError(Bundle.LBL_NoReaderFoundText() + String.format("%nFile '%s' can not be opened.", file));
continue;
} else if (plugins.get(DecodeQualification.INTENDED).size() == 1) {
entry = plugins.get(DecodeQualification.INTENDED).get(0);
fileFormatName = entry.plugin.getFormatNames()[0];
} else if (plugins.get(DecodeQualification.INTENDED).size() == 0 && plugins.get(DecodeQualification.SUITABLE).size() == 1) {
entry = plugins.get(DecodeQualification.SUITABLE).get(0);
fileFormatName = entry.plugin.getFormatNames()[0];
} else {
final List<PluginEntry> intendedPlugIns = plugins.get(DecodeQualification.INTENDED);
final List<PluginEntry> suitablePlugIns = plugins.get(DecodeQualification.SUITABLE);
Collections.sort(intendedPlugIns);
Collections.sort(suitablePlugIns);
fileFormatName = getUserSelection(intendedPlugIns, suitablePlugIns);
if (fileFormatName == null) { // User clicked cancel
return null;
}
}
} else if (formatName == null && plugin != null) {
fileFormatName = plugin.getFormatNames()[0];
} else {
fileFormatName = formatName;
}
ReadProductOperation operation = new ReadProductOperation(file, fileFormatName);
operation.setProductSubsetDef(productSubsetDef);
operation.setProductReaderPlugIn(plugin);
RequestProcessor.Task task = rp.create(operation);
// TODO (mp/20160830) - Cancellation is not working; the thread is not interrupted. Why?
ProgressHandle handle = ProgressHandleFactory.createHandle("Reading " + file.getName()/*, operation.createCancellable(task)*/);
operation.attacheProgressHandle(handle);
task.schedule(IMMEDIATELY);
}
return true;
}
static Map<DecodeQualification, List<PluginEntry>> getPluginsForFile(File file) {
final Iterator<ProductReaderPlugIn> allReaderPlugIns = ProductIOPlugInManager.getInstance().getAllReaderPlugIns();
final Map<DecodeQualification, List<PluginEntry>> possiblePlugIns = new HashMap<>();
possiblePlugIns.put(DecodeQualification.INTENDED, new ArrayList<>());
possiblePlugIns.put(DecodeQualification.SUITABLE, new ArrayList<>());
allReaderPlugIns.forEachRemaining(plugIn -> {
final DecodeQualification qualification = plugIn.getDecodeQualification(file);
if (qualification != DecodeQualification.UNABLE) {
possiblePlugIns.get(qualification).add(new PluginEntry(plugIn, qualification));
}
});
return possiblePlugIns;
}
static String getUserSelection(List<PluginEntry> intendedPlugins, List<PluginEntry> suitablePlugIns) {
final PluginEntry leadPlugin;
if (!intendedPlugins.isEmpty()) {
leadPlugin = intendedPlugins.get(0);
} else {
leadPlugin = suitablePlugIns.get(0);
}
final boolean dontShowDialog = SnapApp.getDefault().getPreferences().getBoolean(PREFERENCES_KEY_DONT_SHOW_DIALOG, false);
String prefKeyFormat = PREFERENCES_KEY_PREFIX_ALTERNATIVE_READER + leadPlugin.plugin.getClass().getSimpleName();
final String storedSelection = SnapApp.getDefault().getPreferences().get(prefKeyFormat, null);
if (dontShowDialog && storedSelection != null) {
return storedSelection;
}
final TableLayout layout = new TableLayout(1);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableFill(TableLayout.Fill.HORIZONTAL);
layout.setTablePadding(4, 4);
final JPanel readerSelectionPanel = new JPanel(layout);
readerSelectionPanel.add(new JLabel("<html>Multiple readers are available for the selected file.<br>" +
"The readers might interpret the data differently.<br>" +
"Please select one of the following:"));
final JComboBox<ProductReaderPlugIn> pluginsCombobox = new JComboBox<>();
DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setText(((ProductReaderPlugIn) value).getDescription(Locale.getDefault()));
return this;
}
};
pluginsCombobox.setRenderer(cellRenderer);
for (PluginEntry plugin : intendedPlugins) {
pluginsCombobox.addItem(plugin.plugin);
}
for (PluginEntry plugin : suitablePlugIns) {
pluginsCombobox.addItem(plugin.plugin);
}
readerSelectionPanel.add(pluginsCombobox);
JCheckBox decisionCheckBox = new JCheckBox("Remember my decision and don't ask again.", false);
decisionCheckBox.setHorizontalAlignment(SwingConstants.RIGHT);
readerSelectionPanel.add(decisionCheckBox);
NotifyDescriptor d = new NotifyDescriptor(readerSelectionPanel,
Dialogs.getDialogTitle("Multiple Readers Available"),
NotifyDescriptor.OK_CANCEL_OPTION, NotifyDescriptor.QUESTION_MESSAGE, null,
NotifyDescriptor.OK_OPTION);
Object answer = DialogDisplayer.getDefault().notify(d);
if (NotifyDescriptor.OK_OPTION.equals(answer)) {
boolean storeResult = decisionCheckBox.isSelected();
String selectedFormatName = ((ProductReaderPlugIn) pluginsCombobox.getSelectedItem()).getFormatNames()[0];
if (storeResult) {
SnapApp.getDefault().getPreferences().put(prefKeyFormat, selectedFormatName);
SnapApp.getDefault().getPreferences().put(PREFERENCES_KEY_DONT_SHOW_DIALOG, "true");
}
return selectedFormatName;
}
return null;
}
static class PluginEntry implements Comparable<PluginEntry> {
ProductReaderPlugIn plugin;
DecodeQualification qualification;
public PluginEntry(ProductReaderPlugIn plugin, DecodeQualification qualification) {
this.plugin = plugin;
this.qualification = qualification;
}
@Override
public int compareTo(PluginEntry other) {
final int qualificationComparison = this.qualification.compareTo(other.qualification);
if (qualificationComparison == 0) {
final String description1 = this.plugin.getDescription(Locale.getDefault());
final String description2 = other.plugin.getDescription(Locale.getDefault());
return description1.compareTo(description2);
} else {
return qualificationComparison;
}
}
}
}
| 15,888 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImportProductAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ImportProductAction.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.actions.file;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.util.Map;
/**
* Generic configurable action for importing data products.
*
* @author Marco Peters
* @author Norman Fomferra
*/
@NbBundle.Messages({
"CTL_ImportProductActionName=Import Product",
"CTL_ImportProductActionMenuText=Import Product..."
})
public class ImportProductAction extends AbstractAction implements HelpCtx.Provider {
/**
* Action factory method used in NetBeans {@code layer.xml} file, e.g.
*
* <pre>
* <file name="org-esa-snap-dataio-ceos-ImportAvnir2Product.instance">
* <attr name="instanceCreate"
* methodvalue="org.openide.awt.Actions.alwaysEnabled"/>
* <attr name="delegate"
* methodvalue="ImportProductAction.create"/>
* <attr name="displayName"
* stringvalue="ALOS/AVNIR-2 Product"/>
* <attr name="formatName"
* stringvalue="AVNIR-2"/>
* <attr name="useAllFileFilter"
* boolvalue="true"/>
* <attr name="helpId"
* stringvalue="importAvnir2Product"/>
* <attr name="ShortDescription"
* stringvalue="Import an ALOS/AVNIR-2 data product."/>
* </file>
* </pre>
*
* @param configuration Configuration attributes from layer.xml.
* @return The action.
* @since SNAP 2
*/
public static ImportProductAction create(Map<String, Object> configuration) {
ImportProductAction importProductAction = new ImportProductAction();
importProductAction.setFormatName((String) configuration.get("formatName"));
importProductAction.setHelpCtx((String) configuration.get("helpId"));
importProductAction.setUseAllFileFilter((Boolean) configuration.get("useAllFileFilter"));
return importProductAction;
}
@Override
public HelpCtx getHelpCtx() {
return (HelpCtx) getValue("helpCtx");
}
public void setHelpCtx(String helpId) {
putValue("helpCtx", helpId != null ? new HelpCtx(helpId) : null);
}
public void setFormatName(String formatName) {
putValue("formatName", formatName);
}
String getFormatName() {
return (String) getValue("formatName");
}
public void setUseAllFileFilter(boolean useAllFileFilter) {
putValue("useAllFileFilter", useAllFileFilter);
}
boolean getUseAllFileFilter() {
return Boolean.TRUE.equals(getValue("useAllFileFilter"));
}
@Override
public void actionPerformed(ActionEvent e) {
final ProductOpener opener = new ProductOpener();
opener.setFileFormat(getFormatName());
opener.setUseAllFileFilter(getUseAllFileFilter());
opener.setMultiSelectionEnabled(false);
opener.setSubsetImportEnabled(true);
opener.openProduct();
}
}
| 3,759 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OpenProductAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/OpenProductAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.file;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.rcp.SnapApp;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author Norman
*/
@ActionID(
category = "File",
id = "OpenProductAction"
)
@ActionRegistration(
displayName = "#CTL_OpenProductActionName",
menuText = "#CTL_OpenProductActionMenuText",
iconBase = "org/esa/snap/rcp/icons/Open.gif"
)
@ActionReferences({
@ActionReference(path = "Menu/File", position = 5),
@ActionReference(path = "Toolbars/File", position = 10)
})
@NbBundle.Messages({
"CTL_OpenProductActionName=Open Product",
"CTL_OpenProductActionMenuText=Open Product...",
"LBL_NoReaderFoundText=No appropriate product reader found.",
})
public final class OpenProductAction extends AbstractAction {
public static final String PREFERENCES_KEY_RECENTLY_OPENED_PRODUCTS = "recently_opened_products";
public static final String PREFERENCES_KEY_LAST_PRODUCT_DIR = "last_product_open_dir";
static RecentPaths getRecentProductPaths() {
return new RecentPaths(SnapApp.getDefault().getPreferences(), PREFERENCES_KEY_RECENTLY_OPENED_PRODUCTS, true);
}
static List<File> getOpenedProductFiles() {
return Arrays.stream(SnapApp.getDefault().getProductManager().getProducts())
.map(Product::getFileLocation)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
public File[] getFiles() {
Object value = getValue("files");
if (value instanceof File[]) {
return (File[]) value;
}
return null;
}
public void setFile(File file) {
setFiles(file);
}
public void setFiles(File... files) {
putValue("files", files);
}
public String getFileFormat() {
Object value = getValue("fileFormat");
if (value instanceof String) {
return (String) value;
}
return null;
}
public void setFileFormat(String fileFormat) {
putValue("fileFormat", fileFormat);
}
public void setUseAllFileFilter(boolean useAllFileFilter) {
putValue("useAllFileFilter", useAllFileFilter);
}
public boolean getUseAllFileFilter() {
// by default the All file filter is used
return getBooleanProperty("useAllFileFilter", true);
}
private boolean getBooleanProperty(String propertyName, Boolean defaultValue) {
final Object propValue = getValue(propertyName);
if (propValue == null) {
return defaultValue;
} else {
return Boolean.TRUE.equals(propValue);
}
}
@Override
public void actionPerformed(ActionEvent e) {
execute();
}
/**
* Executes the action command.
*
* @return {@code Boolean.TRUE} on success, {@code Boolean.FALSE} on failure, or {@code null} on cancellation.
*/
public Boolean execute() {
final ProductOpener opener = new ProductOpener();
opener.setFiles(getFiles());
opener.setFileFormat(getFileFormat());
opener.setUseAllFileFilter(getUseAllFileFilter());
opener.setMultiSelectionEnabled(true);
opener.setSubsetImportEnabled(false);
return opener.openProduct();
}
}
| 3,881 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CloseAllProductsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/CloseAllProductsAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.file;
import java.awt.event.ActionEvent;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.swing.AbstractAction;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.rcp.SnapApp;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
/**
* Action which closes all opened products.
*
* @author Norman
*/
@ActionID(category = "File", id = "CloseAllProductsAction")
@ActionRegistration(displayName = "#CTL_CloseAllProductsActionName", lazy = false)
@ActionReferences({
@ActionReference(path = "Menu/File", position = 25),
@ActionReference(path = "Context/Product/Product", position = 70)
})
@NbBundle.Messages({"CTL_CloseAllProductsActionName=Close All Products"})
public final class CloseAllProductsAction extends AbstractAction {
public CloseAllProductsAction() {
super(Bundle.CTL_CloseAllProductsActionName());
ProductManager productManager = SnapApp.getDefault().getProductManager();
productManager.addListener(new CloseAllProductListener());
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent e) {
execute();
}
/**
* Executes the action command.
*
* @return {@code Boolean.TRUE} on success, {@code Boolean.FALSE} on failure, or {@code null} on cancellation.
*/
public Boolean execute() {
Set<Product> collect = Stream.of(SnapApp.getDefault().getProductManager().getProducts()).collect(Collectors.toSet());
return CloseProductAction.closeProducts(collect);
}
private class CloseAllProductListener implements ProductManager.Listener {
@Override
public void productAdded(ProductManager.Event event) {
updateEnableState();
}
@Override
public void productRemoved(ProductManager.Event event) {
updateEnableState();
}
private void updateEnableState() {
setEnabled(SnapApp.getDefault().getProductManager().getProductCount() > 0);
}
}
}
| 2,467 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReadProductInspectorTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ReadProductInspectorTimerRunnable.java | package org.esa.snap.rcp.actions.file;
import org.esa.snap.core.metadata.MetadataInspector;
import org.esa.snap.ui.loading.AbstractTimerRunnable;
import org.esa.snap.ui.loading.LoadingIndicator;
import java.nio.file.Path;
/**
* Created by jcoravu on 17/2/2020.
* Updated by Denisa Stefanescu on 18/02/2020
*/
public class ReadProductInspectorTimerRunnable extends AbstractTimerRunnable<MetadataInspector.Metadata> {
private final MetadataInspector metadataInspector;
private final Path productFile;
public ReadProductInspectorTimerRunnable(LoadingIndicator loadingIndicator, int threadId, MetadataInspector metadataInspector, Path productFile) {
super(loadingIndicator, threadId, 500);
this.metadataInspector = metadataInspector;
this.productFile = productFile;
}
@Override
protected void onTimerWakeUp(String messageToDisplay) {
super.onTimerWakeUp("Loading...");
}
@Override
protected MetadataInspector.Metadata execute() throws Exception {
return metadataInspector.getMetadata(this.productFile);
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to read the product metadata inspector.";
}
}
| 1,231 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ReopenProductAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ReopenProductAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.file;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.preferences.general.UiBehaviorController;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import org.openide.util.actions.Presenter;
import javax.swing.AbstractAction;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.List;
import java.util.prefs.Preferences;
import static org.esa.snap.rcp.actions.file.OpenProductAction.getRecentProductPaths;
/**
* @author Norman
*/
@ActionID(
category = "File",
id = "ReopenProductAction"
)
@ActionRegistration(
displayName = "#CTL_ReopenProductActionName",
menuText = "#CTL_ReopenProductActionMenuText",
lazy = false
)
@ActionReference(path = "Menu/File", position = 10)
@NbBundle.Messages({
"CTL_ReopenProductActionName=Reopen Product",
"CTL_ReopenProductActionMenuText=Reopen Product",
"CTL_ClearListActionMenuText=Clear List"
})
public final class ReopenProductAction extends AbstractAction implements Presenter.Toolbar, Presenter.Menu, Presenter.Popup {
private final int DEFAULT_MAX_FILE_LIST_REOPEN = 10;
@Override
public JMenuItem getMenuPresenter() {
List<File> openedFiles = OpenProductAction.getOpenedProductFiles();
List<String> pathList = getRecentProductPaths().get();
final Preferences preference = SnapApp.getDefault().getPreferences();
int maxFileList = preference.getInt(UiBehaviorController.PREFERENCE_KEY_LIST_FILES_TO_REOPEN,
DEFAULT_MAX_FILE_LIST_REOPEN);
// Add "open recent product file" actions
JMenu menu = new JMenu(Bundle.CTL_ReopenProductActionMenuText());
pathList.stream().limit(maxFileList).forEach(path->{
File theFile = new File(path);
if (!openedFiles.contains(theFile) && theFile.exists()) {
JMenuItem menuItem = new JMenuItem(path);
OpenProductAction openProductAction = new OpenProductAction();
openProductAction.setFile(theFile);
menuItem.addActionListener(openProductAction);
menu.add(menuItem);
}
});
// Add "Clear List" action
if (menu.getComponentCount() > 0 || pathList.size() > 0) {
menu.addSeparator();
JMenuItem menuItem = new JMenuItem(Bundle.CTL_ClearListActionMenuText());
menuItem.addActionListener(e -> getRecentProductPaths().clear());
menu.add(menuItem);
}
return menu;
}
@Override
public JMenuItem getPopupPresenter() {
return getMenuPresenter();
}
@Override
public Component getToolbarPresenter() {
return getMenuPresenter();
}
@Override
public void actionPerformed(ActionEvent e) {
// do nothing
}
}
| 3,217 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SaveProductAsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/SaveProductAsAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.file;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductReader;
import org.esa.snap.core.dataio.dimap.DimapProductConstants;
import org.esa.snap.core.dataio.dimap.DimapProductHelpers;
import org.esa.snap.core.dataio.dimap.DimapProductReader;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.image.BandOpImage;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
/**
* Action which saves a selected product using a new name.
*
* @author Norman
*/
@ActionID(category = "File", id = "SaveProductAsAction")
@ActionRegistration(displayName = "#CTL_SaveProductAsActionName")
@ActionReferences({
@ActionReference(path = "Menu/File", position = 45, separatorAfter = 46),
@ActionReference(path = "Context/Product/Product", position = 95, separatorAfter = 96)
})
@NbBundle.Messages({"CTL_SaveProductAsActionName=Save Product As..."})
public final class SaveProductAsAction extends AbstractAction {
public static final String PREFERENCES_KEY_PRODUCT_CONVERSION_REQUIRED = "product_conversion_required";
public static final String PREFERENCES_KEY_LAST_PRODUCT_DIR = "last_product_save_dir";
private final WeakReference<ProductNode> productNodeRef;
public SaveProductAsAction(ProductNode productNode) {
productNodeRef = new WeakReference<>(productNode);
}
@Override
public void actionPerformed(ActionEvent e) {
execute();
}
/**
* Executes the action command.
*
* @return {@code Boolean.TRUE} on success, {@code Boolean.FALSE} on failure, or {@code null} on cancellation.
*/
public Boolean execute() {
ProductNode productNode = productNodeRef.get();
if (productNode != null && productNode.getProduct() != null) {
return saveProductAs(productNode.getProduct());
} else {
// reference was garbage collected, that's fine, no need to save.
return true;
}
}
private Boolean saveProductAs(Product product) {
ProductReader reader = product.getProductReader();
if (reader != null && !(reader instanceof DimapProductReader)) {
Dialogs.Answer answer = Dialogs.requestDecision("Save Product As",
MessageFormat.format("In order to save the product\n" +
" {0}\n" +
"it has to be converted to the BEAM-DIMAP format.\n" +
"Depending on the product size the conversion also may take a while.\n\n" +
"Do you really want to convert the product now?\n",
product.getDisplayName()),
true,
PREFERENCES_KEY_PRODUCT_CONVERSION_REQUIRED);
if (answer == Dialogs.Answer.NO) {
return false;
} else if (answer == Dialogs.Answer.CANCELLED) {
return null;
}
}
String fileName = product.getName();
if (StringUtils.isNullOrEmpty(fileName) && product.getFileLocation() != null) {
// fallback
fileName = product.getFileLocation().getName();
}
File newFile = Dialogs.requestFileForSave("Save Product As",
false,
DimapProductHelpers.createDimapFileFilter(),
DimapProductConstants.DIMAP_HEADER_FILE_EXTENSION,
fileName,
null,
OpenProductAction.PREFERENCES_KEY_LAST_PRODUCT_DIR);
if (newFile == null) {
// cancelled
return null;
}
String oldProductName = product.getName();
File oldFile = product.getFileLocation();
// For DIMAP products, check if file path has really changed
// if not, just save product
if (reader instanceof DimapProductReader && newFile.equals(oldFile)) {
return new SaveProductAction(product).execute();
}
product.setFileLocation(newFile);
Boolean status = SaveProductAction.saveProduct(product);
if (Boolean.TRUE.equals(status)) {
try {
attachNewDimapReaderInstance(product, newFile);
} catch (IOException e) {
SnapApp.getDefault().handleError("Failed to reopen product", e);
}
} else {
product.setFileLocation(oldFile);
product.setName(oldProductName);
}
return status;
}
private void attachNewDimapReaderInstance(Product product, File newFile) throws IOException {
DimapProductReader productReader = (DimapProductReader) ProductIO.getProductReader(DimapProductConstants.DIMAP_FORMAT_NAME);
productReader.bindProduct(newFile, product);
product.setProductReader(productReader);
Band[] bands = product.getBands();
for (Band band : bands) {
if (band.isSourceImageSet() && band.getSourceImage().getImage(0) instanceof BandOpImage) {
band.setSourceImage(null);
}
}
}
}
| 6,414 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportProductAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/ExportProductAction.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.actions.file;
import org.esa.snap.core.dataio.EncodeQualification;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductWriter;
import org.esa.snap.core.dataio.ProductWriterPlugIn;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.netbeans.api.progress.BaseProgressUtils;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.prefs.Preferences;
/**
* Action for exporting a product.
*
* @author Marco Peters
*/
public class ExportProductAction extends AbstractAction implements HelpCtx.Provider, ContextAwareAction {
private static final String PROPERTY_FORMAT_NAME = "formatName";
private static final String PROPERTY_HELP_CTX = "helpCtx";
private static final String PROPERTY_USE_ALL_FILE_FILTER = "useAllFileFilter";
private WeakReference<Product> productRef;
/**
* Action factory method used in NetBeans {@code layer.xml} file, e.g.
* <p>
* <pre>
* <file name="org-esa-snap-csv-dataio-ExportCSVProduct.instance">
* <attr name="instanceCreate" methodvalue="org.openide.awt.Actions.context"/>
* <attr name="type" stringvalue="ProductNode"/>
* <attr name="delegate" methodvalue="ExportProductAction.create"/>
* <attr name="selectionType" stringvalue="EXACTLY_ONE"/>
* <attr name="displayName" stringvalue="CSV Product"/>
* <attr name="formatName" stringvalue="CSV"/>
* <attr name="useAllFileFilter" boolvalue="true"/>
* <attr name="helpId" stringvalue="exportCsvProduct"/>
* <attr name="ShortDescription" stringvalue="Writes a product in CSV format."/>
* </file>
* </pre>
*
* @param configuration Configuration attributes from layer.xml.
* @return The action.
* @since SNAP 2
*/
public static ExportProductAction create(Map<String, Object> configuration) {
ExportProductAction exportProductAction = new ExportProductAction();
exportProductAction.setFormatName((String) configuration.get(PROPERTY_FORMAT_NAME));
exportProductAction.setHelpCtx((String) configuration.get("helpId"));
exportProductAction.setUseAllFileFilter((Boolean) configuration.get(PROPERTY_USE_ALL_FILE_FILTER));
return exportProductAction;
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
ProductNode productNode = actionContext.lookup(ProductNode.class);
setProduct(productNode.getProduct());
return this;
}
@Override
public HelpCtx getHelpCtx() {
return (HelpCtx) getValue(PROPERTY_HELP_CTX);
}
public void setHelpCtx(String helpId) {
putValue(PROPERTY_HELP_CTX, helpId != null ? new HelpCtx(helpId) : null);
}
public String getDisplayName() {
return (String) getValue("displayName");
}
public void setFormatName(String formatName) {
putValue(PROPERTY_FORMAT_NAME, formatName);
}
public void setUseAllFileFilter(Boolean useAllFileFilter) {
putValue(PROPERTY_USE_ALL_FILE_FILTER, useAllFileFilter);
}
public void setProduct(Product p) {
productRef = new WeakReference<>(p);
}
@Override
public void actionPerformed(ActionEvent e) {
execute();
}
/**
* @return {@code Boolean.TRUE} on success, {@code Boolean.FALSE} on failure, or {@code null} on cancellation.
*/
public Boolean execute() {
Product product = productRef.get();
if (product != null) {
return exportProduct(product, (String) getValue(PROPERTY_FORMAT_NAME));
} else {
// reference was garbage collected, that's fine, no need to save.
return true;
}
}
private Boolean exportProduct(Product product, String formatName) {
final ProductWriter productWriter = ProductIO.getProductWriter(formatName);
if (productWriter == null) {
Dialogs.showError(getDisplayName(), MessageFormat.format("No writer found for format {0}.", formatName));
return null;
}
final EncodeQualification encodeQualification = productWriter.getWriterPlugIn().getEncodeQualification(product);
if (encodeQualification.getPreservation() == EncodeQualification.Preservation.UNABLE) {
Dialogs.showError(getDisplayName(), MessageFormat.format("Writing this product as {0} is not possible:\n"
+ encodeQualification.getInfoString(),
formatName
));
return null;
}
Preferences preferences = SnapApp.getDefault().getPreferences();
ProductFileChooser fc = new ProductFileChooser(new File(preferences.get(ProductOpener.PREFERENCES_KEY_LAST_PRODUCT_DIR, ".")));
fc.setDialogType(JFileChooser.SAVE_DIALOG);
fc.setSubsetEnabled(true);
fc.setAdvancedEnabled(false);
fc.addChoosableFileFilter(getFileFilter(formatName));
fc.setProductToExport(product);
int returnVal = fc.showSaveDialog(SnapApp.getDefault().getMainFrame());
if (returnVal != JFileChooser.APPROVE_OPTION) {
// cancelled
return null;
}
File newFile = fc.getSelectedFile();
if (newFile == null) {
// cancelled
return null;
}
if (newFile.isFile() && !newFile.canWrite()) {
Dialogs.showWarning(getDisplayName(),
MessageFormat.format("The product\n" +
"''{0}''\n" +
"exists and cannot be overwritten, because it is read only.\n" +
"Please choose another file or remove the write protection.",
newFile.getPath()),
null);
return false;
}
Product exportProduct = fc.getSubsetProduct() != null ? fc.getSubsetProduct() : product;
SnapApp.getDefault().setStatusBarMessage(MessageFormat.format("Exporting product ''{0}'' to {1}...", exportProduct.getDisplayName(), newFile));
WriteProductOperation operation = new WriteProductOperation(exportProduct, newFile, formatName, false);
BaseProgressUtils.runOffEventThreadWithProgressDialog(operation,
getDisplayName(),
operation.getProgressHandle(),
true,
50,
1000);
SnapApp.getDefault().setStatusBarMessage("");
return operation.getStatus();
}
private FileFilter getFileFilter(String formatName) {
Iterator<ProductWriterPlugIn> writerPlugIns = ProductIOPlugInManager.getInstance().getWriterPlugIns(formatName);
if (writerPlugIns.hasNext()) {
return writerPlugIns.next().getProductFileFilter();
}
return null;
}
private String getFileExtension(String formatName) {
Iterator<ProductWriterPlugIn> writerPlugIns = ProductIOPlugInManager.getInstance().getWriterPlugIns(formatName);
String fileExtension = null;
if (writerPlugIns.hasNext()) {
SnapFileFilter fileFilter = writerPlugIns.next().getProductFileFilter();
if (fileFilter != null) {
fileExtension = fileFilter.getDefaultExtension();
}
}
return fileExtension;
}
}
| 9,224 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SaveProductAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/SaveProductAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.actions.file;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.dataio.dimap.DimapProductReader;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.netbeans.api.progress.BaseProgressUtils;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.io.File;
import java.lang.ref.WeakReference;
import java.text.MessageFormat;
/**
* Action which closes a selected product.
*
* @author Norman
*/
@ActionID(category = "File", id = "SaveProductAction")
@ActionRegistration(displayName = "#CTL_SaveProductActionName")
@ActionReferences({
@ActionReference(path = "Menu/File", position = 40, separatorBefore = 38),
@ActionReference(path = "Context/Product/Product", position = 90)
})
@NbBundle.Messages({"CTL_SaveProductActionName=Save Product"})
public final class SaveProductAction extends AbstractAction{
private WeakReference<ProductNode> productNodeRef;
public SaveProductAction(ProductNode productNode) {
productNodeRef = new WeakReference<>(productNode);
}
static Boolean saveProduct(Product product) {
Assert.notNull(product.getFileLocation());
final File file = product.getFileLocation();
if (file.isFile() && !file.canWrite()) {
Dialogs.showWarning(Bundle.CTL_SaveProductActionName(),
MessageFormat.format("The product\n" +
"''{0}''\n" +
"exists and cannot be overwritten, because it is read only.\n" +
"Please choose another file or remove the write protection.",
file.getPath()),
null);
return false;
}
SnapApp.getDefault().setStatusBarMessage(MessageFormat.format("Writing product ''{0}'' to {1}...", product.getDisplayName(), file));
boolean incremental = true;
WriteProductOperation operation = new WriteProductOperation(product, incremental);
BaseProgressUtils.runOffEventThreadWithProgressDialog(operation,
Bundle.CTL_SaveProductActionName(),
operation.getProgressHandle(),
true,
50,
1000);
SnapApp.getDefault().setStatusBarMessage("");
return operation.getStatus();
}
@Override
public void actionPerformed(ActionEvent e) {
execute();
}
/**
* Executes the action command.
*
* @return {@code Boolean.TRUE} on success, {@code Boolean.FALSE} on failure, or {@code null} on cancellation.
*/
public Boolean execute() {
ProductNode productNode = productNodeRef.get();
if (productNode != null && productNode.getProduct() != null) {
Product product = productNode.getProduct();
if (product != null) {
if (product.getFileLocation() != null && (product.getProductReader() == null || product.getProductReader() instanceof DimapProductReader)) {
return saveProduct(product);
} else {
// if file location not set, delegate to save-as
return new SaveProductAsAction(product).execute();
}
} else {
// reference was garbage collected, that's fine, no need to save.
return true;
}
}
return true;
}
}
| 4,271 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WriteProductOperation.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/WriteProductOperation.java | package org.esa.snap.rcp.actions.file;
import com.bc.ceres.core.Assert;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.dimap.DimapProductConstants;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNodeList;
import org.esa.snap.core.util.Debug;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.util.ProgressHandleMonitor;
import org.netbeans.api.progress.ProgressHandle;
import org.openide.util.Cancellable;
import org.openide.util.NbBundle;
import java.io.File;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.DEFAULT_VALUE_SAVE_INCREMENTAL;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.DEFAULT_VALUE_SAVE_PRODUCT_ANNOTATIONS;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.DEFAULT_VALUE_SAVE_PRODUCT_HEADERS;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.DEFAULT_VALUE_SAVE_PRODUCT_HISTORY;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.PREFERENCE_KEY_SAVE_INCREMENTAL;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.PREFERENCE_KEY_SAVE_PRODUCT_ANNOTATIONS;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.PREFERENCE_KEY_SAVE_PRODUCT_HEADERS;
import static org.esa.snap.rcp.preferences.general.WriteOptionsController.PREFERENCE_KEY_SAVE_PRODUCT_HISTORY;
/**
* @author Norman Fomferra
* @author Marco Peters
*/
@NbBundle.Messages({"CTL_WriteProductOperationName=Write Product"})
public class WriteProductOperation implements Runnable, Cancellable {
private final Product product;
private final Boolean incremental;
private final ProgressHandleMonitor pm;
private final File fileLocation;
private final String formatName;
private Boolean status;
public WriteProductOperation(Product product, Boolean incremental) {
this(product, product.getFileLocation(), DimapProductConstants.DIMAP_FORMAT_NAME, incremental);
}
public WriteProductOperation(Product product, File fileLocation, String formatName, Boolean incremental) {
Assert.notNull(product, "product");
Assert.notNull(fileLocation, "fileLocation");
Assert.notNull(formatName, "formatName");
this.product = product;
this.fileLocation = fileLocation;
this.formatName = formatName;
if (incremental != null) {
this.incremental = incremental;
} else {
this.incremental = SnapApp.getDefault().getPreferences().getBoolean(PREFERENCE_KEY_SAVE_INCREMENTAL,
DEFAULT_VALUE_SAVE_INCREMENTAL);
}
this.pm = ProgressHandleMonitor.create(Bundle.CTL_WriteProductOperationName(), this);
}
public Boolean getStatus() {
return status;
}
public ProgressHandle getProgressHandle() {
return pm.getProgressHandle();
}
@Override
public boolean cancel() {
Dialogs.Answer answer = Dialogs.requestDecision(Bundle.CTL_WriteProductOperationName(),
"Cancellation of writing may lead to an unreadable product.\n\n"
+ "Do you really want to cancel the write process?",
false, null);
return answer == Dialogs.Answer.YES;
}
@Override
public void run() {
boolean saveProductHeaders = SnapApp.getDefault().getPreferences().getBoolean(PREFERENCE_KEY_SAVE_PRODUCT_HEADERS,
DEFAULT_VALUE_SAVE_PRODUCT_HEADERS);
boolean saveProductHistory = SnapApp.getDefault().getPreferences().getBoolean(PREFERENCE_KEY_SAVE_PRODUCT_HISTORY,
DEFAULT_VALUE_SAVE_PRODUCT_HISTORY);
boolean saveADS = SnapApp.getDefault().getPreferences().getBoolean(PREFERENCE_KEY_SAVE_PRODUCT_ANNOTATIONS,
DEFAULT_VALUE_SAVE_PRODUCT_ANNOTATIONS);
MetadataElement metadataRoot = product.getMetadataRoot();
ProductNodeList<MetadataElement> metadataElementBackup = new ProductNodeList<>();
if (!saveProductHeaders) {
String[] headerNames = new String[]{
"MPH", "SPH",
"Earth_Explorer_Header", "Fixed_Header", "Variable_Header", "Specific_Product_Header",
"Global_Attributes", "GlobalAttributes", "Variable_Attributes"
};
for (String headerName : headerNames) {
MetadataElement element = metadataRoot.getElement(headerName);
metadataElementBackup.add(element);
metadataRoot.removeElement(element);
}
}
if (!saveProductHistory) {
final MetadataElement element = metadataRoot.getElement("History");
metadataElementBackup.add(element);
metadataRoot.removeElement(element);
}
if (!saveADS) {
final String[] names = metadataRoot.getElementNames();
for (final String name : names) {
if (name.endsWith("ADS") || name.endsWith("Ads") || name.endsWith("ads")) {
final MetadataElement element = metadataRoot.getElement(name);
metadataElementBackup.add(element);
metadataRoot.removeElement(element);
}
}
}
Boolean saveOk = writeProduct(product, fileLocation, formatName, incremental, pm);
if (saveOk != null && saveOk) {
product.setModified(false);
OpenProductAction.getRecentProductPaths().add(fileLocation.getPath());
} else {
if (metadataRoot != null) {
final MetadataElement[] elementsArray = new MetadataElement[metadataElementBackup.size()];
metadataElementBackup.toArray(elementsArray);
for (final MetadataElement metadataElement : elementsArray) {
metadataRoot.addElement(metadataElement);
}
}
}
status = saveOk;
}
private static Boolean writeProduct(Product product,
File file,
String formatName,
boolean incremental,
ProgressMonitor pm) {
Debug.assertNotNull(product);
try {
ProductIO.writeProduct(product, file, formatName, incremental, pm);
return !pm.isCanceled() ? true : null;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
javax.swing.SwingUtilities.invokeLater(() -> Dialogs.showError("Writing failed", e.getMessage()));
return false;
}
}
}
| 7,248 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportLegendImageAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportLegendImageAction.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.actions.file.export;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.datamodel.ImageLegend;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.param.ParamGroup;
import org.esa.snap.core.param.Parameter;
import org.esa.snap.core.util.PreferencesPropertyMap;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.SnapFileChooser;
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.awt.ActionRegistration;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.util.prefs.Preferences;
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.file.export.ExportLegendImageAction"
)
@ActionRegistration(
displayName = "#CTL_ExportLegendImageAction_MenuText",
popupText = "#CTL_ExportLegendImageAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Export/Other", position = 10),
@ActionReference(path = "Context/ProductSceneView", position = 90)
})
@NbBundle.Messages({
"CTL_ExportLegendImageAction_MenuText=Colour Legend as Image",
"CTL_ExportLegendImageAction_PopupText=Export Colour Legend as Image",
"CTL_ExportLegendImageAction_ShortDescription=Export the colour legend of the current view as an image."
})
public class ExportLegendImageAction extends AbstractExportImageAction {
private final static String[][] IMAGE_FORMAT_DESCRIPTIONS = {
BMP_FORMAT_DESCRIPTION,
PNG_FORMAT_DESCRIPTION,
JPEG_FORMAT_DESCRIPTION,
TIFF_FORMAT_DESCRIPTION,
};
private static final String HELP_ID = "exportLegendImageFile";
private static final String HORIZONTAL_STR = "Horizontal";
private static final String VERTICAL_STR = "Vertical";
private SnapFileFilter[] imageFileFilters;
private ParamGroup legendParamGroup;
private ImageLegend imageLegend;
@SuppressWarnings("FieldCanBeLocal")
private Lookup.Result<ProductSceneView> result;
public ExportLegendImageAction() {
this(Utilities.actionsGlobalContext());
}
public ExportLegendImageAction(Lookup lookup) {
super(Bundle.CTL_ExportLegendImageAction_MenuText(), HELP_ID);
putValue("popupText",Bundle.CTL_ExportLegendImageAction_PopupText());
imageFileFilters = new SnapFileFilter[IMAGE_FORMAT_DESCRIPTIONS.length];
for (int i = 0; i < IMAGE_FORMAT_DESCRIPTIONS.length; i++) {
imageFileFilters[i] = createFileFilter(IMAGE_FORMAT_DESCRIPTIONS[i]);
}
result = lookup.lookupResult(ProductSceneView.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ExportLegendImageAction(lookup);
}
@Override
public void actionPerformed(ActionEvent e) {
exportImage(imageFileFilters);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView();
boolean enabled = view != null && !view.isRGB();
setEnabled(enabled);
}
@Override
protected void configureFileChooser(SnapFileChooser fileChooser, ProductSceneView view, String imageBaseName) {
legendParamGroup = createLegendParamGroup();
final Preferences preferences = SnapApp.getDefault().getPreferences();
legendParamGroup.setParameterValues(new PreferencesPropertyMap(preferences), null);
modifyHeaderText(legendParamGroup, view.getRaster());
fileChooser.setDialogTitle(SnapApp.getDefault().getInstanceName() + " - export Colour Legend Image"); /*I18N*/
fileChooser.setCurrentFilename(imageBaseName + "_legend");
final RasterDataNode raster = view.getRaster();
imageLegend = new ImageLegend(raster.getImageInfo(), raster);
fileChooser.setAccessory(createImageLegendAccessory(
fileChooser,
legendParamGroup,
imageLegend, getHelpCtx().getHelpID()));
}
@Override
protected RenderedImage createImage(String imageFormat, ProductSceneView view) {
transferParamsToImageLegend(legendParamGroup, imageLegend);
imageLegend.setBackgroundTransparencyEnabled(isTransparencySupportedByFormat(imageFormat));
return imageLegend.createImage();
}
@Override
protected boolean isEntireImageSelected() {
return true;
}
private static ParamGroup createLegendParamGroup() {
ParamGroup paramGroup = new ParamGroup();
Parameter param = new Parameter("legend.usingHeader", Boolean.TRUE);
param.getProperties().setLabel("Show header text");
paramGroup.addParameter(param);
param = new Parameter("legend.headerText", "");
param.getProperties().setLabel("Header text");
param.getProperties().setNumCols(24);
param.getProperties().setNullValueAllowed(true);
paramGroup.addParameter(param);
param = new Parameter("legend.orientation", HORIZONTAL_STR);
param.getProperties().setLabel("Orientation");
param.getProperties().setValueSet(new String[]{HORIZONTAL_STR, VERTICAL_STR});
param.getProperties().setValueSetBound(true);
paramGroup.addParameter(param);
param = new Parameter("legend.fontSize", 14);
param.getProperties().setLabel("Font size");
param.getProperties().setMinValue(4);
param.getProperties().setMaxValue(100);
paramGroup.addParameter(param);
param = new Parameter("legend.foregroundColor", Color.black);
param.getProperties().setLabel("Foreground colour");
paramGroup.addParameter(param);
param = new Parameter("legend.backgroundColor", Color.white);
param.getProperties().setLabel("Background colour");
paramGroup.addParameter(param);
param = new Parameter("legend.backgroundTransparency", 0.0f);
param.getProperties().setLabel("Background transparency");
param.getProperties().setMinValue(0.0f);
param.getProperties().setMaxValue(1.0f);
paramGroup.addParameter(param);
param = new Parameter("legend.antialiasing", Boolean.TRUE);
param.getProperties().setLabel("Perform anti-aliasing");
paramGroup.addParameter(param);
return paramGroup;
}
private static void modifyHeaderText(ParamGroup legendParamGroup, RasterDataNode raster) {
String name = raster.getName();
String unit = raster.getUnit() != null ? raster.getUnit() : "-";
unit = unit.replace('*', ' ');
String headerText = name + " [" + unit + "]";
legendParamGroup.getParameter("legend.headerText").setValue(headerText, null);
}
private static JComponent createImageLegendAccessory(final JFileChooser fileChooser,
final ParamGroup legendParamGroup,
final ImageLegend imageLegend, String helpId) {
final JButton button = new JButton("Properties...");
button.setMnemonic('P');
button.addActionListener(e -> {
final SnapFileFilter fileFilter = (SnapFileFilter) fileChooser.getFileFilter();
final ImageLegendDialog dialog = new ImageLegendDialog(
legendParamGroup,
imageLegend,
isTransparencySupportedByFormat(fileFilter.getFormatName()), helpId);
dialog.show();
});
final JPanel accessory = new JPanel(new BorderLayout());
accessory.setBorder(new EmptyBorder(3, 3, 3, 3));
accessory.add(button, BorderLayout.NORTH);
return accessory;
}
private static void transferParamsToImageLegend(ParamGroup legendParamGroup, ImageLegend imageLegend) {
Object value;
value = legendParamGroup.getParameter("legend.usingHeader").getValue();
imageLegend.setUsingHeader((Boolean) value);
value = legendParamGroup.getParameter("legend.headerText").getValue();
imageLegend.setHeaderText((String) value);
value = legendParamGroup.getParameter("legend.orientation").getValue();
imageLegend.setOrientation(HORIZONTAL_STR.equals(value) ? ImageLegend.HORIZONTAL : ImageLegend.VERTICAL);
value = legendParamGroup.getParameter("legend.fontSize").getValue();
imageLegend.setFont(imageLegend.getFont().deriveFont(((Number) value).floatValue()));
value = legendParamGroup.getParameter("legend.backgroundColor").getValue();
imageLegend.setBackgroundColor((Color) value);
value = legendParamGroup.getParameter("legend.foregroundColor").getValue();
imageLegend.setForegroundColor((Color) value);
value = legendParamGroup.getParameter("legend.backgroundTransparency").getValue();
imageLegend.setBackgroundTransparency(((Number) value).floatValue());
value = legendParamGroup.getParameter("legend.antialiasing").getValue();
imageLegend.setAntialiasing((Boolean) value);
}
public static class ImageLegendDialog extends ModalDialog {
private ImageInfo imageInfo;
private RasterDataNode raster;
private boolean transparencyEnabled;
private ParamGroup paramGroup;
private Parameter usingHeaderParam;
private Parameter headerTextParam;
private Parameter orientationParam;
private Parameter fontSizeParam;
private Parameter backgroundColorParam;
private Parameter foregroundColorParam;
private Parameter antialiasingParam;
private Parameter backgroundTransparencyParam;
public ImageLegendDialog(ParamGroup paramGroup, ImageLegend imageLegend,
boolean transparencyEnabled, String helpId) {
super(SnapApp.getDefault().getMainFrame(), SnapApp.getDefault().getInstanceName() + " - Colour Legend Properties", ID_OK_CANCEL, helpId);
this.imageInfo = imageLegend.getImageInfo();
this.raster = imageLegend.getRaster();
this.transparencyEnabled = transparencyEnabled;
this.paramGroup = paramGroup;
initParams();
initUI();
updateUIState();
this.paramGroup.addParamChangeListener(event -> updateUIState());
}
private void updateUIState() {
boolean headerTextEnabled = (Boolean) usingHeaderParam.getValue();
headerTextParam.setUIEnabled(headerTextEnabled);
backgroundTransparencyParam.setUIEnabled(transparencyEnabled);
}
public ParamGroup getParamGroup() {
return paramGroup;
}
public void getImageLegend(ImageLegend imageLegend) {
transferParamsToImageLegend(getParamGroup(), imageLegend);
}
public ImageInfo getImageInfo() {
return imageInfo;
}
@Override
protected void onOK() {
final Preferences preferences = SnapApp.getDefault().getPreferences();
getParamGroup().getParameterValues(new PreferencesPropertyMap(preferences));
super.onOK();
}
private void initUI() {
final JButton previewButton = new JButton("Preview...");
previewButton.setMnemonic('v');
previewButton.addActionListener(e -> showPreview());
final GridBagConstraints gbc = new GridBagConstraints();
final JPanel p = GridBagUtils.createPanel();
gbc.anchor = GridBagConstraints.WEST;
gbc.fill = GridBagConstraints.NONE;
gbc.insets.top = 0;
gbc.gridy = 0;
gbc.gridwidth = 2;
p.add(usingHeaderParam.getEditor().getEditorComponent(), gbc);
gbc.gridy++;
gbc.gridwidth = 1;
p.add(headerTextParam.getEditor().getLabelComponent(), gbc);
p.add(headerTextParam.getEditor().getEditorComponent(), gbc);
gbc.gridy++;
gbc.insets.top = 10;
p.add(orientationParam.getEditor().getLabelComponent(), gbc);
p.add(orientationParam.getEditor().getEditorComponent(), gbc);
gbc.gridy++;
gbc.insets.top = 3;
p.add(fontSizeParam.getEditor().getLabelComponent(), gbc);
p.add(fontSizeParam.getEditor().getEditorComponent(), gbc);
gbc.gridy++;
gbc.insets.top = 10;
p.add(foregroundColorParam.getEditor().getLabelComponent(), gbc);
p.add(foregroundColorParam.getEditor().getEditorComponent(), gbc);
gbc.gridy++;
gbc.insets.top = 3;
p.add(backgroundColorParam.getEditor().getLabelComponent(), gbc);
p.add(backgroundColorParam.getEditor().getEditorComponent(), gbc);
gbc.gridy++;
gbc.insets.top = 3;
p.add(backgroundTransparencyParam.getEditor().getLabelComponent(), gbc);
p.add(backgroundTransparencyParam.getEditor().getEditorComponent(), gbc);
gbc.gridy++;
gbc.insets.top = 10;
gbc.gridx = 0;
gbc.anchor = GridBagConstraints.NORTHWEST;
p.add(antialiasingParam.getEditor().getEditorComponent(), gbc);
gbc.insets.top = 10;
gbc.gridx = 1;
gbc.anchor = GridBagConstraints.NORTHEAST;
p.add(previewButton, gbc);
p.setBorder(new EmptyBorder(7, 7, 7, 7));
setContent(p);
}
private void initParams() {
usingHeaderParam = paramGroup.getParameter("legend.usingHeader");
headerTextParam = paramGroup.getParameter("legend.headerText");
orientationParam = paramGroup.getParameter("legend.orientation");
fontSizeParam = paramGroup.getParameter("legend.fontSize");
foregroundColorParam = paramGroup.getParameter("legend.foregroundColor");
backgroundColorParam = paramGroup.getParameter("legend.backgroundColor");
backgroundTransparencyParam = paramGroup.getParameter("legend.backgroundTransparency");
antialiasingParam = paramGroup.getParameter("legend.antialiasing");
}
private void showPreview() {
final ImageLegend imageLegend = new ImageLegend(getImageInfo(), raster);
getImageLegend(imageLegend);
final BufferedImage image = imageLegend.createImage();
final JLabel imageDisplay = new JLabel(new ImageIcon(image));
imageDisplay.setOpaque(true);
imageDisplay.addMouseListener(new MouseAdapter() {
// Both events (releases & pressed) must be checked, otherwise it won't work on all
// platforms
/**
* Invoked when a mouse button has been released on a component.
*/
@Override
public void mouseReleased(MouseEvent e) {
// On Windows
showPopup(e, image, imageDisplay);
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
@Override
public void mousePressed(MouseEvent e) {
// On Linux
// todo - clipboard does not work on linux.
// todo - better not to show popup until it works correctly
// showPopup(e, image, imageDisplay);
}
});
final ModalDialog dialog = new ModalDialog(getParent(),
SnapApp.getDefault().getInstanceName() + " - Colour Legend Preview",
imageDisplay,
ID_OK, null);
dialog.getJDialog().setResizable(false);
dialog.show();
}
private static void showPopup(final MouseEvent e, final BufferedImage image, final JComponent imageDisplay) {
if (e.isPopupTrigger()) {
final JPopupMenu popupMenu = new JPopupMenu();
final JMenuItem menuItem = new JMenuItem("Copy image to clipboard");
menuItem.addActionListener(e1 -> SystemUtils.copyToClipboard(image));
popupMenu.add(menuItem);
popupMenu.show(imageDisplay, e.getX(), e.getY());
}
}
}
}
| 18,409 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportKmzFileAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportKmzFileAction.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.actions.file.export;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageEncoder;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.dataop.maptransf.IdentityTransformDescriptor;
import org.esa.snap.core.dataop.maptransf.MapTransformDescriptor;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.runtime.Config;
import org.esa.snap.ui.SnapFileChooser;
import org.esa.snap.ui.product.ProductSceneView;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import static org.esa.snap.rcp.actions.file.export.AbstractExportImageAction.IMAGE_EXPORT_DIR_PREFERENCES_KEY;
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.file.export.ExportKmzFileAction"
)
@ActionRegistration(
displayName = "#CTL_ExportKmzFileAction_MenuText",
popupText = "#CTL_ExportKmzFileAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Export/Other", position = 85),
@ActionReference(path = "Context/ProductSceneView", position = 60)
})
@NbBundle.Messages({
"CTL_ExportKmzFileAction_MenuText=View as Google Earth KMZ",
"CTL_ExportKmzFileAction_PopupText=Export View as Google Earth KMZ",
"CTL_ExportKmzFileAction_ShortDescription=Export View as Google Earth KMZ."
})
public class ExportKmzFileAction extends AbstractAction implements HelpCtx.Provider, ContextAwareAction, LookupListener {
private static final String OVERLAY_KML = "overlay.kml";
private static final String OVERLAY_PNG = "overlay.png";
private static final String IMAGE_TYPE = "PNG";
private static final String LEGEND_PNG = "legend.png";
private static final String[] KMZ_FORMAT_DESCRIPTION = {"KMZ", "kmz", "KMZ - Google Earth File Format"};
private static final String HELP_ID = "exportKmzFile";
@SuppressWarnings("FieldCanBeLocal")
private final Lookup.Result<ProductSceneView> result;
public ExportKmzFileAction() {
this(Utilities.actionsGlobalContext());
}
public ExportKmzFileAction(Lookup lookup) {
super(Bundle.CTL_ExportKmzFileAction_MenuText());
putValue("popupText", Bundle.CTL_ExportKmzFileAction_PopupText());
result = lookup.lookupResult(ProductSceneView.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
static String getLastDir() {
return Config.instance().load().preferences().get(
IMAGE_EXPORT_DIR_PREFERENCES_KEY,
SystemUtils.getUserHomeDir().getPath());
}
static void setLastDir(File currentDirectory) {
Config.instance().load().preferences().put(
IMAGE_EXPORT_DIR_PREFERENCES_KEY,
currentDirectory.getPath());
}
private static RenderedImage createImageLegend(RasterDataNode raster) {
ImageLegend imageLegend = initImageLegend(raster);
return imageLegend.createImage();
}
private static String formatKML(ProductSceneView view, String imageName) {
final RasterDataNode raster = view.getRaster();
final Product product = raster.getProduct();
final GeoCoding geoCoding = raster.getGeoCoding();
final PixelPos upperLeftPP = new PixelPos(0, 0);
final PixelPos lowerRightPP = new PixelPos(product.getSceneRasterWidth(),
product.getSceneRasterHeight());
final GeoPos upperLeftGP = geoCoding.getGeoPos(upperLeftPP, null);
final GeoPos lowerRightGP = geoCoding.getGeoPos(lowerRightPP, null);
double eastLon = lowerRightGP.getLon();
if (geoCoding.isCrossingMeridianAt180()) {
eastLon += 360;
}
String pinKml = "";
ProductNodeGroup<Placemark> pinGroup = product.getPinGroup();
Placemark[] pins = pinGroup.toArray(new Placemark[pinGroup.getNodeCount()]);
for (Placemark placemark : pins) {
GeoPos geoPos = placemark.getGeoPos();
if (geoPos != null && product.containsPixel(placemark.getPixelPos())) {
pinKml += String.format(
"<Placemark>\n"
+ " <name>%s</name>\n"
+ " <Point>\n"
+ " <coordinates>%f,%f,0</coordinates>\n"
+ " </Point>\n"
+ "</Placemark>\n",
placemark.getLabel(),
geoPos.lon,
geoPos.lat);
}
}
String name;
String description;
String legendKml = "";
if (view.isRGB()) {
name = "RGB";
description = view.getSceneName() + "\n" + product.getName();
} else {
name = raster.getName();
description = raster.getDescription() + "\n" + product.getName();
legendKml = " <ScreenOverlay>\n"
+ " <name>Legend</name>\n"
+ " <Icon>\n"
+ " <href>legend.png</href>\n"
+ " </Icon>\n"
+ " <overlayXY x=\"0\" y=\"1\" xunits=\"fraction\" yunits=\"fraction\" />\n"
+ " <screenXY x=\"0\" y=\"1\" xunits=\"fraction\" yunits=\"fraction\" />\n"
+ " </ScreenOverlay>\n";
}
return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<kml xmlns=\"http://earth.google.com/kml/2.0\">\n"
+ "<Document>\n"
+ " <name>" + name + "</name>\n"
+ " <description>" + description + "</description>\n"
+ " <GroundOverlay>\n"
+ " <name>Raster data</name>\n"
+ " <LatLonBox>\n"
+ " <north>" + upperLeftGP.getLat() + "</north>\n"
+ " <south>" + lowerRightGP.getLat() + "</south>\n"
+ " <east>" + eastLon + "</east>\n"
+ " <west>" + upperLeftGP.getLon() + "</west>\n"
+ " </LatLonBox>\n"
+ " <Icon>\n"
+ " <href>" + imageName + "</href>\n"
+ " </Icon>\n"
+ " </GroundOverlay>\n"
+ legendKml
+ pinKml
+ "</Document>\n"
+ "</kml>\n";
}
private static ImageLegend initImageLegend(RasterDataNode raster) {
ImageLegend imageLegend = new ImageLegend(raster.getImageInfo(), raster);
imageLegend.setHeaderText(getLegendHeaderText(raster));
imageLegend.setOrientation(ImageLegend.VERTICAL);
imageLegend.setBackgroundTransparency(0.0f);
imageLegend.setBackgroundTransparencyEnabled(true);
imageLegend.setAntialiasing(true);
return imageLegend;
}
private static String getLegendHeaderText(RasterDataNode raster) {
String unit = raster.getUnit() != null ? raster.getUnit() : "-";
unit = unit.replace('*', ' ');
return "(" + unit + ")";
}
@Override
public void actionPerformed(ActionEvent e) {
ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView();
final GeoCoding geoCoding = view.getProduct().getSceneGeoCoding();
boolean isGeographic = false;
if (geoCoding instanceof MapGeoCoding) {
MapGeoCoding mapGeoCoding = (MapGeoCoding) geoCoding;
MapTransformDescriptor transformDescriptor = mapGeoCoding.getMapInfo()
.getMapProjection().getMapTransform().getDescriptor();
String typeID = transformDescriptor.getTypeID();
if (typeID.equals(IdentityTransformDescriptor.TYPE_ID)) {
isGeographic = true;
}
} else if (geoCoding instanceof CrsGeoCoding) {
isGeographic = CRS.equalsIgnoreMetadata(geoCoding.getMapCRS(), DefaultGeographicCRS.WGS84);
}
if (isGeographic) {
exportImage(view);
} else {
String message = "Product must be in ''Geographic Lat/Lon'' projection.";
Dialogs.showInformation(message, null);
}
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ExportKmzFileAction(lookup);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnabled(SnapApp.getDefault().getSelectedProductSceneView() != null);
}
private void exportImage(ProductSceneView sceneView) {
SnapApp snapApp = SnapApp.getDefault();
final String lastDir = getLastDir();
final File currentDir = new File(lastDir);
final SnapFileChooser fileChooser = new SnapFileChooser();
HelpCtx.setHelpIDString(fileChooser, getHelpCtx().getHelpID());
SnapFileFilter kmzFileFilter = new SnapFileFilter(KMZ_FORMAT_DESCRIPTION[0],
KMZ_FORMAT_DESCRIPTION[1],
KMZ_FORMAT_DESCRIPTION[2]);
fileChooser.setCurrentDirectory(currentDir);
fileChooser.addChoosableFileFilter(kmzFileFilter);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setDialogTitle(snapApp.getInstanceName() + " - " + "export KMZ");
final String currentFilename = sceneView.isRGB() ? "RGB" : sceneView.getRaster().getName();
fileChooser.setCurrentFilename(currentFilename);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
Dimension fileChooserSize = fileChooser.getPreferredSize();
if (fileChooserSize != null) {
fileChooser.setPreferredSize(new Dimension(
fileChooserSize.width + 120, fileChooserSize.height));
} else {
fileChooser.setPreferredSize(new Dimension(512, 256));
}
int result = fileChooser.showSaveDialog(snapApp.getMainFrame());
File file = fileChooser.getSelectedFile();
fileChooser.addPropertyChangeListener(evt -> {
// @todo never comes here, why?
Debug.trace(evt.toString());
});
final File currentDirectory = fileChooser.getCurrentDirectory();
if (currentDirectory != null) {
setLastDir(currentDirectory);
}
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
if (file == null || file.getName().isEmpty()) {
return;
}
if (!Dialogs.requestOverwriteDecision("h", file)) {
return;
}
final SaveKMLSwingWorker worker = new SaveKMLSwingWorker(snapApp, "Save KMZ", sceneView, file);
worker.executeWithBlocking();
}
private static class SaveKMLSwingWorker extends ProgressMonitorSwingWorker {
private final SnapApp snapApp;
private final ProductSceneView view;
private final File file;
SaveKMLSwingWorker(SnapApp snapApp, String message, ProductSceneView view, File file) {
super(snapApp.getMainFrame(), message);
this.snapApp = snapApp;
this.view = view;
this.file = file;
}
@Override
protected Object doInBackground(ProgressMonitor pm) throws Exception {
try {
final String message = String.format("Saving image as %s...", file.getPath());
pm.beginTask(message, view.isRGB() ? 4 : 3);
snapApp.setStatusBarMessage(message);
snapApp.getMainFrame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final Dimension dimension = new Dimension(view.getProduct().getSceneRasterWidth(),
view.getProduct().getSceneRasterHeight());
RenderedImage image = ExportImageAction.createImage(view, true, dimension, true, true);
pm.worked(1);
try (ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(file))) {
outStream.putNextEntry(new ZipEntry(OVERLAY_KML));
final String kmlContent = formatKML(view, OVERLAY_PNG);
outStream.write(kmlContent.getBytes());
pm.worked(1);
outStream.putNextEntry(new ZipEntry(OVERLAY_PNG));
ImageEncoder encoder = ImageCodec.createImageEncoder(IMAGE_TYPE, outStream, null);
encoder.encode(image);
pm.worked(1);
if (!view.isRGB()) {
outStream.putNextEntry(new ZipEntry(LEGEND_PNG));
encoder = ImageCodec.createImageEncoder(IMAGE_TYPE, outStream, null);
encoder.encode(createImageLegend(view.getRaster()));
pm.worked(1);
}
}
} catch (OutOfMemoryError ignored) {
Dialogs.showOutOfMemoryError("The image could not be exported."); /*I18N*/
} catch (Throwable e) {
snapApp.handleError("The image could not be exported", e);
} finally {
snapApp.getMainFrame().setCursor(Cursor.getDefaultCursor());
snapApp.setStatusBarMessage("");
pm.done();
}
return null;
}
}
}
| 14,897 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportMetadataAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportMetadataAction.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.actions.file.export;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.DialogProgressMonitor;
import org.esa.snap.core.datamodel.MetadataAttribute;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.metadata.MetadataViewTopComponent;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.SelectExportMethodDialog;
import org.esa.snap.ui.UIUtils;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import java.awt.Dialog;
import java.awt.event.ActionEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.MessageFormat;
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.file.export.ExportMetadataAction"
)
@ActionRegistration(
displayName = "#CTL_ ExportMetadataAction_MenuText",
popupText = "#CTL_ ExportMetadataAction_PopupText",
lazy = false
)
@ActionReference(path = "Menu/File/Export/Other", position = 60)
@NbBundle.Messages({
"CTL_ExportMetadataAction_MenuText=Product Metadata",
"CTL_ExportMetadataAction_PopupText=Export Product Metadata...",
"CTL_ExportMetadataAction_HelpID=exportMetadata",
"CTL_ExportMetadataAction_ShortDescription=Export the currently displayed metadata as tab-separated text."
})
public class ExportMetadataAction extends AbstractAction implements HelpCtx.Provider, LookupListener, ContextAwareAction {
private static final String ERR_MSG_BASE = "Metadata could not be exported:\n";
private static final String DLG_TITLE = "Export Product Metadata";
private final Lookup.Result<MetadataElement> result;
private final Lookup lookup;
private MetadataElement productMetadata;
public ExportMetadataAction() {
this(Utilities.actionsGlobalContext());
}
public ExportMetadataAction(Lookup lookup) {
super(Bundle.CTL_ExportMetadataAction_MenuText());
this.lookup = lookup;
result = lookup.lookupResult(MetadataElement.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
private static String getWindowTitle() {
return SnapApp.getDefault().getInstanceName() + " - " + DLG_TITLE;
}
/**
* Opens a modal file chooser dialog that prompts the user to select the output file name.
*
* @param defaultFileName The default file name.
* @return The selected file, {@code null} means "Cancel".
*/
private static File promptForFile(String defaultFileName) {
// Loop while the user does not want to overwrite a selected, existing file
// or if the user presses "Cancel"
File file = null;
while (file == null) {
file = Dialogs.requestFileForSave(DLG_TITLE,
false,
null,
".txt",
defaultFileName, null,
"exportMetadata.lastDir");
if (file == null) {
return null; // Cancel
} else if (file.exists()) {
int status = JOptionPane.showConfirmDialog(SnapApp.getDefault().getMainFrame(),
"The file '" + file + "' already exists.\n" + /*I18N*/
"Overwrite it?",
MessageFormat.format("{0} - {1}", SnapApp.getDefault().getInstanceName(), DLG_TITLE),
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.WARNING_MESSAGE);
if (status == JOptionPane.CANCEL_OPTION) {
return null; // Cancel
} else if (status == JOptionPane.NO_OPTION) {
file = null; // No, do not overwrite, let user select other file
}
}
}
return file;
}
/**
* Invoked when a command action is performed.
*
* @param event the command event
*/
@Override
public void actionPerformed(ActionEvent event) {
exportMetadata();
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(Bundle.CTL_ExportMetadataAction_MenuText());
}
/////////////////////////////////////////////////////////////////////////
// Private implementations for the "Export Metadata" command
/////////////////////////////////////////////////////////////////////////
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new ExportMetadataAction(actionContext);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
MetadataElement metadataElement = lookup.lookup(MetadataElement.class);
setEnabled(metadataElement != null);
}
private void exportMetadata() {
productMetadata = lookup.lookup(MetadataElement.class);
final String msgText = "How do you want to export the metadata?\n" +
productMetadata.getName() + "Element will be exported.\n";
final int method = SelectExportMethodDialog.run(SnapApp.getDefault().getMainFrame(), getWindowTitle(),
msgText, getHelpCtx().getHelpID());
final PrintWriter out;
final StringBuffer clipboardText;
final int initialBufferSize = 256000;
if (method == SelectExportMethodDialog.EXPORT_TO_CLIPBOARD) {
// Write into string buffer
final StringWriter stringWriter = new StringWriter(initialBufferSize);
out = new PrintWriter(stringWriter);
clipboardText = stringWriter.getBuffer();
} else if (method == SelectExportMethodDialog.EXPORT_TO_FILE) {
// Write into file, get file from user
MetadataViewTopComponent metadataViewTopComponent = new MetadataViewTopComponent(productMetadata);
final File file = promptForFile(createDefaultFileName(metadataViewTopComponent));
if (file == null) {
return; // Cancel
}
final FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
} catch (IOException e) {
Dialogs.showError(DLG_TITLE,
ERR_MSG_BASE + "Failed to create file '" + file + "':\n" + e.getMessage());
return; // Error
}
out = new PrintWriter(new BufferedWriter(fileWriter, initialBufferSize));
clipboardText = null;
} else {
return; // Cancel
}
// Create a progress monitor and adds them to the progress controller pool in order to show export progress
// Create a new swing worker instance (as instance of an anonymous class).
// When the swing worker's start() method is called, a new separate thread is started.
// The swing worker's construct() method is executed in that thread, so that
// VISAT can keep on handling user events.
//
final SwingWorker swingWorker = new SwingWorker<Exception, Object>() {
@Override
protected Exception doInBackground() throws Exception {
boolean success;
Exception returnValue = null;
try {
ProgressMonitor pm = new DialogProgressMonitor(SnapApp.getDefault().getMainFrame(), DLG_TITLE,
Dialog.ModalityType.APPLICATION_MODAL);
final MetadataExporter exporter = new MetadataExporter(productMetadata);
success = exporter.exportMetadata(out, pm);
if (success && clipboardText != null) {
SystemUtils.copyToClipboard(clipboardText.toString());
clipboardText.setLength(0);
}
} catch (Exception e) {
returnValue = e;
} finally {
out.close();
}
return returnValue;
}
/**
* Called on the event dispatching thread (not on the worker thread) after the {@code construct} method
* has returned.
*/
@Override
public void done() {
// clear status bar
SnapApp.getDefault().setStatusBarMessage("");
// show default-cursor
UIUtils.setRootFrameDefaultCursor(SnapApp.getDefault().getMainFrame());
// On error, show error message
Exception exception;
try {
exception = get();
} catch (Exception e) {
exception = e;
}
if (exception != null) {
Dialogs.showError(DLG_TITLE, ERR_MSG_BASE + exception.getMessage());
}
}
};
// show wait-cursor
// show message in status bar
SnapApp.getDefault().setStatusBarMessage("Exporting Product Metadata..."); /*I18N*/
// Start separate worker thread.
swingWorker.execute();
}
private String createDefaultFileName(MetadataViewTopComponent productMetadataView) {
return FileUtils.getFilenameWithoutExtension(productMetadataView.getDocument().getProduct().getName()) + "_" +
productMetadata.getName() +
".txt";
}
private static class MetadataExporter {
private final MetadataElement rootElement;
private MetadataExporter(MetadataElement rootElement) {
this.rootElement = rootElement;
}
public boolean exportMetadata(final PrintWriter out, ProgressMonitor pm) {
pm.beginTask("Export Metadata", 1);
try {
writeHeaderLine(out);
writeAttributes(out, rootElement);
pm.worked(1);
} finally {
pm.done();
}
return true;
}
private void writeHeaderLine(final PrintWriter out) {
out.print("Value\t");
out.print("Type\t");
out.print("Unit\t");
out.print("Description\t\n");
}
private void writeAttributes(PrintWriter out, MetadataElement element) {
final MetadataAttribute[] attributes = element.getAttributes();
for (MetadataAttribute attribute : attributes) {
out.print(createAttributeName(attribute) + "\t");
out.print(attribute.getData().getElemString() + "\t");
out.print(attribute.getUnit() + "\t");
out.print(attribute.getDescription() + "\t\n");
}
final MetadataElement[] subElements = element.getElements();
for (MetadataElement subElement : subElements) {
writeAttributes(out, subElement);
}
}
private String createAttributeName(MetadataAttribute attribute) {
StringBuilder sb = new StringBuilder();
MetadataElement metadataElement = attribute.getParentElement();
if (metadataElement != null) {
prependParentName(metadataElement, sb);
}
sb.append(attribute.getName());
return sb.toString();
}
private void prependParentName(MetadataElement element, StringBuilder sb) {
final MetadataElement owner = element.getParentElement();
if (owner != null) {
if (owner != rootElement) {
prependParentName(owner, sb);
} else if (owner.getName() != null) {
sb.insert(0, owner.getName()).append(".");
}
}
if (element.getName() != null) {
sb.append(element.getName()).append(".");
}
}
}
}
| 13,683 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportEnviGcpFileAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportEnviGcpFileAction.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.actions.file.export;
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.core.datamodel.ProductNode;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.runtime.Config;
import org.esa.snap.ui.SnapFileChooser;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.*;
/**
* This actions exports ground control points of the selected product in a ENVI format.
*/
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.file.export.ExportEnviGcpFileAction"
)
@ActionRegistration(
displayName = "#CTL_ExportEnviGcpFileAction_MenuText",
popupText = "#CTL_ExportEnviGcpFileAction_PopupText",
lazy = false
)
@ActionReference(path = "Menu/File/Export/Other", position = 30)
@NbBundle.Messages({
"CTL_ExportEnviGcpFileAction_MenuText=Geo-Coding as ENVI GCP File",
"CTL_ExportEnviGcpFileAction_PopupText=Export Geo-Coding as ENVI GCP File",
"CTL_ExportEnviGcpFileAction_DialogTitle=Export ENVI Ground Control Points",
"CTL_ExportEnviGcpFileAction_ShortDescription=Export an ENVI GCP (ground control points) file for image registration"
})
public class ExportEnviGcpFileAction extends AbstractAction implements LookupListener, ContextAwareAction, HelpCtx.Provider {
private static final String GCP_FILE_DESCRIPTION = "ENVI Ground Control Points";
private static final String GCP_FILE_EXTENSION = ".pts";
private static final String GCP_LINE_SEPARATOR = System.getProperty("line.separator");
private static final String GCP_EXPORT_DIR_PREFERENCES_KEY = "user.gcp.export.dir";
private static final String HELP_ID = "exportEnviGcpFile";
private final Lookup.Result<ProductNode> result;
public ExportEnviGcpFileAction() {
this(Utilities.actionsGlobalContext());
}
public ExportEnviGcpFileAction(Lookup lookup) {
super(Bundle.CTL_ExportEnviGcpFileAction_MenuText());
result = lookup.lookupResult(ProductNode.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ExportEnviGcpFileAction(lookup);
}
@Override
public void actionPerformed(ActionEvent e) {
exportGroundControlPoints();
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnabled(SnapApp.getDefault().getSelectedProduct(AUTO) != null);
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
private void exportGroundControlPoints() {
SnapApp snapApp = SnapApp.getDefault();
final Product product = snapApp.getSelectedProduct(AUTO);
if (product == null) {
return;
}
JFileChooser fileChooser = createFileChooser();
int result = fileChooser.showSaveDialog(snapApp.getMainFrame());
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
File file = fileChooser.getSelectedFile();
if (file == null || file.getName().equals("")) {
return;
}
final File absoluteFile = FileUtils.ensureExtension(file.getAbsoluteFile(), GCP_FILE_EXTENSION);
String lastDirPath = absoluteFile.getParent();
Config.instance().load().preferences().put(GCP_EXPORT_DIR_PREFERENCES_KEY, lastDirPath);
final GeoCoding geoCoding = product.getSceneGeoCoding();
if (geoCoding == null) {
return;
}
final Boolean decision = Dialogs.requestOverwriteDecision(Bundle.CTL_ExportEnviGcpFileAction_DialogTitle(), absoluteFile);
if (decision == null || !decision) {
return;
}
if (absoluteFile.exists()) {
absoluteFile.delete();
}
try (FileWriter writer = new FileWriter(absoluteFile)) {
writer.write(createLineString("; ENVI Registration GCP File"));
final int width = product.getSceneRasterWidth();
final int height = product.getSceneRasterHeight();
final int resolution = Config.instance().load().preferences().getInt("gcp.resolution", 112);
final int gcpWidth = Math.max(width / resolution + 1, 2); //2 minimum
final int gcpHeight = Math.max(height / resolution + 1, 2);//2 minimum
final float xMultiplier = 1f * (width - 1) / (gcpWidth - 1);
final float yMultiplier = 1f * (height - 1) / (gcpHeight - 1);
final PixelPos pixelPos = new PixelPos();
final GeoPos geoPos = new GeoPos();
for (int y = 0; y < gcpHeight; y++) {
for (int x = 0; x < gcpWidth; x++) {
final float imageX = xMultiplier * x;
final float imageY = yMultiplier * y;
pixelPos.x = imageX + 0.5f;
pixelPos.y = imageY + 0.5f;
geoCoding.getGeoPos(pixelPos, geoPos);
final double mapX = geoPos.lon; //longitude
final double mapY = geoPos.lat; //latitude
writer.write(createLineString(mapX, mapY,
pixelPos.x + 1,
// + 1 because ENVI uses a one-based pixel co-ordinate system
pixelPos.y + 1));
}
}
} catch (IOException e) {
Dialogs.showInformation(Bundle.CTL_ExportEnviGcpFileAction_DialogTitle(),
"An I/O error occurred:\n" + e.getMessage());
}
}
private static String createLineString(final String str) {
return str.concat(GCP_LINE_SEPARATOR);
}
private static String createLineString(final double mapX, final double mapY, final double imageX, final double imageY) {
return "" + mapX + "\t" + mapY + "\t" + imageX + "\t" + imageY + GCP_LINE_SEPARATOR;
}
private JFileChooser createFileChooser() {
String lastDirPath = Config.instance().load().preferences().get(GCP_EXPORT_DIR_PREFERENCES_KEY,
SystemUtils.getUserHomeDir().getPath());
SnapFileChooser fileChooser = new SnapFileChooser();
HelpCtx.setHelpIDString(fileChooser, getHelpCtx().getHelpID());
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setCurrentDirectory(new File(lastDirPath));
fileChooser.setFileFilter(
new SnapFileFilter(GCP_FILE_DESCRIPTION, GCP_FILE_EXTENSION, GCP_FILE_DESCRIPTION));
fileChooser.setDialogTitle(Bundle.CTL_ExportEnviGcpFileAction_DialogTitle());
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
return fileChooser;
}
}
| 8,529 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportGeometryAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportGeometryAction.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.actions.file.export;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.locationtech.jts.geom.Geometry;
import org.esa.snap.core.datamodel.CrsGeoCoding;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.UIUtils;
import org.geotools.data.DefaultTransaction;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.data.shapefile.ShapefileDataStore;
import org.geotools.data.shapefile.ShapefileDataStoreFactory;
import org.geotools.data.simple.SimpleFeatureCollection;
import org.geotools.data.simple.SimpleFeatureSource;
import org.geotools.data.simple.SimpleFeatureStore;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.FeatureTypes;
import org.geotools.feature.SchemaException;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.GeometryCoordinateSequenceTransformer;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.feature.type.AttributeDescriptor;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.SwingWorker;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.file.export.ExportGeometryAction"
)
@ActionRegistration(
displayName = "#CTL_ExportGeometryAction_MenuText",
popupText = "#CTL_ExportGeometryAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Export/Other", position = 40),
@ActionReference(path = "Menu/Vector/Export"),
@ActionReference(path = "Context/Product/VectorDataNode", position = 208)
})
@NbBundle.Messages({
"CTL_ExportGeometryAction_MenuText=Geometry as Shape file",
"CTL_ExportGeometryAction_PopupText=Export Geometry as Shape file",
"CTL_ExportGeometryAction_DialogTitle=Export Geometry as ESRI Shapefile",
"CTL_ExportGeometryAction_ShortDescription=Exports the currently selected geometry as ESRI Shapefile."
})
public class ExportGeometryAction extends AbstractAction implements ContextAwareAction, LookupListener, HelpCtx.Provider {
private static final String ESRI_SHAPEFILE = "ESRI Shapefile";
private static final String FILE_EXTENSION_SHAPEFILE = ".shp";
private static final String HELP_ID = "exportShapefile";
@SuppressWarnings("FieldCanBeLocal")
// If converted to local the result gets garbage collected and the listener is not informed anymore
private final Lookup.Result<VectorDataNode> result;
private final Lookup lookup;
private VectorDataNode vectorDataNode;
@SuppressWarnings("unused")
public ExportGeometryAction() {
this(Utilities.actionsGlobalContext());
}
public ExportGeometryAction(Lookup lookup) {
super(Bundle.CTL_ExportGeometryAction_MenuText());
this.lookup = lookup;
result = lookup.lookupResult(VectorDataNode.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
vectorDataNode = lookup.lookup(VectorDataNode.class);
setEnabled(vectorDataNode != null);
}
/*
* Opens a modal file chooser dialog that prompts the user to select the output file name.
*
* @param visatApp the VISAT application
* @return the selected file, <code>null</code> means "Cancel"
*/
private static File promptForFile(String defaultFileName) {
return Dialogs.requestFileForSave(Bundle.CTL_ExportGeometryAction_DialogTitle(), false,
new SnapFileFilter(ESRI_SHAPEFILE, FILE_EXTENSION_SHAPEFILE, ESRI_SHAPEFILE),
FILE_EXTENSION_SHAPEFILE,
defaultFileName,
null,
"exportVectorDataNode.lastDir");
}
/////////////////////////////////////////////////////////////////////////
// Private implementations for the "export Mask Pixels" command
/////////////////////////////////////////////////////////////////////////
private static void exportVectorDataNode(VectorDataNode vectorNode, File file, ProgressMonitor pm) throws Exception {
Map<Class<?>, List<SimpleFeature>> featureListMap = createGeometryToFeaturesListMap(vectorNode);
if (featureListMap.size() > 1) {
final String msg = "The selected geometry contains different types of shapes.\n" +
"Each type of shape will be exported as a separate shapefile.";
Dialogs.showInformation(Bundle.CTL_ExportGeometryAction_DialogTitle(),
msg, ExportGeometryAction.class.getName() + ".exportInfo");
}
Set<Map.Entry<Class<?>, List<SimpleFeature>>> entries = featureListMap.entrySet();
pm.beginTask("Writing ESRI Shapefiles...", featureListMap.size());
try {
for (Map.Entry<Class<?>, List<SimpleFeature>> entry : entries) {
writeEsriShapefile(entry.getKey(), entry.getValue(), file);
pm.worked(1);
}
} finally {
pm.done();
}
}
static void writeEsriShapefile(Class<?> geomType, List<SimpleFeature> features, File file) throws IOException {
String geomName = geomType.getSimpleName();
String basename = file.getName();
if (basename.endsWith(FILE_EXTENSION_SHAPEFILE)) {
basename = basename.substring(0, basename.length() - 4);
}
File file1 = new File(file.getParentFile(), basename + "_" + geomName + FILE_EXTENSION_SHAPEFILE);
SimpleFeature simpleFeature = features.get(0);
SimpleFeatureType simpleFeatureType = changeGeometryType(simpleFeature.getType(), geomType);
ShapefileDataStoreFactory factory = new ShapefileDataStoreFactory();
Map<String, Serializable> map = Collections.singletonMap("url", file1.toURI().toURL());
ShapefileDataStore dataStore = (ShapefileDataStore) factory.createNewDataStore(map);
dataStore.createSchema(simpleFeatureType);
String typeName = dataStore.getTypeNames()[0];
SimpleFeatureSource featureSource = dataStore.getFeatureSource(typeName);
DefaultTransaction transaction = new DefaultTransaction("X");
if (featureSource instanceof SimpleFeatureStore) {
SimpleFeatureStore featureStore = (SimpleFeatureStore) featureSource;
SimpleFeatureCollection collection = new ListFeatureCollection(simpleFeatureType, features);
featureStore.setTransaction(transaction);
// I'm not sure why the next line is necessary (mp/20170627)
// Without it is not working, the wrong feature type is used for writing
// But it is not mentioned in the tutorials
dataStore.getEntry(featureSource.getName()).getState(transaction).setFeatureType(simpleFeatureType);
try {
featureStore.addFeatures(collection);
transaction.commit();
} catch (Exception problem) {
transaction.rollback();
throw new IOException(problem);
} finally {
transaction.close();
}
} else {
throw new IOException(typeName + " does not support read/write access");
}
}
private static Map<Class<?>, List<SimpleFeature>> createGeometryToFeaturesListMap(VectorDataNode vectorNode) throws TransformException,
SchemaException {
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = vectorNode.getFeatureCollection();
CoordinateReferenceSystem crs = vectorNode.getFeatureType().getCoordinateReferenceSystem();
if (crs == null) { // for pins and GCPs crs is null
crs = vectorNode.getProduct().getSceneCRS();
}
final CoordinateReferenceSystem modelCrs;
if (vectorNode.getProduct().getSceneGeoCoding() instanceof CrsGeoCoding) {
modelCrs = vectorNode.getProduct().getSceneCRS();
} else {
modelCrs = DefaultGeographicCRS.WGS84;
}
// Not using ReprojectingFeatureCollection - it is reprojecting all geometries of a feature
// but we want to reproject the default geometry only
GeometryCoordinateSequenceTransformer transformer = createTransformer(crs, modelCrs);
Map<Class<?>, List<SimpleFeature>> featureListMap = new HashMap<>();
final FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
// The schema needs to be reprojected. We need to build a new feature be cause we can't change the schema.
// It is necessary to have this reprojected schema, because otherwise the shapefile is not correctly georeferenced.
SimpleFeatureType schema = featureCollection.getSchema();
SimpleFeatureType transformedSchema = FeatureTypes.transform(schema, modelCrs);
while (featureIterator.hasNext()) {
SimpleFeature feature = featureIterator.next();
Object defaultGeometry = feature.getDefaultGeometry();
feature.setDefaultGeometry(transformer.transform((Geometry) defaultGeometry));
Class<?> geometryType = defaultGeometry.getClass();
List<SimpleFeature> featureList = featureListMap.computeIfAbsent(geometryType, k -> new ArrayList<>());
SimpleFeature exportFeature = SimpleFeatureBuilder.build(transformedSchema, feature.getAttributes(), feature.getID());
featureList.add(exportFeature);
}
return featureListMap;
}
private static GeometryCoordinateSequenceTransformer createTransformer(CoordinateReferenceSystem crs, CoordinateReferenceSystem modelCrs) {
GeometryCoordinateSequenceTransformer transformer = new GeometryCoordinateSequenceTransformer();
try {
MathTransform reprojTransform = CRS.findMathTransform(crs, modelCrs, true);
transformer.setMathTransform(reprojTransform);
return transformer;
} catch (FactoryException e) {
throw new IllegalStateException("Could not create math transform", e);
}
}
static SimpleFeatureType changeGeometryType(SimpleFeatureType original, Class<?> geometryType) {
SimpleFeatureTypeBuilder sftb = new SimpleFeatureTypeBuilder();
sftb.setCRS(original.getCoordinateReferenceSystem());
sftb.setDefaultGeometry(original.getGeometryDescriptor().getLocalName());
boolean defaultGeometryAdded = false;
for (AttributeDescriptor descriptor : original.getAttributeDescriptors()) {
if (original.getGeometryDescriptor().getLocalName().equals(descriptor.getLocalName())) {
sftb.add(descriptor.getLocalName(), geometryType);
defaultGeometryAdded = true;
}else {
sftb.add(descriptor);
}
}
if(!defaultGeometryAdded) {
sftb.add(original.getGeometryDescriptor().getLocalName(), geometryType);
}
sftb.setName("FT_" + geometryType.getSimpleName());
return sftb.buildFeatureType();
}
@Override
public void actionPerformed(ActionEvent e) {
exportVectorDataNode();
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new ExportGeometryAction(actionContext);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
vectorDataNode = lookup.lookup(VectorDataNode.class);
setEnabled(vectorDataNode != null);
}
/**
* Performs the actual "export Mask Pixels" command.
*/
private void exportVectorDataNode() {
SnapApp snapApp = SnapApp.getDefault();
if (vectorDataNode.getFeatureCollection().isEmpty()) {
Dialogs.showInformation(Bundle.CTL_ExportGeometryAction_DialogTitle(),
"The selected geometry is empty. Nothing to export.", null);
return;
}
final File file = promptForFile(vectorDataNode.getName());
if (file == null) {
return;
}
final SwingWorker<Exception, Object> swingWorker = new ExportVectorNodeSwingWorker(snapApp, vectorDataNode, file);
UIUtils.setRootFrameWaitCursor(snapApp.getMainFrame());
snapApp.setStatusBarMessage("Exporting Geometry...");
swingWorker.execute();
}
private static class ExportVectorNodeSwingWorker extends ProgressMonitorSwingWorker<Exception, Object> {
private final SnapApp snapApp;
private final VectorDataNode vectorDataNode;
private final File file;
private ExportVectorNodeSwingWorker(SnapApp snapApp, VectorDataNode vectorDataNode, File file) {
super(snapApp.getMainFrame(), Bundle.CTL_ExportGeometryAction_DialogTitle());
this.snapApp = snapApp;
this.vectorDataNode = vectorDataNode;
this.file = file;
}
@Override
protected Exception doInBackground(ProgressMonitor pm) throws Exception {
try {
exportVectorDataNode(vectorDataNode, file, pm);
} catch (Exception e) {
return e;
}
return null;
}
/**
* Called on the event dispatching thread (not on the worker thread) after the <code>construct</code> method
* has returned.
*/
@Override
public void done() {
Exception exception = null;
try {
UIUtils.setRootFrameDefaultCursor(SnapApp.getDefault().getMainFrame());
snapApp.setStatusBarMessage("");
exception = get();
} catch (InterruptedException | ExecutionException e) {
exception = e;
} finally {
if (exception != null) {
exception.printStackTrace();
Dialogs.showError(Bundle.CTL_ExportGeometryAction_DialogTitle(),
"Can not export geometry.\n" + exception.getMessage());
}
}
}
}
}
| 16,584 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportMaskPixelsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportMaskPixelsAction.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.actions.file.export;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.SelectExportMethodDialog;
import org.esa.snap.ui.UIUtils;
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.awt.ActionRegistration;
import org.openide.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.file.export.ExportMaskPixelsAction"
)
@ActionRegistration(
displayName = "#CTL_ExportMaskPixelsAction_MenuText",
popupText = "#CTL_ExportMaskPixelsAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Export/Other", position = 50),
@ActionReference(path = "Menu/Raster/Export", position = 100),
@ActionReference(path = "Context/ProductSceneView", position = 50)
})
@NbBundle.Messages({
"CTL_ExportMaskPixelsAction_MenuText=Mask Pixels",
"CTL_ExportMaskPixelsAction_PopupText=Export Mask Pixels",
"CTL_ExportMaskPixelsAction_DialogTitle=Export Mask Pixels",
"CTL_ExportMaskPixelsAction_ShortDescription=Export Mask Pixels."
})
public class ExportMaskPixelsAction extends AbstractAction implements ContextAwareAction, LookupListener, HelpCtx.Provider {
private static final String HELP_ID = "exportMaskPixels";
private static final String ERR_MSG_BASE = "Mask pixels cannot be exported:\n";
private final Lookup.Result<ProductSceneView> result;
public ExportMaskPixelsAction() {
this(Utilities.actionsGlobalContext());
}
public ExportMaskPixelsAction(Lookup lkp) {
super(Bundle.CTL_ExportMaskPixelsAction_MenuText());
putValue("popupText", Bundle.CTL_ExportMaskPixelsAction_PopupText());
result = lkp.lookupResult(ProductSceneView.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
private static String createDefaultFileName(final Product raster, String maskName) {
String productName = FileUtils.getFilenameWithoutExtension(raster.getProduct().getName());
return productName + "_" + maskName + "_Mask.txt";
}
private static String getWindowTitle() {
return SnapApp.getDefault().getInstanceName() + " - " + Bundle.CTL_ExportMaskPixelsAction_DialogTitle();
}
/*
* Opens a modal file chooser dialog that prompts the user to select the output file name.
*
* @param visatApp the VISAT application
* @return the selected file, <code>null</code> means "Cancel"
*/
private static File promptForFile(String defaultFileName) {
final SnapFileFilter fileFilter = new SnapFileFilter("TXT", "txt", "Text");
return Dialogs.requestFileForSave(Bundle.CTL_ExportMaskPixelsAction_DialogTitle(),
false,
fileFilter,
".txt",
defaultFileName,
null,
"exportMaskPixels.lastDir");
}
/////////////////////////////////////////////////////////////////////////
// Private implementations for the "export Mask Pixels" command
/////////////////////////////////////////////////////////////////////////
/**
* Writes all pixel values of the given product within the given Mask to the specified out.
*
* @param out the data output writer
* @param product the product providing the pixel values
* @param maskName the mask name
* @param mustCreateHeader
* @param mustExportTiePoints
* @param mustExportWavelengthsAndSF
* @param pm progress monitor
* @return <code>true</code> for success, <code>false</code> if export has been terminated (by user)
*/
private static boolean exportMaskPixels(final PrintWriter out,
final Product product,
String maskName,
boolean mustCreateHeader,
boolean mustExportTiePoints,
boolean mustExportWavelengthsAndSF,
ProgressMonitor pm) throws IOException {
final RenderedImage maskImage = product.getMaskGroup().get(maskName).getSourceImage();
final int minTileX = maskImage.getMinTileX();
final int minTileY = maskImage.getMinTileY();
final int numXTiles = maskImage.getNumXTiles();
final int numYTiles = maskImage.getNumYTiles();
final int w = product.getSceneRasterWidth();
final int h = product.getSceneRasterHeight();
final Rectangle imageRect = new Rectangle(0, 0, w, h);
pm.beginTask("Writing pixel data...", numXTiles * numYTiles + 2);
try {
if (mustCreateHeader) {
createHeader(out, product, maskName, mustExportWavelengthsAndSF);
}
pm.worked(1);
writeColumnNames(out, product, maskName, mustExportTiePoints);
pm.worked(1);
for (int tileX = minTileX; tileX < minTileX + numXTiles; ++tileX) {
for (int tileY = minTileY; tileY < minTileY + numYTiles; ++tileY) {
if (pm.isCanceled()) {
return false;
}
final Rectangle tileRectangle = new Rectangle(maskImage.getTileGridXOffset() + tileX * maskImage.getTileWidth(),
maskImage.getTileGridYOffset() + tileY * maskImage.getTileHeight(),
maskImage.getTileWidth(), maskImage.getTileHeight());
final Rectangle r = imageRect.intersection(tileRectangle);
if (!r.isEmpty()) {
Raster maskTile = maskImage.getTile(tileX, tileY);
for (int y = r.y; y < r.y + r.height; y++) {
for (int x = r.x; x < r.x + r.width; x++) {
if (maskTile.getSample(x, y, 0) != 0) {
writeDataLine(out, product, maskName, x, y, mustExportTiePoints);
}
}
}
}
pm.worked(1);
}
}
} finally {
pm.done();
}
return true;
}
private static void createHeader(PrintWriter out, Product product, String maskName, boolean mustExportWavelengthsAndSF) {
out.write("# Exported mask '" + maskName + "' on " +
new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss.mmmmmm").format(new GregorianCalendar().getTime()) + "\n");
out.write("# Product name: " + product.getName() + "\n");
if (product.getFileLocation() != null) {
out.write("# Product file location: " + product.getFileLocation() + "\n");
}
out.write("\n");
if (mustExportWavelengthsAndSF) {
out.write("# Wavelength:");
out.write("\t\t\t"); // account for pixel-x, pixel-y, lon, lat columns
for (final Band band : product.getBands()) {
out.print("\t");
out.print("" + band.getSpectralWavelength());
}
out.print("\n");
out.write("# Solar flux:");
out.write("\t\t\t"); // account for pixel-x, pixel-y, lon, lat columns
for (final Band band : product.getBands()) {
out.print("\t");
out.print("" + band.getSolarFlux());
}
out.print("\n");
}
}
/*
* Writes the header line of the dataset to be exported.
*
* @param out the data output writer
* @param geoCoding the product's geo-coding
* @param bands the array of bands to be considered
* @param mustExportTiePointGrids if tie-point grids shall be considered
* @param tiePointGrids the array of tie-point grids to be considered
*/
private static void writeColumnNames(final PrintWriter out,
final Product product,
final String maskName,
final boolean mustExportTiePointGrids) {
if (!product.isMultiSize()) {
out.print("Pixel-X");
out.print("\t");
out.print("Pixel-Y");
} else {
// Add the mask name to the identification of the pixel
out.print("Pixel-X." + maskName);
out.print("\t");
out.print("Pixel-Y." + maskName);
}
if (product.getSceneGeoCoding() != null) {
out.print("\t");
out.print("Longitude");
out.print("\t");
out.print("Latitude");
}
for (final Band band : product.getBands()) {
out.print("\t");
out.print(band.getName());
}
if (mustExportTiePointGrids) {
for (final TiePointGrid grid : product.getTiePointGrids()) {
out.print("\t");
out.print(grid.getName());
}
}
out.print("\n");
}
/**
* Writes a data line of the dataset to be exported for the given pixel position.
*
* @param out the data output writer
* @param product the product
* @param maskName the mask name (where the pixel X and Y where read)
* @param x the current pixel's X coordinate
* @param y the current pixel's Y coordinate
* @param mustExportTiePoints if tie-point grids shall be exported
* @throws IOException
*/
private static void writeDataLine(final PrintWriter out,
final Product product,
final String maskName,
final int x, final int y,
final boolean mustExportTiePoints) throws IOException {
// All the positions computations will be done at the centre of pixel cell
final PixelPos pixelPosRef = new PixelPos(x + 0.5f, y + 0.5f);
out.print(pixelPosRef.x);
out.print("\t");
out.print(pixelPosRef.y);
final Mask mask = product.getMaskGroup().get(maskName);
final GeoCoding maskGeocoding = mask.getGeoCoding();
if (maskGeocoding != null) {
final GeoPos geoPos = maskGeocoding.getGeoPos(pixelPosRef, null);
out.print("\t");
out.print(geoPos.lon);
out.print("\t");
out.print(geoPos.lat);
}
final int[] intPixel = new int[1];
final float[] floatPixel = new float[1];
for (final Band band : product.getBands()) {
out.print("\t");
PixelPos pixelForBand = product.getPixelForBand(pixelPosRef, mask, band);
int xForBand = MathUtils.floorInt(pixelForBand.x);
int yForBand = MathUtils.floorInt(pixelForBand.y);
if (band.isPixelValid(xForBand, yForBand)) {
if (band.isFloatingPointType()) {
band.readPixels(xForBand, yForBand, 1, 1, floatPixel, ProgressMonitor.NULL);
out.print(floatPixel[0]);
} else {
band.readPixels(xForBand, yForBand, 1, 1, intPixel, ProgressMonitor.NULL);
out.print(intPixel[0]);
}
} else {
out.print(RasterDataNode.NO_DATA_TEXT);
}
} // end loop on bands
if (mustExportTiePoints) {
for (final TiePointGrid grid : product.getTiePointGrids()) {
PixelPos pixelForGrid = product.getPixelForBand(pixelPosRef, mask, grid);
grid.readPixels(MathUtils.floorInt(pixelForGrid.x), MathUtils.floorInt(pixelForGrid.y),
1, 1, floatPixel, ProgressMonitor.NULL);
out.print("\t");
out.print(floatPixel[0]);
if (Float.isNaN(floatPixel[0])) {
System.out.println("NaN for " + grid.getName());
}
}
} // end loop on Tie Point grids
out.print("\n");
}
/*
* Computes the total number of pixels within the specified Mask.
*
* @param raster the raster data node
* @param maskImage the rendered image masking out the Mask
* @return the total number of pixels in the Mask
*/
private static long getNumMaskPixels(final RenderedImage maskImage, int sceneRasterWidth, int sceneRasterHeight) {
final int minTileX = maskImage.getMinTileX();
final int minTileY = maskImage.getMinTileY();
final int numXTiles = maskImage.getNumXTiles();
final int numYTiles = maskImage.getNumYTiles();
final Rectangle imageRect = new Rectangle(0, 0, sceneRasterWidth, sceneRasterHeight);
long numMaskPixels = 0;
for (int tileX = minTileX; tileX < minTileX + numXTiles; ++tileX) {
for (int tileY = minTileY; tileY < minTileY + numYTiles; ++tileY) {
final Rectangle tileRectangle = new Rectangle(maskImage.getTileGridXOffset() + tileX * maskImage.getTileWidth(),
maskImage.getTileGridYOffset() + tileY * maskImage.getTileHeight(),
maskImage.getTileWidth(), maskImage.getTileHeight());
final Rectangle r = imageRect.intersection(tileRectangle);
if (!r.isEmpty()) {
Raster maskTile = maskImage.getTile(tileX, tileY);
for (int y = r.y; y < r.y + r.height; y++) {
for (int x = r.x; x < r.x + r.width; x++) {
if (maskTile.getSample(x, y, 0) != 0) {
numMaskPixels++;
}
}
}
}
}
}
return numMaskPixels;
}
/**
* Invoked when a command action is performed.
*
* @param event the command event
*/
@Override
public void actionPerformed(ActionEvent event) {
ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView();
if (sceneView != null) {
Product product = sceneView.getProduct();
// if (product.isMultiSize()) {
// final Product resampledProduct = MultiSizeIssue.maybeResample(product);
// if (resampledProduct != null) {
// product = resampledProduct;
// } else {
// return;
// }
// }
exportMaskPixels(product);
}
}
@Override
public Action createContextAwareInstance(Lookup lkp) {
return new ExportMaskPixelsAction(lkp);
}
@Override
public void resultChanged(LookupEvent le) {
ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView();
boolean enabled = false;
if (sceneView != null) {
Product product = sceneView.getProduct();
if (product != null) {
enabled = product.getMaskGroup().getNodeCount() > 0;
}
}
setEnabled(enabled);
}
/**
* Performs the actual "export Mask Pixels" command.
*
* @param product
*/
private void exportMaskPixels(Product product) {
String[] maskNames = product.getMaskGroup().getNodeNames();
final String maskName;
if (maskNames.length == 1) {
maskName = maskNames[0];
} else {
JPanel panel = new JPanel();
BoxLayout boxLayout = new BoxLayout(panel, BoxLayout.X_AXIS);
panel.setLayout(boxLayout);
panel.add(new JLabel("Select Mask: "));
JComboBox<String> maskCombo = new JComboBox<>(maskNames);
panel.add(maskCombo);
ModalDialog modalDialog = new ModalDialog(SnapApp.getDefault().getMainFrame(),
Bundle.CTL_ExportMaskPixelsAction_DialogTitle(), panel,
ModalDialog.ID_OK_CANCEL | ModalDialog.ID_HELP, getHelpCtx().getHelpID());
if (modalDialog.show() == AbstractDialog.ID_OK) {
maskName = (String) maskCombo.getSelectedItem();
} else {
return;
}
}
final RenderedImage maskImage = product.getMaskGroup().get(maskName).getSourceImage();
if (maskImage == null) {
Dialogs.showError(Bundle.CTL_ExportMaskPixelsAction_DialogTitle(),
ERR_MSG_BASE + "No Mask image available.");
return;
}
// Compute total number of Mask pixels
final long numMaskPixels = getNumMaskPixels(maskImage, product.getSceneRasterWidth(), product.getSceneRasterHeight());
String numPixelsText;
if (numMaskPixels == 1) {
numPixelsText = "One Mask pixel will be exported.\n";
} else {
numPixelsText = numMaskPixels + " Mask pixels will be exported.\n";
}
// Get export method from user
final String questionText = "How do you want to export the pixel values?\n";
final JCheckBox createHeaderBox = new JCheckBox("Create header");
final JCheckBox exportTiePointsBox = new JCheckBox("Export tie-points");
final JCheckBox exportWavelengthsAndSFBox = new JCheckBox("Export wavelengths + solar fluxes");
final int method = SelectExportMethodDialog.run(SnapApp.getDefault().getMainFrame(), getWindowTitle(),
questionText + numPixelsText, new JCheckBox[]{
createHeaderBox,
exportTiePointsBox,
exportWavelengthsAndSFBox
}, getHelpCtx().getHelpID());
final boolean mustCreateHeader = createHeaderBox.isSelected();
final boolean mustExportTiePoints = exportTiePointsBox.isSelected();
final boolean mustExportWavelengthsAndSF = exportWavelengthsAndSFBox.isSelected();
//
final PrintWriter out;
final StringBuffer clipboardText;
final int initialBufferSize = 256000;
if (method == SelectExportMethodDialog.EXPORT_TO_CLIPBOARD) {
// Write into string buffer
final StringWriter stringWriter = new StringWriter(initialBufferSize);
out = new PrintWriter(stringWriter);
clipboardText = stringWriter.getBuffer();
} else if (method == SelectExportMethodDialog.EXPORT_TO_FILE) {
// Write into file, get file from user
final File file = promptForFile(createDefaultFileName(product, maskName));
if (file == null) {
return; // Cancel
}
final FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
} catch (IOException e) {
Dialogs.showError(Bundle.CTL_ExportMaskPixelsAction_DialogTitle(),
ERR_MSG_BASE + "Failed to create file '" + file + "':\n" + e.getMessage());
return; // Error
}
out = new PrintWriter(new BufferedWriter(fileWriter, initialBufferSize));
clipboardText = null;
} else {
return; // Cancel
}
final ProgressMonitorSwingWorker<Exception, Object> swingWorker = new ProgressMonitorSwingWorker<>(
SnapApp.getDefault().getMainFrame(), Bundle.CTL_ExportMaskPixelsAction_DialogTitle()) {
@Override
protected Exception doInBackground(ProgressMonitor pm) {
Exception returnValue = null;
try {
boolean success = exportMaskPixels(out, product, maskName,
mustCreateHeader, mustExportTiePoints, mustExportWavelengthsAndSF, pm);
if (success && clipboardText != null) {
SystemUtils.copyToClipboard(clipboardText.toString());
clipboardText.setLength(0);
}
} catch (Exception e) {
returnValue = e;
} finally {
out.close();
}
return returnValue;
}
@Override
public void done() {
// clear status bar
SnapApp.getDefault().setStatusBarMessage("");
// show default-cursor
UIUtils.setRootFrameDefaultCursor(SnapApp.getDefault().getMainFrame());
// On error, show error message
Exception exception;
try {
exception = get();
} catch (Exception e) {
exception = e;
}
if (exception != null) {
Dialogs.showError(Bundle.CTL_ExportMaskPixelsAction_DialogTitle(),
ERR_MSG_BASE + exception.getMessage());
}
}
};
// show wait-cursor
UIUtils.setRootFrameWaitCursor(SnapApp.getDefault().getMainFrame());
// show message in status bar
SnapApp.getDefault().setStatusBarMessage("Exporting Mask pixels...");
// Start separate worker thread.
swingWorker.execute();
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
}
| 23,209 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractExportImageAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/AbstractExportImageAction.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.actions.file.export;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import com.sun.media.jai.codec.ImageCodec;
import com.sun.media.jai.codec.ImageEncoder;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.geotiff.GeoTIFF;
import org.esa.snap.core.util.geotiff.GeoTIFFMetadata;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.runtime.Config;
import org.esa.snap.ui.SnapFileChooser;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.LookupListener;
import javax.media.jai.operator.BandSelectDescriptor;
import javax.swing.*;
import java.awt.*;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
public abstract class AbstractExportImageAction extends AbstractAction implements LookupListener, ContextAwareAction, HelpCtx.Provider {
public static final String IMAGE_EXPORT_DIR_PREFERENCES_KEY = "user.image.export.dir";
protected static final String[] BMP_FORMAT_DESCRIPTION = {"BMP", "bmp", "BMP - Microsoft Windows Bitmap"};
protected static final String[] PNG_FORMAT_DESCRIPTION = {"PNG", "png", "PNG - Portable Network Graphics"};
protected static final String[] JPEG_FORMAT_DESCRIPTION = {"JPEG", "jpg,jpeg", "JPEG - Joint Photographic Experts Group"};
protected static final String[] GEOTIFF_FORMAT_DESCRIPTION = {"GeoTIFF", "tif,tiff", "GeoTIFF - TIFF with geo-location"};
// not yet used
// private static final String[] JPEG2K_FORMAT_DESCRIPTION = {"JPEG2000", "jpg,jpeg", "JPEG 2000 - Joint Photographic Experts Group"};
protected static final String[] TIFF_FORMAT_DESCRIPTION = {"TIFF", "tif,tiff", "TIFF - Tagged Image File Format"};
private static final String[] TRANSPARENCY_IMAGE_FORMATS = new String[]{"TIFF", "PNG"};
private String dialogTitle;
private final String helpId;
public AbstractExportImageAction(String name, String helpId) {
super(name);
this.dialogTitle = name;
this.helpId = helpId;
Config.instance().load();
}
protected static boolean isTransparencySupportedByFormat(String formatName) {
for (final String format : TRANSPARENCY_IMAGE_FORMATS) {
if (format.equalsIgnoreCase(formatName)) {
return true;
}
}
return false;
}
protected static SnapFileFilter createFileFilter(String[] description) {
final String formatName = description[0];
final String formatExt = description[1];
final String formatDescr = description[2];
return new SnapFileFilter(formatName, formatExt, formatDescr);
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(helpId);
}
protected void exportImage(final SnapFileFilter[] filters) {
final ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView();
if (view == null) {
return;
}
final String lastDir = Config.instance().preferences().get(IMAGE_EXPORT_DIR_PREFERENCES_KEY,
SystemUtils.getUserHomeDir().getPath());
final File currentDir = new File(lastDir);
final SnapFileChooser fileChooser = new SnapFileChooser();
HelpCtx.setHelpIDString(fileChooser, getHelpCtx().getHelpID());
fileChooser.setCurrentDirectory(currentDir);
for (int i = 0; i < filters.length; i++) {
SnapFileFilter filter = filters[i];
Debug.trace("export image: supported format " + (i + 1) + ": " + filter.getFormatName());
fileChooser.addChoosableFileFilter(filter); // note: also selects current file filter!
}
fileChooser.setAcceptAllFileFilterUsed(false);
String name = view.getProduct().getName();
final String imageBaseName = FileUtils.getFilenameWithoutExtension(name).replace('.', '_');
configureFileChooser(fileChooser, view, imageBaseName);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
Dimension fileChooserSize = fileChooser.getPreferredSize();
if (fileChooserSize != null) {
fileChooser.setPreferredSize(new Dimension(fileChooserSize.width + 120, fileChooserSize.height));
} else {
fileChooser.setPreferredSize(new Dimension(512, 256));
}
int result = fileChooser.showSaveDialog(SnapApp.getDefault().getMainFrame());
File file = fileChooser.getSelectedFile();
fileChooser.addPropertyChangeListener(evt -> {
// @todo never comes here, why?
Debug.trace(evt.toString());
});
final File currentDirectory = fileChooser.getCurrentDirectory();
if (currentDirectory != null) {
Config.instance().preferences().put(IMAGE_EXPORT_DIR_PREFERENCES_KEY, currentDirectory.getPath());
}
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
if (file == null || file.getName().equals("")) {
return;
}
final boolean entireImageSelected = isEntireImageSelected();
final SnapFileFilter fileFilter = fileChooser.getSnapFileFilter();
String imageFormat = fileFilter != null ? fileFilter.getFormatName() : "TIFF";
if (imageFormat.equals(GEOTIFF_FORMAT_DESCRIPTION[0]) && !entireImageSelected) {
final String msg = "GeoTIFF is not applicable to image clippings. Please select 'Full scene' option." +
"\nShall TIFF format be used instead?";
Dialogs.Answer status = Dialogs.requestDecision(dialogTitle, msg, true, null);
if (status == Dialogs.Answer.YES) {
imageFormat = "TIFF";
} else {
return;
}
}
if (Boolean.TRUE.equals(Dialogs.requestOverwriteDecision(dialogTitle, file))) {
exportImage(imageFormat, view, entireImageSelected, file);
}
}
protected void exportImage(final String imageFormat, final ProductSceneView view, final boolean entireImageSelected, final File file) {
final SaveImageSwingWorker worker = new SaveImageSwingWorker(SnapApp.getDefault(), "Save Image", imageFormat, view,
entireImageSelected, file);
worker.executeWithBlocking();
}
protected abstract RenderedImage createImage(String imageFormat, ProductSceneView view);
protected abstract boolean isEntireImageSelected();
protected abstract void configureFileChooser(SnapFileChooser fileChooser, ProductSceneView view,
String imageBaseName);
private class SaveImageSwingWorker extends ProgressMonitorSwingWorker {
private final String imageFormat;
private final ProductSceneView view;
private final boolean entireImageSelected;
private final File file;
private final SnapApp snapApp;
SaveImageSwingWorker(SnapApp snapApp, String message, String imageFormat, ProductSceneView view,
boolean entireImageSelected, File file) {
super(snapApp.getMainFrame(), message);
this.snapApp = snapApp;
this.imageFormat = imageFormat;
this.view = view;
this.entireImageSelected = entireImageSelected;
this.file = file;
}
@Override
protected Object doInBackground(ProgressMonitor pm) throws Exception {
try {
final String message = "Saving image as " + file.getPath() + "...";
pm.beginTask(message, 1);
snapApp.setStatusBarMessage(message);
snapApp.getMainFrame().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
RenderedImage image = createImage(imageFormat, view);
boolean geoTIFFWritten = false;
if (imageFormat.equals("GeoTIFF") && entireImageSelected) {
final GeoTIFFMetadata metadata = ProductUtils.createGeoTIFFMetadata(view.getProduct());
if (metadata != null) {
GeoTIFF.writeImage(image, file, metadata);
geoTIFFWritten = true;
}
}
if (!geoTIFFWritten) {
if ("JPEG".equalsIgnoreCase(imageFormat)) {
image = BandSelectDescriptor.create(image, new int[]{0, 1, 2}, null);
}
try (OutputStream stream = new FileOutputStream(file)) {
ImageEncoder encoder = ImageCodec.createImageEncoder(imageFormat, stream, null);
encoder.encode(image);
}
}
} catch (OutOfMemoryError e) {
Dialogs.showOutOfMemoryError("The image could not be exported.");
} catch (Throwable e) {
snapApp.handleError("The image could not be exported.", e); //handleUnknownException(e);
} finally {
snapApp.getMainFrame().setCursor(Cursor.getDefaultCursor());
snapApp.setStatusBarMessage("");
pm.done();
}
return null;
}
}
}
| 10,304 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportColorPaletteAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportColorPaletteAction.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.actions.file.export;
import org.esa.snap.core.datamodel.ColorPaletteDef;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.image.ImageManager;
import org.esa.snap.core.util.NamingConvention;
import org.esa.snap.core.util.PreferencesPropertyMap;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
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.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Optional;
import java.util.prefs.Preferences;
/**
* This action exports the color palette of the selected product.
*
* @author Marco Peters
*/
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.file.export.ExportColorPaletteAction"
)
@ActionRegistration(
displayName = "#CTL_ExportColorPaletteAction_MenuText",
popupText = "#CTL_ExportColorPaletteAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Export/Other", position = 20),
@ActionReference(path = "Context/ProductSceneView" ,position = 80)
})
@NbBundle.Messages({
"CTL_ExportColorPaletteAction_MenuText=" + NamingConvention.COLOR_MIXED_CASE + " Palette as File",
"CTL_ExportColorPaletteAction_PopupText=Export " + NamingConvention.COLOR_MIXED_CASE + " Palette as File",
"CTL_ExportColorPaletteAction_DialogTitle=Export " + NamingConvention.COLOR_MIXED_CASE + " Palette",
"CTL_ExportColorPaletteAction_ShortDescription=Export " + NamingConvention.COLOR_MIXED_CASE + " Palette as File."
})
public class ExportColorPaletteAction extends AbstractAction implements LookupListener, ContextAwareAction, HelpCtx.Provider {
private static final String KEY_LAST_OPEN = "ExportColorPaletteVPI.path";
private static final String HELP_ID = "exportColorPalette";
private final Lookup.Result<ProductSceneView> result;
public ExportColorPaletteAction() {
this(Utilities.actionsGlobalContext());
}
public ExportColorPaletteAction(Lookup lookup) {
super(Bundle.CTL_ExportColorPaletteAction_MenuText());
putValue("popupText", Bundle.CTL_ExportColorPaletteAction_PopupText());
result = lookup.lookupResult(ProductSceneView.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent e) {
SnapFileFilter fileFilter1 = new SnapFileFilter("CSV", ".csv", "CSV files"); // I18N
SnapFileFilter fileFilter2 = new SnapFileFilter("TXT", ".txt", "Text files"); // I18N
JFileChooser fileChooser = new JFileChooser();
File lastDir = new File(getPreferences().getPropertyString(KEY_LAST_OPEN, "."));
fileChooser.setCurrentDirectory(lastDir);
RasterDataNode raster = getSelectedRaster();
fileChooser.setSelectedFile(new File(lastDir, raster.getName() + "-palette.csv"));
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.addChoosableFileFilter(fileFilter1);
fileChooser.addChoosableFileFilter(fileFilter2);
fileChooser.setFileFilter(fileFilter1);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setDialogTitle(Bundle.CTL_ExportColorPaletteAction_DialogTitle());
if (fileChooser.showSaveDialog(SnapApp.getDefault().getMainFrame()) == JFileChooser.APPROVE_OPTION
&& fileChooser.getSelectedFile() != null) {
getPreferences().setPropertyString(KEY_LAST_OPEN, fileChooser.getCurrentDirectory().getAbsolutePath());
File file = fileChooser.getSelectedFile();
if (fileChooser.getFileFilter() instanceof SnapFileFilter) {
SnapFileFilter fileFilter = (SnapFileFilter) fileChooser.getFileFilter();
file = FileUtils.ensureExtension(file, fileFilter.getDefaultExtension());
}
try {
writeColorPalette(raster, file);
} catch (IOException ie) {
Dialogs.showError(Bundle.CTL_ExportColorPaletteAction_DialogTitle(),
"Failed to export " + NamingConvention.COLOR_LOWER_CASE + " palette:\n" + ie.getMessage());
}
}
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ExportColorPaletteAction(lookup);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnabled(getSelectedImageInfo() != null);
}
private static void writeColorPalette(RasterDataNode raster, File file) throws IOException {
try (FileWriter writer = new FileWriter(file)) {
writeColorPalette(raster, writer);
}
}
private static void writeColorPalette(RasterDataNode raster, FileWriter writer) throws IOException {
ImageInfo imageInfo = raster.getImageInfo();
final ColorPaletteDef paletteDef = imageInfo.getColorPaletteDef();
final Color[] colorPalette = ImageManager.createColorPalette(imageInfo);
double s1 = paletteDef.getMinDisplaySample();
double s2 = paletteDef.getMaxDisplaySample();
int numColors = colorPalette.length;
writer.write("# Band: " + raster.getName() + "\n");
writer.write("# Sample unit: " + raster.getUnit() + "\n");
writer.write("# Minimum sample value: " + s1 + "\n");
writer.write("# Maximum sample value: " + s2 + "\n");
writer.write("# Number of colors: " + numColors + "\n");
double sf = (s2 - s1) / (numColors - 1.0);
writer.write("ID;Sample;RGB\n");
for (int i = 0; i < numColors; i++) {
Color color = colorPalette[i];
double s = s1 + i * sf;
writer.write(i + ";" + s + ";" + StringUtils.formatColor(color) + "\n");
}
}
private RasterDataNode getSelectedRaster() {
Optional<? extends ProductSceneView> first = result.allInstances().stream().findFirst();
if (first.isPresent()) {
return first.get().getRaster();
}
return null;
}
private ImageInfo getSelectedImageInfo() {
RasterDataNode raster = getSelectedRaster();
if (raster != null) {
return raster.getImageInfo();
}
return null;
}
private static PropertyMap getPreferences() {
final Preferences preferences = SnapApp.getDefault().getPreferences();
return new PreferencesPropertyMap(preferences);
}
}
| 8,198 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportTransectPixelsAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportTransectPixelsAction.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.actions.file.export;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.FigureSelection;
import com.bc.ceres.swing.figure.ShapeFigure;
import com.bc.ceres.swing.progress.DialogProgressMonitor;
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.PixelPos;
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.datamodel.TiePointGrid;
import org.esa.snap.core.datamodel.TransectProfileData;
import org.esa.snap.core.datamodel.TransectProfileDataBuilder;
import org.esa.snap.core.transform.MathTransform2D;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.SelectExportMethodDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneView;
import org.opengis.referencing.operation.TransformException;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBox;
import javax.swing.SwingWorker;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
@ActionID(category = "File", id = "org.esa.snap.rcp.actions.file.export.ExportTransectPixelsAction")
@ActionRegistration(
displayName = "#CTL_ExportTransectPixelsAction_MenuText",
popupText = "#CTL_ExportTransectPixelsAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Export/Other", position = 65),
@ActionReference(path = "Menu/Raster/Export", position = 205),
@ActionReference(path = "Context/Product/RasterDataNode", position = 50, separatorAfter = 55),
@ActionReference(path = "Context/ProductSceneView", position = 40)
})
@NbBundle.Messages({
"CTL_ExportTransectPixelsAction_MenuText=Transect Pixels",
"CTL_ExportTransectPixelsAction_PopupText=Export Transect Pixels",
"CTL_ExportTransectPixelsAction_DialogTitle=Export Transect Pixels",
"CTL_ExportTransectPixelsAction_ShortDescription=Export Transect Pixels."
})
public class ExportTransectPixelsAction extends AbstractAction implements ContextAwareAction, LookupListener {
private static final String ERR_MSG_BASE = "Transect pixels cannot be exported:\n";
private final Lookup.Result<FigureSelection> result;
@SuppressWarnings("unused")
public ExportTransectPixelsAction() {
this(Utilities.actionsGlobalContext());
}
public ExportTransectPixelsAction(Lookup lkp) {
super(Bundle.CTL_ExportTransectPixelsAction_MenuText());
putValue("popupText", Bundle.CTL_ExportTransectPixelsAction_PopupText());
result = lkp.lookupResult(FigureSelection.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
updateEnableState(getCurrentFigureSelection());
}
/**
* Invoked when a command action is performed.
*
* @param event the command event
*/
@Override
public void actionPerformed(ActionEvent event) {
exportTransectPixels();
}
@Override
public Action createContextAwareInstance(Lookup lkp) {
return new ExportTransectPixelsAction(lkp);
}
@Override
public void resultChanged(LookupEvent le) {
updateEnableState(getCurrentFigureSelection());
}
private void exportTransectPixels() {
// Get current view showing a product's band
final ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView();
if (view == null) {
return;
}
final FigureSelection selection = getCurrentFigureSelection();
// Get the displayed raster data node (band or tie-point grid)
final RasterDataNode raster = view.getRaster();
// Get the transect of the displayed raster data node
final ShapeFigure transect;
if (selection.getFigureCount() > 0) {
Figure figure = selection.getFigure(0);
transect = figure instanceof ShapeFigure ? (ShapeFigure) figure : null;
} else {
transect = null;
}
if (transect == null) {
Dialogs.showError(Bundle.CTL_ExportTransectPixelsAction_DialogTitle(),
ERR_MSG_BASE + "There is no selected transect defined in the selected band.");
return;
}
// Get export method from user
final JCheckBox createHeaderBox = new JCheckBox("Create header");
final JCheckBox exportTiePointsBox = new JCheckBox("Export tie-points");
final JCheckBox exportWavelengthsAndSFBox = new JCheckBox("Export wavelengths + solar fluxes");
final int method = SelectExportMethodDialog.run(SnapApp.getDefault().getMainFrame(), getWindowTitle(),
"How do you want to export the pixel values?",
new JCheckBox[]{
createHeaderBox,
exportTiePointsBox,
exportWavelengthsAndSFBox
},
"exportTransectPixels");
final PrintWriter out;
final StringBuffer clipboardText;
final int initialBufferSize = 256000;
if (method == SelectExportMethodDialog.EXPORT_TO_CLIPBOARD) {
// Write into string buffer
final StringWriter stringWriter = new StringWriter(initialBufferSize);
out = new PrintWriter(stringWriter);
clipboardText = stringWriter.getBuffer();
} else if (method == SelectExportMethodDialog.EXPORT_TO_FILE) {
// Write into file, get file from user
final File file = promptForFile(createDefaultFileName(raster));
if (file == null) {
return; // Cancel
}
final FileWriter fileWriter;
try {
fileWriter = new FileWriter(file);
} catch (IOException e) {
Dialogs.showError(Bundle.CTL_ExportTransectPixelsAction_DialogTitle(),
ERR_MSG_BASE + "Failed to create file '" + file + "':\n" + e.getMessage());
return; // Error
}
out = new PrintWriter(new BufferedWriter(fileWriter, initialBufferSize));
clipboardText = null;
} else {
return; // Cancel
}
final SwingWorker<Exception, Object> swingWorker = new SwingWorker<Exception, Object>() {
@Override
protected Exception doInBackground() {
Exception returnValue = null;
ProgressMonitor pm = new DialogProgressMonitor(SnapApp.getDefault().getMainFrame(), Bundle.CTL_ExportTransectPixelsAction_DialogTitle(),
Dialog.ModalityType.APPLICATION_MODAL);
try {
final boolean mustCreateHeader = createHeaderBox.isSelected();
final boolean mustExportWavelengthsAndSF = exportWavelengthsAndSFBox.isSelected();
final boolean mustExportTiePoints = exportTiePointsBox.isSelected();
final TransectProfileData transectProfileData = new TransectProfileDataBuilder()
.raster(raster)
.path(transect.getShape())
.build();
TransectExporter exporter = new TransectExporter(mustCreateHeader, mustExportWavelengthsAndSF, mustExportTiePoints);
boolean success = exporter.exportTransectPixels(out,
transectProfileData,
pm);
if (success && clipboardText != null) {
SystemUtils.copyToClipboard(clipboardText.toString());
clipboardText.setLength(0);
}
} catch (Exception e) {
returnValue = e;
} finally {
out.close();
}
return returnValue;
}
@Override
public void done() {
// clear status bar
SnapApp.getDefault().setStatusBarMessage("");
// show default-cursor
UIUtils.setRootFrameDefaultCursor(SnapApp.getDefault().getMainFrame());
// On error, show error message
Exception exception;
try {
exception = get();
} catch (Exception e) {
exception = e;
}
if (exception != null) {
Dialogs.showError(Bundle.CTL_ExportTransectPixelsAction_DialogTitle(),
ERR_MSG_BASE + exception.getMessage());
SystemUtils.LOG.log(Level.SEVERE, "Could not export transect pixels", exception);
}
}
};
// show wait-cursor
UIUtils.setRootFrameWaitCursor(SnapApp.getDefault().getMainFrame());
// show message in status bar
SnapApp.getDefault().setStatusBarMessage("Exporting transect pixels...");
// Start separate worker thread.
swingWorker.execute();
}
private FigureSelection getCurrentFigureSelection() {
return result.allInstances().stream().findFirst().orElse(null);
}
private void updateEnableState(FigureSelection figureSelection) {
setEnabled(figureSelection != null);
}
private static String createDefaultFileName(final RasterDataNode raster) {
return FileUtils.getFilenameWithoutExtension(raster.getProduct().getName()) + "_TRANSECT.txt";
}
private static String getWindowTitle() {
return SnapApp.getDefault().getInstanceName() + " - " + Bundle.CTL_ExportTransectPixelsAction_DialogTitle();
}
/**
* Opens a modal file chooser dialog that prompts the user to select the output file name.
*
* @return the selected file, {@code null} means "Cancel"
*/
private static File promptForFile(String defaultFileName) {
final SnapFileFilter fileFilter = new SnapFileFilter("TXT", "txt", "Text");
return Dialogs.requestFileForSave(Bundle.CTL_ExportTransectPixelsAction_DialogTitle(),
false,
fileFilter,
".txt",
defaultFileName,
null,
"exportTransectPixels.lastDir");
}
private static int getNumTransectPixels(final Dimension sceneSize,
final TransectProfileData transectProfileData) {
final Point2D[] pixelPositions = transectProfileData.getPixelPositions();
int numTransectPixels = 0;
for (Point2D pixelPosition : pixelPositions) {
int x = (int) Math.floor(pixelPosition.getX());
int y = (int) Math.floor(pixelPosition.getY());
if (x >= 0 && x < sceneSize.getWidth()
&& y >= 0 && y < sceneSize.getHeight()) {
numTransectPixels++;
}
}
return numTransectPixels;
}
static class TransectExporter {
private final boolean mustCreateHeader;
private final boolean mustExportWavelengthsAndSF;
private final boolean mustExportTiePoints;
TransectExporter(boolean mustCreateHeader, boolean mustExportWavelengthsAndSF, boolean mustExportTiePoints) {
this.mustCreateHeader = mustCreateHeader;
this.mustExportWavelengthsAndSF = mustExportWavelengthsAndSF;
this.mustExportTiePoints = mustExportTiePoints;
}
/**
* Writes all pixel values of the given product within the given ROI to the specified out.
*
* @param out the data output writer
* @param transectProfileData the data of the transect
* @return {@code true} for success, {@code false} if export has been terminated (by user)
*/
private boolean exportTransectPixels(final PrintWriter out,
final TransectProfileData transectProfileData,
ProgressMonitor pm) throws TransformException {
final RasterDataNode raster = transectProfileData.getConfig().raster;
final Product product = raster.getProduct();
final Band[] bands = product.getBands();
final TiePointGrid[] tiePointGrids = product.getTiePointGrids();
if (mustCreateHeader) {
writeFileHeader(out, bands);
}
writeTableHeader(out, raster, product.isMultiSize(), bands, mustExportTiePoints, tiePointGrids, mustExportWavelengthsAndSF);
final Point2D[] pixelPositions = transectProfileData.getPixelPositions();
int numTransectPixels = getNumTransectPixels(raster.getRasterSize(), transectProfileData);
pm.beginTask("Writing pixel data...", numTransectPixels);
final List<RasterDataNode> rasters = new ArrayList<>(Arrays.asList(product.getBands()));
if (mustExportTiePoints) {
rasters.addAll(Arrays.asList(product.getTiePointGrids()));
}
try {
for (Point2D pixelPosition : pixelPositions) {
int x = MathUtils.floorInt(pixelPosition.getX());
int y = MathUtils.floorInt(pixelPosition.getY());
writeDataLine(out, raster, rasters, x, y);
pm.worked(1);
if (pm.isCanceled()) {
return false;
}
}
} finally {
pm.done();
}
return true;
}
private void writeFileHeader(PrintWriter out, Band[] bands) {
ProductData.UTC utc = ProductData.UTC.create(new Date(), 0);
out.printf("# Exported transect on %s%n", utc.format());
if (bands.length > 0) {
Product product = bands[0].getProduct();
out.printf("# Product name: %s%n", product.getName());
if (product.getFileLocation() != null) {
out.printf("# Product file location: %s%n", product.getFileLocation().getAbsolutePath());
}
}
out.println();
}
private void writeTableHeader(final PrintWriter out,
final RasterDataNode raster,
final boolean isMultiSize,
final Band[] bands,
final boolean mustExportTiePoints,
final TiePointGrid[] tiePointGrids,
final boolean mustExportWavelengthsAndSF) {
if (mustExportWavelengthsAndSF) {
float[] wavelengthArray = new float[bands.length];
for (int i = 0; i < bands.length; i++) {
wavelengthArray[i] = bands[i].getSpectralWavelength();
}
out.printf("# Wavelength:\t \t \t \t%s\n", StringUtils.arrayToString(wavelengthArray, "\t"));
float[] solarFluxArray = new float[bands.length];
for (int i = 0; i < bands.length; i++) {
solarFluxArray[i] = bands[i].getSolarFlux();
}
out.printf("# Solar flux:\t \t \t \t%s%n", StringUtils.arrayToString(solarFluxArray, "\t"));
}
if (!isMultiSize) {
out.print("Pixel-X");
out.print("\t");
out.print("Pixel-Y");
} else {
// Add the band name to the identification of the pixel
out.print("Pixel-X." + raster.getName());
out.print("\t");
out.print("Pixel-Y." + raster.getName());
}
if (raster.getGeoCoding() != null) {
out.print("\t");
out.print("Longitude");
out.print("\t");
out.print("Latitude");
}
for (final Band band : bands) {
out.print("\t");
out.print(band.getName());
}
if (mustExportTiePoints) {
for (final TiePointGrid grid : tiePointGrids) {
out.print("\t");
out.print(grid.getName());
}
}
out.print("\n");
}
/**
* Writes a data line of the dataset to be exported for the given pixel position.
*
* @param out the data output writer
* @param refRaster the raster which defines the reference for the X,Y coordinates
* @param rasters list of rasters to be exported
* @param x the current pixel's X coordinate
* @param y the current pixel's Y coordinate
*/
private void writeDataLine(final PrintWriter out,
RasterDataNode refRaster,
List<RasterDataNode> rasters, final int x, final int y) throws TransformException {
final PixelPos pixelPos = new PixelPos(x + 0.5f, y + 0.5f);
out.printf("%.1f\t%.1f", pixelPos.x, pixelPos.y);
// Compute the geo position according to the raster resolution
final GeoCoding rasterGeocoding = refRaster.getGeoCoding();
if (rasterGeocoding != null) {
final GeoPos geoPosForPrint = rasterGeocoding.getGeoPos(pixelPos, null);
out.printf("\t%s\t%s", geoPosForPrint.lon, geoPosForPrint.lat);
}
for (final RasterDataNode raster : rasters) {
PixelPos rasterPixelPos = calcPixelPosForCurrentRaster(refRaster, raster, pixelPos);
final int rasterX = MathUtils.floorInt(rasterPixelPos.x);
final int rasterY = MathUtils.floorInt(rasterPixelPos.y);
final boolean pixelValid = raster.isPixelValid(rasterX, rasterY);
String pixelString = pixelValid ? raster.getPixelString(rasterX, rasterY) : RasterDataNode.INVALID_POS_TEXT;
out.printf("\t%s", pixelString);
}
out.print("\n");
}
private PixelPos calcPixelPosForCurrentRaster(RasterDataNode refRaster, RasterDataNode curRaster, PixelPos srcPoint) throws TransformException {
final AffineTransform i2mTransRef = refRaster.getImageToModelTransform();
final MathTransform2D m2sTransRef = refRaster.getModelToSceneTransform();
final MathTransform2D s2mTransCur = curRaster.getSceneToModelTransform();
final AffineTransform m2iTransCur = curRaster.getMultiLevelModel().getModelToImageTransform(0);
if (areCompatible(refRaster, curRaster)) {
return srcPoint;
} else {
final PixelPos targetPos = new PixelPos(srcPoint.x, srcPoint.y);
i2mTransRef.transform(srcPoint, targetPos);
m2sTransRef.transform(targetPos, targetPos);
s2mTransCur.transform(targetPos, targetPos);
m2iTransCur.transform(targetPos, targetPos);
return targetPos;
}
}
private boolean areCompatible(RasterDataNode refRaster, RasterDataNode curRaster) {
return curRaster.getImageToModelTransform().equals(refRaster.getImageToModelTransform()) &&
curRaster.getSceneToModelTransform().equals(refRaster.getSceneToModelTransform());
}
}
}
| 22,161 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExportImageAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/file/export/ExportImageAction.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.actions.file.export;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.accessors.DefaultPropertyAccessor;
import com.bc.ceres.binding.converters.IntegerConverter;
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.grender.support.BufferedImageRendering;
import com.bc.ceres.grender.support.DefaultViewport;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyPane;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.SnapFileChooser;
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.awt.ActionRegistration;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Action for exporting scene views as images.
*
* @author Marco Peters
* @author Ralf Quast
*/
// SEPT 2019 - Authors: Bing Yang, Daniel Knowles
// Modifications to the Export Image tool:
// 1. Modified to use fixed-ratio for the width and height of exported image when using custom user resolution.
// If the user adjusts the width field then the height field auto-adjusts accordingly, and vice versa.
// There is likely not a need for the user to want to stretch the image, so fixed-ratio does prevent this.
// If this functionality of independently setting the width and height fields is desired then this code could
// be further modified to add a fixed-ratio selector.
// 2. Added many tooltips to aid the user in understanding the functionality of the various components.
@ActionID(category = "File", id = "org.esa.snap.rcp.actions.file.export.ExportImageAction")
@ActionRegistration(
displayName = "#CTL_ExportImageAction_MenuText",
popupText = "#CTL_ExportImageAction_PopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Export/Other", position = 80, separatorAfter = 200),
@ActionReference(path = "Context/ProductSceneView", position = 70)
})
@NbBundle.Messages({
"CTL_ExportImageAction_MenuText=View as Image",
"CTL_ExportImageAction_PopupText=Export View as Image",
"CTL_ExportImageAction_ShortDescription=Export the current view as an image."
})
public class ExportImageAction extends AbstractExportImageAction {
private final static String[][] SCENE_IMAGE_FORMAT_DESCRIPTIONS = {
PNG_FORMAT_DESCRIPTION,
GEOTIFF_FORMAT_DESCRIPTION,
JPEG_FORMAT_DESCRIPTION,
TIFF_FORMAT_DESCRIPTION,
BMP_FORMAT_DESCRIPTION,
};
private static final String HELP_ID = "exportImageFile";
private static final String AC_VIEW_RES = "viewRes";
private static final String AC_FULL_RES = "fullRes";
private static final String AC_USER_RES = "userRes";
private static final String AC_FULL_REGION = "fullRegion";
private static final String AC_VIEW_REGION = "viewRegion";
private static final String PSEUDO_AC_INIT = "INIT";
private SnapFileFilter[] sceneImageFileFilters;
private SizeComponent sizeComponent;
@SuppressWarnings("FieldCanBeLocal")
private Lookup.Result<ProductSceneView> result;
private ButtonGroup buttonGroupResolution;
private ButtonGroup buttonGroupRegion;
private JRadioButton buttonVisibleRegion;
private JRadioButton buttonViewResolution;
private JRadioButton buttonFullResolution;
private JRadioButton buttonUserResolution;
private JRadioButton buttonFullRegion;
public ExportImageAction() {
this(Utilities.actionsGlobalContext());
}
public ExportImageAction(Lookup lookup) {
super(Bundle.CTL_ExportImageAction_MenuText(), HELP_ID);
putValue("popupText", Bundle.CTL_ExportImageAction_PopupText());
sceneImageFileFilters = new SnapFileFilter[SCENE_IMAGE_FORMAT_DESCRIPTIONS.length];
for (int i = 0; i < SCENE_IMAGE_FORMAT_DESCRIPTIONS.length; i++) {
sceneImageFileFilters[i] = createFileFilter(SCENE_IMAGE_FORMAT_DESCRIPTIONS[i]);
}
result = lookup.lookupResult(ProductSceneView.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent event) {
exportImage(sceneImageFileFilters);
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ExportImageAction(lookup);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnabled(SnapApp.getDefault().getSelectedProductSceneView() != null);
}
protected void configureFileChooser(final SnapFileChooser fileChooser, final ProductSceneView view,
String imageBaseName) {
fileChooser.setDialogTitle(SnapApp.getDefault().getInstanceName() + " - " + "Export Image"); /*I18N*/
if (view.isRGB()) {
fileChooser.setCurrentFilename(imageBaseName + "_RGB");
} else {
fileChooser.setCurrentFilename(imageBaseName + "_" + view.getRaster().getName());
}
final JPanel regionPanel = new JPanel(new GridLayout(2, 1));
regionPanel.setBorder(BorderFactory.createTitledBorder("Image Region"));
buttonFullRegion = new JRadioButton("Full scene");
buttonFullRegion.setToolTipText("Use the image boundaries of the source data");
buttonFullRegion.setActionCommand(AC_FULL_REGION);
buttonVisibleRegion = new JRadioButton("View region");
buttonVisibleRegion.setToolTipText("Use the image boundaries of the view window");
buttonVisibleRegion.setActionCommand(AC_VIEW_REGION);
regionPanel.add(buttonVisibleRegion);
regionPanel.add(buttonFullRegion);
buttonGroupRegion = new ButtonGroup();
buttonGroupRegion.add(buttonVisibleRegion);
buttonGroupRegion.add(buttonFullRegion);
final JPanel resolutionPanel = new JPanel(new GridLayout(3, 1));
resolutionPanel.setBorder(BorderFactory.createTitledBorder("Image Resolution"));
buttonViewResolution = new JRadioButton("View resolution");
buttonViewResolution.setToolTipText("Use the resolution of the view window as it is on the computer screen");
buttonViewResolution.setActionCommand(AC_VIEW_RES);
buttonFullResolution = new JRadioButton("Full resolution");
buttonFullResolution.setToolTipText("Use the resolution of the source data");
buttonFullResolution.setActionCommand(AC_FULL_RES);
buttonUserResolution = new JRadioButton("User resolution");
buttonUserResolution.setToolTipText("Use a custom resolution set by the user");
buttonUserResolution.setActionCommand(AC_USER_RES);
resolutionPanel.add(buttonViewResolution);
resolutionPanel.add(buttonFullResolution);
resolutionPanel.add(buttonUserResolution);
buttonGroupResolution = new ButtonGroup();
buttonGroupResolution.add(buttonViewResolution);
buttonGroupResolution.add(buttonFullResolution);
buttonGroupResolution.add(buttonUserResolution);
sizeComponent = new SizeComponent(view);
JComponent sizePanel = sizeComponent.createComponent();
sizePanel.setBorder(BorderFactory.createTitledBorder("Image Dimension")); /*I18N*/
sizePanel.setToolTipText("Fixed ratio is automatically applied to width and height");
final JPanel accessory = new JPanel();
accessory.setLayout(new BoxLayout(accessory, BoxLayout.Y_AXIS));
accessory.add(regionPanel);
accessory.add(resolutionPanel);
accessory.add(sizePanel);
fileChooser.setAccessory(accessory);
buttonVisibleRegion.addActionListener(e -> updateComponents(e.getActionCommand()));
buttonFullRegion.addActionListener(e -> updateComponents(e.getActionCommand()));
buttonViewResolution.addActionListener(e -> updateComponents(e.getActionCommand()));
buttonFullResolution.addActionListener(e -> updateComponents(e.getActionCommand()));
buttonUserResolution.addActionListener(e -> updateComponents(e.getActionCommand()));
updateComponents(PSEUDO_AC_INIT);
}
private void updateComponents(String actionCommand) {
updateEnableState(actionCommand);
sizeComponent.updateDimensions();
}
private void updateEnableState(String actionCommand) {
switch (actionCommand) {
case AC_FULL_REGION:
buttonViewResolution.setEnabled(false);
if (buttonViewResolution.isSelected()) {
buttonFullResolution.setSelected(true);
}
break;
case AC_VIEW_REGION:
buttonViewResolution.setEnabled(true);
break;
case PSEUDO_AC_INIT:
buttonVisibleRegion.setSelected(true);
buttonViewResolution.setSelected(true);
}
switch (actionCommand) {
case AC_FULL_RES:
sizeComponent.setEnabled(false);
break;
case AC_VIEW_RES:
sizeComponent.setEnabled(false);
break;
case AC_USER_RES:
sizeComponent.setEnabled(true);
break;
case PSEUDO_AC_INIT:
sizeComponent.setEnabled(false);
}
}
protected RenderedImage createImage(String imageFormat, ProductSceneView view) {
final boolean useAlpha = !BMP_FORMAT_DESCRIPTION[0].equals(imageFormat) && !JPEG_FORMAT_DESCRIPTION[0].equals(imageFormat);
final boolean entireImage = isEntireImageSelected();
return createImage(view, entireImage, sizeComponent.getDimension(), useAlpha, GEOTIFF_FORMAT_DESCRIPTION[0].equals(imageFormat));
}
static RenderedImage createImage(ProductSceneView view, boolean fullScene, Dimension dimension, boolean alphaChannel, boolean geoReferenced) {
final long pixelCount = dimension.width * (long) dimension.height;
if (pixelCount > Integer.MAX_VALUE) {
throw new IllegalArgumentException("Image size is too big. Maximum supported pixel count is " + Integer.MAX_VALUE + ". Current pixel count is " + pixelCount);
}
final int imageType = alphaChannel ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR;
final BufferedImage bufferedImage = new BufferedImage(dimension.width, dimension.height, imageType);
final BufferedImageRendering imageRendering = createRendering(view, fullScene, geoReferenced, bufferedImage);
if (!alphaChannel) {
final Graphics2D graphics = imageRendering.getGraphics();
graphics.setColor(view.getLayerCanvas().getBackground());
graphics.fillRect(0, 0, dimension.width, dimension.height);
}
view.getRootLayer().render(imageRendering);
return bufferedImage;
}
private static BufferedImageRendering createRendering(ProductSceneView view, boolean fullScene,
boolean geoReferenced, BufferedImage bufferedImage) {
final Viewport vp1 = view.getLayerCanvas().getViewport();
final Viewport vp2 = new DefaultViewport(new Rectangle(bufferedImage.getWidth(), bufferedImage.getHeight()),
vp1.isModelYAxisDown());
if (fullScene) {
vp2.zoom(view.getBaseImageLayer().getModelBounds());
} else {
setTransform(vp1, vp2);
}
final BufferedImageRendering imageRendering = new BufferedImageRendering(bufferedImage, vp2);
if (geoReferenced) {
// because image to model transform is stored with the exported image we have to invert
// image to view transformation
final AffineTransform m2iTransform = view.getBaseImageLayer().getModelToImageTransform(0);
final AffineTransform v2mTransform = vp2.getViewToModelTransform();
v2mTransform.preConcatenate(m2iTransform);
final AffineTransform v2iTransform = new AffineTransform(v2mTransform);
final Graphics2D graphics2D = imageRendering.getGraphics();
v2iTransform.concatenate(graphics2D.getTransform());
graphics2D.setTransform(v2iTransform);
}
return imageRendering;
}
private static void setTransform(Viewport vp1, Viewport vp2) {
vp2.setTransform(vp1);
final Rectangle rectangle1 = vp1.getViewBounds();
final Rectangle rectangle2 = vp2.getViewBounds();
final double w1 = rectangle1.getWidth();
final double w2 = rectangle2.getWidth();
final double h1 = rectangle1.getHeight();
final double h2 = rectangle2.getHeight();
final double x1 = rectangle1.getX();
final double y1 = rectangle1.getY();
final double cx = (x1 + w1) / 2.0;
final double cy = (y1 + h1) / 2.0;
final double magnification;
if (w1 > h1) {
magnification = w2 / w1;
} else {
magnification = h2 / h1;
}
final Point2D modelCenter = vp1.getViewToModelTransform().transform(new Point2D.Double(cx, cy), null);
final double zoomFactor = vp1.getZoomFactor() * magnification;
if (zoomFactor > 0.0) {
vp2.setZoomFactor(zoomFactor, modelCenter.getX(), modelCenter.getY());
}
}
protected boolean isEntireImageSelected() {
ButtonModel selection = buttonGroupRegion.getSelection();
return selection != null && AC_FULL_REGION.equals(selection.getActionCommand());
}
private class SizeComponent {
private static final String PROPERTY_NAME_HEIGHT = "height";
private static final String PROPERTY_NAME_WIDTH = "width";
boolean widthListenerEnabled = false;
boolean heightListenerEnabled = false;
Double heightWidthRatio = null;
private final PropertyContainer propertyContainer;
private final ProductSceneView view;
private BindingContext bindingContext;
SizeComponent(ProductSceneView view) {
this.view = view;
propertyContainer = new PropertyContainer();
initValueContainer();
bindingContext = new BindingContext(propertyContainer);
}
private void setEnabled(boolean enabled) {
bindingContext.setComponentsEnabled(PROPERTY_NAME_HEIGHT, enabled);
bindingContext.setComponentsEnabled(PROPERTY_NAME_WIDTH, enabled);
}
private void updateDimensions() {
final Rectangle2D bounds;
ButtonModel selection = buttonGroupResolution.getSelection();
if (selection == null) {
return;
}
String resolutionAC = selection.getActionCommand();
if (isEntireImageSelected()) {
final ImageLayer imageLayer = view.getBaseImageLayer();
final Rectangle2D modelBounds = imageLayer.getModelBounds();
Rectangle2D imageBounds = imageLayer.getModelToImageTransform().createTransformedShape(modelBounds).getBounds2D();
final double mScale = modelBounds.getWidth() / modelBounds.getHeight();
final double iScale = imageBounds.getHeight() / imageBounds.getWidth();
double scaleFactorX = mScale * iScale;
bounds = new Rectangle2D.Double(0, 0, scaleFactorX * imageBounds.getWidth(), 1 * imageBounds.getHeight());
} else {
switch (resolutionAC) {
case AC_FULL_RES:
bounds = view.getVisibleImageBounds();
break;
case AC_VIEW_RES:
bounds = view.getLayerCanvas().getViewport().getViewBounds();
break;
default: // AC_USER_RES
bounds = new Rectangle(getWidth(), getHeight());
break;
}
}
int w = toInteger(bounds.getWidth());
int h = toInteger(bounds.getHeight());
final double freeMemory = getFreeMemory();
final double expectedMemory = getExpectedMemory(w, h);
if (freeMemory < expectedMemory) {
if (showQuestionDialog() != Dialogs.Answer.YES) {
final double scale = Math.sqrt(freeMemory / expectedMemory);
final double scaledW = w * scale;
final double scaledH = h * scale;
w = toInteger(scaledW);
h = toInteger(scaledH);
}
}
// initialize heightWidthRatio
heightWidthRatio = (double) h / (double) w;
// disable listener and set components then re-enable.
widthListenerEnabled = false;
heightListenerEnabled = false;
setWidth(w);
setHeight(h);
widthListenerEnabled = true;
heightListenerEnabled = true;
}
private int toInteger(double value) {
return MathUtils.floorInt(value);
}
private JComponent createComponent() {
PropertyPane propertyPane = new PropertyPane(bindingContext);
return propertyPane.createPanel();
}
public Dimension getDimension() {
return new Dimension(getWidth(), getHeight());
}
private void initValueContainer() {
final PropertyDescriptor widthDescriptor = new PropertyDescriptor(PROPERTY_NAME_WIDTH, Integer.class);
widthDescriptor.setConverter(new IntegerConverter());
propertyContainer.addProperty(new Property(widthDescriptor, new DefaultPropertyAccessor()));
final PropertyDescriptor heightDescriptor = new PropertyDescriptor(PROPERTY_NAME_HEIGHT, Integer.class);
heightDescriptor.setConverter(new IntegerConverter());
propertyContainer.addProperty(new Property(heightDescriptor, new DefaultPropertyAccessor()));
propertyContainer.addPropertyChangeListener(PROPERTY_NAME_WIDTH, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
// Width has been changed to auto-adjust the height to maintain the current heightWidthRatio
boolean originalHeightListenerEnable = heightListenerEnabled;
heightListenerEnabled = false;
if (widthListenerEnabled) {
Double newHeight = (double) getWidth() * heightWidthRatio;
setHeight((int) Math.round(newHeight));
}
heightListenerEnabled = originalHeightListenerEnable;
}
});
propertyContainer.addPropertyChangeListener(PROPERTY_NAME_HEIGHT, new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
// Height has been changed to auto-adjust the width to maintain the current heightWidthRatio
boolean originalWidthListenerEnabled = widthListenerEnabled;
widthListenerEnabled = false;
if (heightListenerEnabled) {
Double newWidth = (double) getHeight() / heightWidthRatio;
setWidth((int) Math.round(newWidth));
}
widthListenerEnabled = originalWidthListenerEnabled;
}
});
}
private Dialogs.Answer showQuestionDialog() {
return Dialogs.requestDecision(Bundle.CTL_ExportImageAction_MenuText(),
"There may not be enough memory to export the image because\n" +
"the image dimension is too large. \n Do you really want to keep the image dimension?",
true, null);
}
private long getFreeMemory() {
final long usedMemory = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
return Runtime.getRuntime().maxMemory() - usedMemory;
}
private long getExpectedMemory(int width, int height) {
return width * height * 6L;
}
private int getWidth() {
return (Integer) propertyContainer.getValue(PROPERTY_NAME_WIDTH);
}
private void setWidth(Object value) {
propertyContainer.setValue(PROPERTY_NAME_WIDTH, value);
}
private int getHeight() {
return (Integer) propertyContainer.getValue(PROPERTY_NAME_HEIGHT);
}
private void setHeight(Object value) {
propertyContainer.setValue(PROPERTY_NAME_HEIGHT, value);
}
}
}
| 22,881 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RangeFinderInteractor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/RangeFinderInteractor.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.actions.interactors;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.swing.figure.ViewportInteractor;
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.dataop.maptransf.Ellipsoid;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.util.ImageUtilities;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
import java.awt.BasicStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Stroke;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;
/**
* A tool representing the range finder.
*
* @author Sabine Embacher
* @author Ralf Quast
* @author Marco Zuehlke
*/
class RangeFinderInteractor extends ViewportInteractor {
public static final String TITLE = "Range Finder Tool";
private static class ModelPoint extends Point2D.Double {
private static ModelPoint create(Viewport viewport, Point point) {
return new ModelPoint(viewport.getViewToModelTransform().transform(point, new Double()));
}
private ModelPoint() {
super();
}
private ModelPoint(Point2D p) {
super(p.getX(), p.getY());
}
private Point toViewPoint(Viewport viewport) {
return (Point) viewport.getModelToViewTransform().transform(this, new Point());
}
}
private final List<ModelPoint> modelPointList;
private final ModelPoint currentModelPoint;
private final Cursor cursor;
private RangeFinderOverlay overlay;
public RangeFinderInteractor() {
modelPointList = new ArrayList<>();
currentModelPoint = new ModelPoint();
ImageIcon cursorIcon = ImageUtilities.loadImageIcon("org/esa/snap/rcp/cursors/RangeFinder.gif", false);
cursor = createRangeFinderCursor(cursorIcon);
}
@Override
public Cursor getCursor() {
return cursor;
}
@Override
public void mouseDragged(MouseEvent e) {
handleDragAndMove(e);
}
@Override
public void mouseMoved(MouseEvent e) {
handleDragAndMove(e);
}
@Override
public void mouseClicked(MouseEvent e) {
final ProductSceneView view = getProductSceneView(e);
if (view == null) {
return;
}
if (overlay != null && view != overlay.view) {
removeOverlay();
}
if (overlay == null) {
createOverlay(view);
}
if (e.getClickCount() == 1) {
final Point viewPoint = e.getPoint();
final ModelPoint modelPoint = ModelPoint.create(view.getViewport(), viewPoint);
modelPointList.add(modelPoint);
currentModelPoint.setLocation(modelPoint);
overlay.repaint();
}
if (e.getClickCount() == 2 && modelPointList.size() > 0) {
showDetailsDialog(view);
modelPointList.clear();
removeOverlay();
}
}
private void handleDragAndMove(MouseEvent e) {
if (modelPointList.size() > 0 && overlay != null) {
final ProductSceneView view = getProductSceneView(e);
if (view != null) {
final Point viewPoint = e.getPoint();
final ModelPoint modelPoint = ModelPoint.create(view.getViewport(), viewPoint);
currentModelPoint.setLocation(modelPoint);
overlay.repaint();
}
}
}
private void createOverlay(ProductSceneView view) {
overlay = new RangeFinderOverlay(view);
view.getLayerCanvas().addOverlay(overlay);
}
private void removeOverlay() {
overlay.view.getLayerCanvas().removeOverlay(overlay);
overlay = null;
}
private ProductSceneView getProductSceneView(MouseEvent event) {
final Component eventComponent = event.getComponent();
if (eventComponent instanceof ProductSceneView) {
return (ProductSceneView) eventComponent;
}
final Container parentComponent = eventComponent.getParent();
if (parentComponent instanceof ProductSceneView) {
return (ProductSceneView) parentComponent;
}
// Case: Scroll bars are displayed
if (parentComponent.getParent() instanceof ProductSceneView) {
return (ProductSceneView) parentComponent.getParent();
}
return null;
}
private void showDetailsDialog(ProductSceneView view) {
//todo [multisize_products] ask for scenerastertransform instead of geocoding
GeoCoding geoCoding = view.getRaster().getGeoCoding();
if (geoCoding == null) {
Dialogs.showInformation(TITLE, String.format("No geo-coding information for %s.", view.getRaster().getName()), null);
return;
}
float distance = 0;
float distanceError = 0;
final AffineTransform m2i = view.getBaseImageLayer().getModelToImageTransform();
final Point imagePoint1 = new Point();
final Point imagePoint2 = new Point();
final DistanceData[] distanceData = new DistanceData[modelPointList.size() - 1];
for (int i = 0; i < distanceData.length; i++) {
m2i.transform(modelPointList.get(i), imagePoint1);
m2i.transform(modelPointList.get(i + 1), imagePoint2);
final DistanceData segmentData = new DistanceData(geoCoding, imagePoint1, imagePoint2);
distance += segmentData.distance;
distanceError += segmentData.distanceError;
distanceData[i] = segmentData;
}
final JButton detailsButton = new JButton("Details...");
detailsButton.addActionListener(e -> {
final Window parentWindow = SwingUtilities.getWindowAncestor(detailsButton);
createDetailsDialog(parentWindow, distanceData).show();
});
final JPanel buttonPane = new JPanel(new BorderLayout());
buttonPane.add(detailsButton, BorderLayout.EAST);
final JPanel messagePane = new JPanel(new BorderLayout(0, 6));
messagePane.add(new JLabel("Distance: " + distance + " +/- " + distanceError + " km"));
messagePane.add(buttonPane, BorderLayout.SOUTH);
JOptionPane.showMessageDialog(SnapApp.getDefault().getMainFrame(), messagePane,
TITLE,
JOptionPane.INFORMATION_MESSAGE);
}
private static ModalDialog createDetailsDialog(final Window parentWindow, final DistanceData[] dds) {
float distance = 0;
float distanceError = 0;
final StringBuilder message = new StringBuilder();
for (int i = 0; i < dds.length; i++) {
final DistanceData dd = dds[i];
distance += dd.distance;
distanceError += dd.distanceError;
message.append(
"Distance between points " + i + " to " + (i + 1) + " in pixels:\n" +
"XH[" + dd.xH + "] to XN[" + dd.xN + "]: " + Math.abs(dd.xH - dd.xN) + "\n" +
"YH[" + dd.yH + "] to YN[" + dd.yN + "]: " + Math.abs(dd.yH - dd.yN) + "\n" +
"\n" +
"LonH: " + dd.lonH + " LatH: " + dd.latH + "\n" +
"LonN: " + dd.lonN + " LatN: " + dd.latN + "\n" +
"\n" +
"LamH: " + dd.lamH + " PhiH: " + dd.phiH + "\n" +
"LamN: " + dd.lamN + " PhiN: " + dd.phiN + "\n" +
"\n" +
"Mean earth radius used: " + DistanceData.MEAN_EARTH_RADIUS_KM + " km" + "\n" +
"\n" +
"Distance: " + dd.distance + " +/- " + dd.distanceError + " km\n" +
"\n\n"
);
}
message.insert(0, "Total distance: " + distance + " +/- " + distanceError + " km\n" +
"\n" +
"computed as described below:\n\n");
final JScrollPane content = new JScrollPane(new JTextArea(message.toString()));
content.setPreferredSize(new Dimension(300, 150));
final ModalDialog detailsWindow = new ModalDialog(parentWindow, TITLE + " - Details", ModalDialog.ID_OK, null);
detailsWindow.setContent(content);
return detailsWindow;
}
private static Cursor createRangeFinderCursor(ImageIcon cursorIcon) {
Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
final String cursorName = "rangeFinder";
// this is necessary because on some systems the cursor is scaled but not the 'hot spot'
Dimension bestCursorSize = defaultToolkit.getBestCursorSize(cursorIcon.getIconWidth(), cursorIcon.getIconHeight());
Point hotSpot = new Point((7 * bestCursorSize.width) / cursorIcon.getIconWidth(),
(7 * bestCursorSize.height) / cursorIcon.getIconHeight());
return defaultToolkit.createCustomCursor(cursorIcon.getImage(), hotSpot, cursorName);
}
private class RangeFinderOverlay implements LayerCanvas.Overlay {
private final ProductSceneView view;
RangeFinderOverlay(ProductSceneView view) {
this.view = view;
}
void repaint() {
view.getLayerCanvas().repaint();
}
@Override
public void paintOverlay(LayerCanvas canvas, Rendering rendering) {
if (modelPointList.size() == 0) {
return;
}
Graphics2D g2d = rendering.getGraphics();
final Stroke strokeOld = g2d.getStroke();
g2d.setStroke(new BasicStroke(1.0f));
final Color colorOld = g2d.getColor();
g2d.setColor(Color.white);
g2d.translate(0.5, 0.5);
final int r = 3;
final int r2 = r * 2;
Point viewPoint1 = null;
Point viewPoint2 = null;
final Viewport viewport = canvas.getViewport();
for (final ModelPoint modelPoint : modelPointList) {
viewPoint1 = modelPoint.toViewPoint(viewport);
g2d.drawOval(viewPoint1.x - r, viewPoint1.y - r, r2, r2);
g2d.drawLine(viewPoint1.x, viewPoint1.y - r2, viewPoint1.x, viewPoint1.y - r);
g2d.drawLine(viewPoint1.x, viewPoint1.y + r2, viewPoint1.x, viewPoint1.y + r);
g2d.drawLine(viewPoint1.x - r2, viewPoint1.y, viewPoint1.x - r, viewPoint1.y);
g2d.drawLine(viewPoint1.x + r2, viewPoint1.y, viewPoint1.x + r, viewPoint1.y);
if (viewPoint2 != null) {
g2d.drawLine(viewPoint1.x, viewPoint1.y, viewPoint2.x, viewPoint2.y);
}
viewPoint2 = viewPoint1;
}
if (viewPoint1 != null) {
viewPoint2 = currentModelPoint.toViewPoint(canvas.getViewport());
g2d.drawLine(viewPoint1.x, viewPoint1.y, viewPoint2.x, viewPoint2.y);
}
g2d.translate(-0.5, -0.5);
g2d.setStroke(strokeOld);
g2d.setColor(colorOld);
}
}
private static class DistanceData {
final static double MIN_EARTH_RADIUS = Ellipsoid.WGS_84.getSemiMinor();
final static double MAX_EARTH_RADIUS = Ellipsoid.WGS_84.getSemiMajor();
final static double MEAN_EARTH_RADIUS_M = 6371000;
final static double MEAN_EARTH_RADIUS_KM = MEAN_EARTH_RADIUS_M * 0.001;
final static double MEAN_ERROR_FACTOR = MIN_EARTH_RADIUS / MAX_EARTH_RADIUS;
final int xH;
final int yH;
final int xN;
final int yN;
final double lonH;
final double latH;
final double lonN;
final double latN;
final double lamH;
final double phiH;
final double lamN;
final double phiN;
final double distance;
final double distanceError;
public DistanceData(GeoCoding geoCoding, final Point pH, final Point pN) {
this.xH = pH.x;
this.yH = pH.y;
this.xN = pN.x;
this.yN = pN.y;
final GeoPos geoPosH = geoCoding.getGeoPos(new PixelPos(xH, yH), null);
final GeoPos geoPosN = geoCoding.getGeoPos(new PixelPos(xN, yN), null);
this.lonH = geoPosH.getLon();
this.latH = geoPosH.getLat();
this.lonN = geoPosN.getLon();
this.latN = geoPosN.getLat();
this.lamH = (MathUtils.DTOR * lonH);
this.phiH = (MathUtils.DTOR * latH);
this.lamN = (MathUtils.DTOR * lonN);
this.phiN = (MathUtils.DTOR * latN);
this.distance = MathUtils.sphereDistance(MEAN_EARTH_RADIUS_KM, lamH, phiH, lamN, phiN);
this.distanceError = distance * (1 - MEAN_ERROR_FACTOR);
}
}
}
| 14,341 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PannerToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/PannerToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.interactions.PanInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.PannerToolAction"
)
@ActionRegistration(
displayName = "#CTL_PannerToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 110
)
@Messages({
"CTL_PannerToolActionText=Pan",
"CTL_PannerToolActionDescription=Panning tool"
})
public class PannerToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public PannerToolAction() {
this(null);
}
public PannerToolAction(Lookup lookup) {
super(lookup, new PanInteractor());
putValue(NAME, Bundle.CTL_PannerToolActionText());
putValue(SELECTED_KEY, true); //Set Image Panning Tool as default
putValue(SHORT_DESCRIPTION, Bundle.CTL_PannerToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/PannerTool24.gif", false));
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("panTool");
}
} | 2,245 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ZoomToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/ZoomToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.interactions.ZoomInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.ZoomToolAction"
)
@ActionRegistration(
displayName = "#CTL_ZoomToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 120
)
@Messages({
"CTL_ZoomToolActionText=Zoom",
"CTL_ZoomToolActionDescription=Zooming tool"
})
public class ZoomToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public ZoomToolAction() {
this(null);
}
public ZoomToolAction(Lookup lookup) {
super(lookup, new ZoomInteractor());
putValue(NAME, Bundle.CTL_ZoomToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_ZoomToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/ZoomTool24.gif", false));
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("zoomTool");
}
} | 2,154 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/ToolAction.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.actions.interactors;
import com.bc.ceres.core.Assert;
import com.bc.ceres.swing.figure.AbstractInteractorListener;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.InteractorListener;
import com.bc.ceres.swing.figure.interactions.NullInteractor;
import org.esa.snap.core.util.Guardian;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.util.ContextAwareAction;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import org.openide.util.actions.Presenter;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenuItem;
import javax.swing.JToggleButton;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Logger;
/**
* Tool actions are used to interact with a {@link com.bc.ceres.swing.figure.FigureEditor FigureEditor},
* such as the VISAT product scene view.
* <p>
* Derived tool actions must at least provide two public constructors:
* <ol>
* <li>a default constructor</li>
* <li>a constructor that takes a single {@code Lookup} argument</li>
* </ol>
* <p>
* Derived actions must also tell the system to load the actions eagerly, that is, use the action registration
* as follows: {@code @ActionRegistration(displayName = "not-used", lazy = false)}.
*
* @author Norman Fomferra
*/
public abstract class ToolAction extends AbstractAction
implements ContextAwareAction, LookupListener, Presenter.Toolbar, Presenter.Menu, Presenter.Popup, HelpCtx.Provider {
public static final String INTERACTOR_KEY = "interactor";
private static final Logger LOG = Logger.getLogger(ToolAction.class.getName());
private final InteractorListener interactorListener;
private final Lookup lookup;
private final Lookup.Result<ProductSceneView> viewResult;
protected ToolAction() {
this(null);
}
protected ToolAction(Lookup lookup) {
this(lookup, NullInteractor.INSTANCE);
}
protected ToolAction(Lookup lookup, Interactor interactor) {
putValue(ACTION_COMMAND_KEY, getClass().getName());
putValue(SELECTED_KEY, false);
interactorListener = new InternalInteractorListener();
setInteractor(interactor);
this.lookup = lookup != null ? lookup : Utilities.actionsGlobalContext();
this.viewResult = this.lookup.lookupResult(ProductSceneView.class);
this.viewResult.addLookupListener(WeakListeners.create(LookupListener.class, this, viewResult));
updateEnabledState();
}
public ProductSceneView getProductSceneView() {
return lookup.lookup(ProductSceneView.class);
}
@Override
public Component getToolbarPresenter() {
JToggleButton toggleButton = new JToggleButton(this);
toggleButton.setText(null);
return toggleButton;
}
@Override
public JMenuItem getMenuPresenter() {
return new JCheckBoxMenuItem(this);
}
@Override
public JMenuItem getPopupPresenter() {
return getMenuPresenter();
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
try {
Constructor<? extends ToolAction> constructor = getClass().getConstructor(Lookup.class);
return constructor.newInstance(actionContext);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException(e);
}
}
@Override
public void resultChanged(LookupEvent ignored) {
updateEnabledState();
if (isEnabled() && isSelected()) {
ProductSceneView productSceneView = getProductSceneView();
if (productSceneView != null) {
Interactor oldInteractor = productSceneView.getFigureEditor().getInteractor();
Interactor newInteractor = getInteractor();
if (oldInteractor != newInteractor) {
oldInteractor.deactivate();
newInteractor.activate();
productSceneView.getFigureEditor().setInteractor(newInteractor);
}
}
}
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
onSelectionStateChanged();
}
public Lookup getLookup() {
return lookup;
}
public boolean isSelected() {
return Boolean.TRUE.equals(getValue(SELECTED_KEY));
}
public void setSelected(boolean selected) {
putValue(SELECTED_KEY, selected);
}
public Interactor getInteractor() {
return (Interactor) getValue(INTERACTOR_KEY);
}
public final void setInteractor(Interactor interactor) {
Guardian.assertNotNull("interactor", interactor);
Interactor oldInteractor = getInteractor();
if (interactor == oldInteractor) {
return;
}
if (oldInteractor != null) {
oldInteractor.removeListener(interactorListener);
}
interactor.addListener(interactorListener);
putValue(INTERACTOR_KEY, interactor);
}
protected void updateEnabledState() {
super.setEnabled(!viewResult.allInstances().isEmpty());
}
private void onSelectionStateChanged() {
LOG.fine(String.format(">>> %s#onSelectionStateChanged: selected = %s, interactor = %s%n", getClass().getName(), isSelected(), getInteractor()));
ProductSceneView productSceneView = getProductSceneView();
if (productSceneView != null && isSelected()) {
Interactor oldInteractor = productSceneView.getFigureEditor().getInteractor();
Interactor newInteractor = getInteractor();
Assert.notNull(newInteractor, "No interactor set on action " + getClass());
if (oldInteractor != newInteractor && oldInteractor.isActive()) {
oldInteractor.deactivate();
}
if (!newInteractor.isActive()) {
newInteractor.activate();
}
productSceneView.getFigureEditor().setInteractor(newInteractor);
}
}
private class InternalInteractorListener extends AbstractInteractorListener {
@Override
public void interactorActivated(Interactor interactor) {
LOG.fine(String.format(">>> %s#interactorActivated: interactor = %s%n", getClass().getName(), interactor));
if (interactor == getInteractor() && !isSelected()) {
setSelected(true);
}
}
@Override
public void interactorDeactivated(Interactor interactor) {
LOG.fine(String.format(">>> %s#interactorDeactivated: interactor = %s%n", getClass().getName(), interactor));
if (interactor == getInteractor() && isSelected()) {
setSelected(false);
}
}
}
}
| 7,885 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PinToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/PinToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import org.esa.snap.rcp.placemark.InsertPinInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.PinToolAction"
)
@ActionRegistration(
displayName = "#CTL_PinToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 130
)
@Messages({
"CTL_PinToolActionText=Pin Tool",
"CTL_PinToolActionDescription=Pin placing tool"
})
public class PinToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public PinToolAction() {
this(null);
}
public PinToolAction(Lookup lookup) {
super(lookup, new InsertPinInteractor());
putValue(NAME, Bundle.CTL_PinToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_PinToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/PinTool24.gif", false));
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("pinTool");
}
} | 2,149 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
InsertFigureInteractorInterceptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/InsertFigureInteractorInterceptor.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.actions.interactors;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerFilter;
import com.bc.ceres.glayer.support.LayerUtils;
import com.bc.ceres.swing.figure.AbstractInteractorInterceptor;
import com.bc.ceres.swing.figure.Interactor;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.rcp.actions.vector.CreateVectorDataNodeAction;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.VectorDataLayer;
import org.esa.snap.ui.product.VectorDataLayerFilterFactory;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.event.InputEvent;
import java.util.List;
public class InsertFigureInteractorInterceptor extends AbstractInteractorInterceptor {
@Override
public boolean interactionAboutToStart(Interactor interactor, InputEvent inputEvent) {
final ProductSceneView productSceneView = getProductSceneView(inputEvent);
return getActiveVectorDataLayer(productSceneView) != null;
}
public static VectorDataLayer getActiveVectorDataLayer(ProductSceneView productSceneView) {
if (productSceneView == null) {
return null;
}
final LayerFilter geometryFilter = VectorDataLayerFilterFactory.createGeometryFilter();
Layer layer = productSceneView.getSelectedLayer();
if (geometryFilter.accept(layer)) {
layer.setVisible(true);
return (VectorDataLayer) layer;
}
List<Layer> layers = LayerUtils.getChildLayers(productSceneView.getRootLayer(),
LayerUtils.SEARCH_DEEP, geometryFilter);
VectorDataLayer vectorDataLayer;
if (layers.isEmpty()) {
VectorDataNode vectorDataNode = CreateVectorDataNodeAction.createDefaultVectorDataNode(productSceneView.getProduct());
LayerFilter nodeFilter = VectorDataLayerFilterFactory.createNodeFilter(vectorDataNode);
productSceneView.getVectorDataCollectionLayer(true);
vectorDataLayer = (VectorDataLayer) LayerUtils.getChildLayer(productSceneView.getRootLayer(),
LayerUtils.SEARCH_DEEP, nodeFilter);
} else if (layers.size() == 1) {
vectorDataLayer = (VectorDataLayer) layers.get(0);
} else {
vectorDataLayer = showSelectLayerDialog(productSceneView, layers);
}
if (vectorDataLayer == null) {
// = Cancel
return null;
}
productSceneView.setSelectedLayer(vectorDataLayer);
if (productSceneView.getSelectedLayer() == vectorDataLayer) {
vectorDataLayer.setVisible(true);
return vectorDataLayer;
}
return null;
}
static private VectorDataLayer showSelectLayerDialog(ProductSceneView productSceneView, List<Layer> layers) {
String[] layerNames = new String[layers.size()];
for (int i = 0; i < layerNames.length; i++) {
layerNames[i] = layers.get(i).getName();
}
JList<String> listBox = new JList<>(layerNames);
JPanel panel = new JPanel(new BorderLayout(4, 4));
panel.add(new JLabel("Please select a vector data container:"), BorderLayout.NORTH);
panel.add(new JScrollPane(listBox), BorderLayout.CENTER);
ModalDialog dialog = new ModalDialog(SwingUtilities.getWindowAncestor(productSceneView),
"Select Vector Data Container",
ModalDialog.ID_OK_CANCEL_HELP, "");
dialog.setContent(panel);
int i = dialog.show();
if (i == ModalDialog.ID_OK) {
final int index = listBox.getSelectedIndex();
if (index >= 0) {
return (VectorDataLayer) layers.get(index);
}
}
return null;
}
private ProductSceneView getProductSceneView(InputEvent event) {
ProductSceneView productSceneView = null;
Component component = event.getComponent();
while (component != null) {
if (component instanceof ProductSceneView) {
productSceneView = (ProductSceneView) component;
break;
}
component = component.getParent();
}
return productSceneView;
}
}
| 5,302 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DrawRectangleToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/DrawRectangleToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.interactions.InsertRectangleFigureInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.DrawRectangleToolAction"
)
@ActionRegistration(
displayName = "#CTL_DrawRectangleToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 170
)
@Messages({
"CTL_DrawRectangleToolActionText=Draw Rectangle",
"CTL_DrawRectangleToolActionDescription=Rectangle drawing tool"
})
public class DrawRectangleToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public DrawRectangleToolAction() {
this(null);
}
public DrawRectangleToolAction(Lookup lookup) {
super(lookup);
putValue(NAME, Bundle.CTL_DrawRectangleToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_DrawRectangleToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/DrawRectangleTool24.gif", false));
Interactor interactor = new InsertRectangleFigureInteractor();
interactor.addListener(new InsertFigureInteractorInterceptor());
setInteractor(interactor);
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("drawRectangleTool");
}
} | 2,491 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DrawEllipseToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/DrawEllipseToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.interactions.InsertEllipseFigureInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.DrawEllipseToolAction"
)
@ActionRegistration(
displayName = "#CTL_DrawEllipseToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 190
)
@Messages({
"CTL_DrawEllipseToolActionText=Draw Ellipse",
"CTL_DrawEllipseToolActionDescription=Ellipse drawing tool"
})
public class DrawEllipseToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public DrawEllipseToolAction() {
this(null);
}
public DrawEllipseToolAction(Lookup lookup) {
super(lookup);
putValue(NAME, Bundle.CTL_DrawEllipseToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_DrawEllipseToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/DrawEllipseTool24.gif", false));
Interactor interactor = new InsertEllipseFigureInteractor();
interactor.addListener(new InsertFigureInteractorInterceptor());
setInteractor(interactor);
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("drawEllipseTool");
}
} | 2,462 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SelectToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/SelectToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.interactions.SelectionInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.SelectToolAction"
)
@ActionRegistration(
displayName = "#CTL_SelectToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 100
)
@Messages({
"CTL_SelectToolActionText=Select",
"CTL_SelectToolActionDescription=Selection tool"
})
public class SelectToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public SelectToolAction() {
this(null);
}
public SelectToolAction(Lookup lookup) {
super(lookup);
putValue(NAME, Bundle.CTL_SelectToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_SelectToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/SelectTool24.gif", false));
Interactor interactor = new SelectionInteractor();
interactor.addListener(new SelectionInteractorInterceptor());
setInteractor(interactor);
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("selectTool");
}
} | 2,373 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SelectionInteractorInterceptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/SelectionInteractorInterceptor.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.actions.interactors;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerFilter;
import com.bc.ceres.glayer.support.LayerUtils;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.swing.figure.AbstractInteractorInterceptor;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.FigureEditor;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.interactions.SelectionInteractor;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.VectorDataFigureEditor;
import org.esa.snap.ui.product.VectorDataLayer;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.InputEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
class SelectionInteractorInterceptor extends AbstractInteractorInterceptor {
@Override
public void interactionStopped(Interactor interactor, InputEvent inputEvent) {
if (interactor instanceof SelectionInteractor) {
final SelectionInteractor selectionInteractor = (SelectionInteractor) interactor;
FigureEditor editor = selectionInteractor.getFigureEditor(inputEvent);
if (editor instanceof VectorDataFigureEditor && inputEvent instanceof MouseEvent) {
final VectorDataFigureEditor figureEditor = (VectorDataFigureEditor) editor;
final MouseEvent mouseEvent = (MouseEvent) inputEvent;
// preferring rectangle selection on current selected layer
if (!isSelectionOnCurrentLayer(figureEditor, mouseEvent)) {
findLayerForSelection(figureEditor, mouseEvent);
}
}
}
}
private boolean isSelectionOnCurrentLayer(VectorDataFigureEditor figureEditor, MouseEvent mouseEvent) {
Layer selectedLayer = figureEditor.getProductSceneView().getSelectedLayer();
if (selectedLayer instanceof VectorDataLayer) {
VectorDataLayer vectorDataLayer = (VectorDataLayer) selectedLayer;
return getFigures(vectorDataLayer, figureEditor, mouseEvent).length > 0;
}
return false;
}
private static Figure[] getFigures(VectorDataLayer vectorDataLayer, VectorDataFigureEditor figureEditor, MouseEvent mouseEvent) {
Viewport viewport = figureEditor.getViewport();
AffineTransform v2mTransform = viewport.getViewToModelTransform();
Rectangle rectangle = figureEditor.getSelectionRectangle();
Figure[] figures = new Figure[0];
if (rectangle != null) {
Shape shape = v2mTransform.createTransformedShape(rectangle);
figures = vectorDataLayer.getFigureCollection().getFigures(shape);
} else {
v2mTransform.transform(mouseEvent.getPoint(), null);
Point2D modelPoint = v2mTransform.transform(mouseEvent.getPoint(), null);
AffineTransform m2vTransform = viewport.getModelToViewTransform();
Figure figure = vectorDataLayer.getFigureCollection().getFigure(modelPoint, m2vTransform);
if (figure != null) {
figures = new Figure[]{figure};
}
}
return figures;
}
private void findLayerForSelection(VectorDataFigureEditor figureEditor, MouseEvent mouseEvent) {
LayerWithNearFigureFilter figureFilter = new LayerWithNearFigureFilter(figureEditor, mouseEvent);
final ProductSceneView sceneView = figureEditor.getProductSceneView();
final Layer rootLayer = sceneView.getRootLayer();
selectLayer(rootLayer, figureFilter);
}
private void selectLayer(Layer rootLayer, LayerWithNearFigureFilter figureFilter) {
LayerUtils.getChildLayer(rootLayer, LayerUtils.SearchMode.DEEP, figureFilter);
}
private static class LayerWithNearFigureFilter implements LayerFilter {
private VectorDataFigureEditor figureEditor;
private final MouseEvent mouseEvent;
public LayerWithNearFigureFilter(VectorDataFigureEditor figureEditor, MouseEvent mouseEvent) {
this.figureEditor = figureEditor;
this.mouseEvent = mouseEvent;
}
@Override
public boolean accept(Layer layer) {
if (layer instanceof VectorDataLayer) {
VectorDataLayer vectorDataLayer = (VectorDataLayer) layer;
final Figure[] figures = getFigures(vectorDataLayer, figureEditor, mouseEvent);
if (figures.length > 0) {
ProductSceneView sceneView = figureEditor.getProductSceneView();
// selectVectorDataLayer changes selectionRectangle
// to preserve selection get rectangle first and set it afterwards
Rectangle selectionRectangle = figureEditor.getSelectionRectangle();
sceneView.selectVectorDataLayer(vectorDataLayer.getVectorDataNode());
if (selectionRectangle != null) {
figureEditor.setSelectionRectangle(selectionRectangle);
}
return true;
}
}
return false;
}
}
}
| 5,944 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DrawLineToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/DrawLineToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.interactions.InsertLineFigureInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.DrawLineToolAction"
)
@ActionRegistration(
displayName = "#CTL_DrawLineToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 150
)
@Messages({
"CTL_DrawLineToolActionText=Draw Line",
"CTL_DrawLineToolActionDescription=Line drawing tool"
})
public class DrawLineToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public DrawLineToolAction() {
this(null);
}
public DrawLineToolAction(Lookup lookup) {
super(lookup);
putValue(NAME, Bundle.CTL_DrawLineToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_DrawLineToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/DrawLineTool24.gif", false));
Interactor interactor = new InsertLineFigureInteractor();
interactor.addListener(new InsertFigureInteractorInterceptor());
setInteractor(interactor);
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("drawLineTool");
}
} | 2,416 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DrawPolylineToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/DrawPolylineToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.interactions.InsertPolylineFigureInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.DrawPolylineToolAction"
)
@ActionRegistration(
displayName = "#CTL_DrawPolylineToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 160
)
@Messages({
"CTL_DrawPolylineToolActionText=Draw Polyline",
"CTL_DrawPolylineToolActionDescription=Polyline drawing tool"
})
public class DrawPolylineToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public DrawPolylineToolAction() {
this(null);
}
public DrawPolylineToolAction(Lookup lookup) {
super(lookup);
putValue(NAME, Bundle.CTL_DrawPolylineToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_DrawPolylineToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/DrawPolylineTool24.gif", false));
Interactor interactor = new InsertPolylineFigureInteractor();
interactor.addListener(new InsertFigureInteractorInterceptor());
setInteractor(interactor);
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("drawPolylineTool");
}
} | 2,476 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MagicWandToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/MagicWandToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import org.esa.snap.rcp.magicwand.MagicWandInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(category = "Interactors", id = "org.esa.snap.rcp.action.interactors.MagicWandToolAction")
@ActionRegistration(displayName = "#CTL_MagicWandToolActionText", lazy = false)
@ActionReference(path = "Toolbars/Tools", position = 210)
@Messages({
"CTL_MagicWandToolActionText=Magic Wand",
"CTL_MagicWandToolActionDescription=Creates a ROI mask using a magic wand"
})
public class MagicWandToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public MagicWandToolAction() {
this(null);
}
public MagicWandToolAction(Lookup lookup) {
super(lookup, new MagicWandInteractor());
putValue(NAME, Bundle.CTL_MagicWandToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_MagicWandToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/MagicWand22.png", false));
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("magicWandTool");
}
} | 2,150 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RangeFinderAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/RangeFinderAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(category = "Interactors", id = "org.esa.snap.rcp.action.interactors.RangeFinderAction" )
@ActionRegistration(displayName = "#CTL_RangeFinderActionText", lazy = false )
@ActionReference(path = "Toolbars/Tools", position = 200 )
@Messages({
"CTL_RangeFinderActionText=Range Finder",
"CTL_RangeFinderActionDescription=Determines the distance between two points"
})
public class RangeFinderAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public RangeFinderAction() {
this(null);
}
public RangeFinderAction(Lookup lookup) {
super(lookup, new RangeFinderInteractor());
putValue(NAME, Bundle.CTL_RangeFinderActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_RangeFinderActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/RangeFinder24.gif", false));
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx("rangeFinder");
}
} | 2,033 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DrawPolygonToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/DrawPolygonToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import com.bc.ceres.swing.figure.Interactor;
import com.bc.ceres.swing.figure.interactions.InsertPolygonFigureInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.DrawPolygonToolAction"
)
@ActionRegistration(
displayName = "#CTL_DrawPolygonToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 180
)
@Messages({
"CTL_DrawPolygonToolActionText=Draw Polygon",
"CTL_DrawPolygonToolActionDescription=Polygon drawing tool"
})
public class DrawPolygonToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public DrawPolygonToolAction() {
this(null);
}
public DrawPolygonToolAction(Lookup lookup) {
super(lookup);
putValue(NAME, Bundle.CTL_DrawPolygonToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_DrawPolygonToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/DrawPolygonTool24.gif", false));
Interactor interactor = new InsertPolygonFigureInteractor();
interactor.addListener(new InsertFigureInteractorInterceptor());
setInteractor(interactor);
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("drawPolygonTool");
}
} | 2,461 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GcpToolAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/interactors/GcpToolAction.java | /*
* Copyright (C) 2014 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.actions.interactors;
import org.esa.snap.rcp.placemark.InsertGcpInteractor;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.HelpCtx;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.NbBundle.Messages;
import javax.swing.*;
@ActionID(
category = "Interactors",
id = "org.esa.snap.rcp.action.interactors.GcpToolAction"
)
@ActionRegistration(
displayName = "#CTL_GcpToolActionText",
lazy = false
)
@ActionReference(
path = "Toolbars/Tools",
position = 140
)
@Messages({
"CTL_GcpToolActionText=GCP Tool",
"CTL_GcpToolActionDescription=GCP placing tool"
})
public class GcpToolAction extends ToolAction {
@SuppressWarnings("UnusedDeclaration")
public GcpToolAction() {
this(null);
}
public GcpToolAction(Lookup lookup) {
super(lookup, new InsertGcpInteractor());
putValue(NAME, Bundle.CTL_GcpToolActionText());
putValue(SHORT_DESCRIPTION, Bundle.CTL_GcpToolActionDescription());
putValue(SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/GcpTool24.gif", false));
}
@Override
public HelpCtx getHelpCtx() {
// TODO: Make sure help page is available for ID
return new HelpCtx("gcpTool");
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new GcpToolAction(actionContext);
}
} | 2,311 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SelectionActions.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/edit/SelectionActions.java | package org.esa.snap.rcp.actions.edit;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle.Messages;
/**
* Global selection actions (action keys).
*
* @author Norman
*/
@Messages({
"CTL_SelectAllActionName=Select &All",
"CTL_DeselectAllActionName=&Deselect All"
})
public interface SelectionActions {
/**
* The "select-all" action key.
*/
@ActionID(
category = "Edit",
id = "org.esa.snap.rcp.actions.edit.SelectAllAction"
)
@ActionRegistration(
displayName = "#CTL_SelectAllActionName"
)
@ActionReferences({
@ActionReference(path = "Menu/Edit", position = 10000),
@ActionReference(path = "Shortcuts", name = "D-A")
})
String SELECT_ALL = "select-all";
/**
* The "deselect-all" action key.
*/
@ActionID(
category = "Edit",
id = "org.esa.snap.rcp.actions.edit.DeselectAllAction"
)
@ActionRegistration(
displayName = "#CTL_DeselectAllActionName"
)
@ActionReferences({
@ActionReference(path = "Menu/Edit", position = 10001),
@ActionReference(path = "Shortcuts", name = "D-D")
})
String DESELECT_ALL = "deselect-all";
}
| 1,381 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractImportVectorDataNodeAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/AbstractImportVectorDataNodeAction.java | package org.esa.snap.rcp.actions.vector;
import org.esa.snap.core.dataio.geometry.VectorDataNodeReader;
import org.esa.snap.core.datamodel.GeometryDescriptor;
import org.esa.snap.core.datamodel.PlacemarkDescriptor;
import org.esa.snap.core.datamodel.PlacemarkDescriptorRegistry;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.FeatureUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.ui.ModalDialog;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.SwingUtilities;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
/**
* @author olafd
* @author Thomas Storm
*/
abstract class AbstractImportVectorDataNodeAction extends AbstractSnapAction {
protected FeatureUtils.FeatureCrsProvider crsProvider;
protected VectorDataNodeReader.PlacemarkDescriptorProvider placemarkDescriptorProvider;
private int featureCrsDialogResult;
protected AbstractImportVectorDataNodeAction() {
crsProvider = new MyFeatureCrsProvider();
placemarkDescriptorProvider = new MyPlacemarkDescriptorProvider();
}
private class MyPlacemarkDescriptorProvider implements VectorDataNodeReader.PlacemarkDescriptorProvider {
@Override
public PlacemarkDescriptor getPlacemarkDescriptor(SimpleFeatureType simpleFeatureType) {
PlacemarkDescriptorRegistry placemarkDescriptorRegistry = PlacemarkDescriptorRegistry.getInstance();
if (simpleFeatureType.getUserData().containsKey(PlacemarkDescriptorRegistry.PROPERTY_NAME_PLACEMARK_DESCRIPTOR)) {
String placemarkDescriptorClass = simpleFeatureType.getUserData().get(PlacemarkDescriptorRegistry.PROPERTY_NAME_PLACEMARK_DESCRIPTOR).toString();
PlacemarkDescriptor placemarkDescriptor = placemarkDescriptorRegistry.getPlacemarkDescriptor(placemarkDescriptorClass);
if (placemarkDescriptor != null) {
return placemarkDescriptor;
}
}
List<PlacemarkDescriptor> validPlacemarkDescriptors = placemarkDescriptorRegistry.getPlacemarkDescriptors(simpleFeatureType);
if (validPlacemarkDescriptors.size() == 1) {
return validPlacemarkDescriptors.get(0);
}
if (featureCrsDialogResult == ModalDialog.ID_OK) {
TypeDialog typeDialog = new TypeDialog(SnapApp.getDefault().getMainFrame(), simpleFeatureType);
final int dialogResult = typeDialog.show();
if (dialogResult == ModalDialog.ID_OK) {
return typeDialog.getPlacemarkDescriptor();
} else if (dialogResult == ModalDialog.ID_CANCEL) {
typeDialog.close();
return null;
}
} else {
return null;
}
return PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(GeometryDescriptor.class);
}
}
private class MyFeatureCrsProvider implements FeatureUtils.FeatureCrsProvider {
@Override
public CoordinateReferenceSystem getFeatureCrs(final Product product) {
if (product.getSceneCRS() == Product.DEFAULT_IMAGE_CRS) {
return Product.DEFAULT_IMAGE_CRS;
}
final CoordinateReferenceSystem[] featureCrsBuffer = new CoordinateReferenceSystem[1];
Runnable runnable = () -> featureCrsBuffer[0] = promptForFeatureCrs(product);
if (!SwingUtilities.isEventDispatchThread()) {
try {
SwingUtilities.invokeAndWait(runnable);
} catch (InterruptedException | InvocationTargetException e) {
throw new RuntimeException(e);
}
} else {
runnable.run();
}
CoordinateReferenceSystem featureCrs = featureCrsBuffer[0];
return featureCrs != null ? featureCrs : DefaultGeographicCRS.WGS84;
}
@Override
public boolean clipToProductBounds() {
return true;
}
private CoordinateReferenceSystem promptForFeatureCrs(Product product) {
final FeatureCrsDialog dialog = new FeatureCrsDialog(product, "Import " + getVectorDataType() + " Data");
featureCrsDialogResult = dialog.show();
if (featureCrsDialogResult == ModalDialog.ID_OK) {
return dialog.getFeatureCrs();
}
return DefaultGeographicCRS.WGS84;
}
}
protected abstract String getDialogTitle();
protected abstract String getVectorDataType();
}
| 4,825 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImportVectorDataNodeFromMermaidAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/ImportVectorDataNodeFromMermaidAction.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.actions.vector;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.dataio.geometry.VectorDataNodeReader;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
@ActionID(category = "File", id = "ImportVectorDataNodeFromMermaidAction" )
@ActionRegistration(displayName = "#CTL_ImportVectorDataNodeFromMermaidActionText", lazy=false)
@ActionReferences({
@ActionReference(path = "Menu/File/Import/Vector Data", position = 30),
@ActionReference(path = "Menu/Vector/Import")
})
@NbBundle.Messages({
"CTL_ImportVectorDataNodeFromMermaidActionText=MERMAID Extraction File",
"CTL_ImportVectorDataNodeFromMermaidActionDescription=Import Vector Data Node from Mermaid",
"CTL_ImportVectorDataNodeFromMermaidActionHelp=importMermaid"
})
public class ImportVectorDataNodeFromMermaidAction extends AbstractImportVectorDataNodeAction implements ContextAwareAction, LookupListener {
private Lookup lookup;
private final Lookup.Result<ProductNode> result;
private VectorDataNodeImporter importer;
private static final String vector_data_type = "CSV";
public ImportVectorDataNodeFromMermaidAction() {
this(Utilities.actionsGlobalContext());
}
public ImportVectorDataNodeFromMermaidAction(Lookup lookup) {
this.lookup = lookup;
result = lookup.lookupResult(ProductNode.class);
result.addLookupListener(
WeakListeners.create(LookupListener.class, this, result));
setEnableState();
setHelpId(Bundle.CTL_ImportVectorDataNodeFromMermaidActionHelp());
putValue(Action.NAME, Bundle.CTL_ImportVectorDataNodeFromMermaidActionText());
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ImportVectorDataNodeFromMermaidActionDescription());
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ImportVectorDataNodeFromMermaidAction(lookup);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnableState();
}
private void setEnableState() {
boolean state = false;
ProductNode productNode = lookup.lookup(ProductNode.class);
if (productNode != null) {
Product product = productNode.getProduct();
state = product != null && product.getSceneGeoCoding() != null;
}
setEnabled(state);
}
@Override
public void actionPerformed(ActionEvent event) {
final SnapFileFilter filter = new SnapFileFilter(getVectorDataType(),
new String[]{".txt", ".dat", ".csv"},
"Plain text");
importer = new VectorDataNodeImporter(getHelpId(), filter, new MermaidReader(), "Import MERMAID Extraction File", "csv.io.dir");
importer.importGeometry(SnapApp.getDefault());
}
@Override
protected String getDialogTitle() {
return importer.getDialogTitle();
}
@Override
protected String getVectorDataType() {
return vector_data_type;
}
private class MermaidReader implements VectorDataNodeImporter.VectorDataNodeReader {
@Override
public VectorDataNode readVectorDataNode(File file, Product product, ProgressMonitor pm) throws IOException {
FileReader reader = null;
try {
CoordinateReferenceSystem modelCrs = product.getSceneCRS();
reader = new FileReader(file);
char delimiterChar = ';';
return VectorDataNodeReader.read(file.getName(), reader, product, crsProvider, placemarkDescriptorProvider,
modelCrs, delimiterChar, pm);
} finally {
if (reader != null) {
reader.close();
}
}
}
}
}
| 5,427 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CreateVectorDataNodeAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/CreateVectorDataNodeAction.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.actions.vector;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.Validator;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerFilter;
import com.bc.ceres.glayer.support.LayerUtils;
import com.bc.ceres.swing.binding.PropertyPane;
import org.esa.snap.core.datamodel.PlainFeatureFactory;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.nodes.UndoableProductNodeInsertion;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.VectorDataLayerFilterFactory;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.awt.UndoRedo;
import org.openide.util.ContextAwareAction;
import org.openide.util.ImageUtilities;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle.Messages;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPanel;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.text.MessageFormat;
@ActionID(category = "Tools", id = "CreateVectorDataNodeAction" )
@ActionRegistration(
displayName = "#CTL_CreateVectorDataNodeActionText",
popupText = "#CTL_CreateVectorDataNodeActionPopupText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/Vector", position = 0),
@ActionReference(path = "Toolbars/Tools", position = 191)
})
@Messages({
"CTL_CreateVectorDataNodeActionText=New Vector Data Container",
"CTL_CreateVectorDataNodeActionPopupText=New Vector Data Container"
})
public class CreateVectorDataNodeAction extends AbstractAction implements ContextAwareAction, LookupListener {
private static final String HELP_ID = "vectorDataManagement";
private static int numItems = 1;
private Lookup lkp;
private Lookup.Result<ProductNode> result;
public CreateVectorDataNodeAction() {
this(Utilities.actionsGlobalContext());
}
public CreateVectorDataNodeAction(Lookup lkp) {
super(Bundle.CTL_CreateVectorDataNodeActionText());
this.lkp = lkp;
result = this.lkp.lookupResult(ProductNode.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
putValue(Action.LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/NewVectorDataNode16.gif", false));
putValue(Action.SMALL_ICON, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/NewVectorDataNode24.gif", false));
setEnabled(false);
}
public static VectorDataNode createDefaultVectorDataNode(Product product) {
return createDefaultVectorDataNode(product,
getDefaultVectorDataNodeName(),
"Default vector data container for geometries (automatically created)");
}
public static VectorDataNode createDefaultVectorDataNode(Product product, String name, String description) {
CoordinateReferenceSystem modelCrs = product.getSceneCRS();
SimpleFeatureType type = PlainFeatureFactory.createDefaultFeatureType(modelCrs);
VectorDataNode vectorDataNode = new VectorDataNode(name, type);
vectorDataNode.setDescription(description);
product.getVectorDataGroup().add(vectorDataNode);
vectorDataNode.getPlacemarkGroup();
String oldLayerId = selectVectorDataLayer(vectorDataNode);
UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product);
if (undoManager != null) {
undoManager.addEdit(new UndoableVectorDataNodeInsertion(product, vectorDataNode, oldLayerId));
}
return vectorDataNode;
}
private static String selectVectorDataLayer(VectorDataNode vectorDataNode) {
Layer oldLayer = null;
ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView();
if (sceneView != null) {
oldLayer = sceneView.getSelectedLayer();
// todo find new solution
//SnapApp.getDefault().getProductTree().expand(vectorDataNode);
sceneView.selectVectorDataLayer(vectorDataNode);
LayerFilter nodeFilter = VectorDataLayerFilterFactory.createNodeFilter(vectorDataNode);
Layer newSelectedLayer = LayerUtils.getChildLayer(sceneView.getRootLayer(),
LayerUtils.SEARCH_DEEP,
nodeFilter);
if (newSelectedLayer != null) {
newSelectedLayer.setVisible(true);
}
}
return oldLayer != null ? oldLayer.getId() : null;
}
public static String getDefaultVectorDataNodeName() {
return "geometry";
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new CreateVectorDataNodeAction(actionContext);
}
@Override
public void resultChanged(LookupEvent ev) {
ProductNode productNode = SnapApp.getDefault().getSelectedProductNode(SnapApp.SelectionSourceHint.VIEW);
setEnabled(productNode != null);
}
@Override
public void actionPerformed(ActionEvent e) {
ProductNode productNode = SnapApp.getDefault().getSelectedProductNode(SnapApp.SelectionSourceHint.VIEW);
if (productNode == null) {
return;
}
Product product = productNode.getProduct();
if (product != null) {
DialogData dialogData = new DialogData(product.getVectorDataGroup());
PropertySet propertySet = PropertyContainer.createObjectBacked(dialogData);
propertySet.getDescriptor("name").setNotNull(true);
propertySet.getDescriptor("name").setNotEmpty(true);
propertySet.getDescriptor("name").setValidator(new NameValidator(product));
propertySet.getDescriptor("description").setNotNull(true);
final PropertyPane propertyPane = new PropertyPane(propertySet);
JPanel panel = propertyPane.createPanel();
panel.setPreferredSize(new Dimension(400, 100));
ModalDialog dialog = new MyModalDialog(propertyPane);
dialog.setContent(panel);
int i = dialog.show();
if (i == ModalDialog.ID_OK) {
createDefaultVectorDataNode(product, dialogData.name, dialogData.description);
}
}
}
private static class NameValidator implements Validator {
private final Product product;
private NameValidator(Product product) {
this.product = product;
}
@Override
public void validateValue(Property property, Object value) throws ValidationException {
String name = (String) value;
if (product.getVectorDataGroup().contains(name)) {
final String pattern = "A vector data container with name ''{0}'' already exists.\n" +
"Please choose another one.";
throw new ValidationException(MessageFormat.format(pattern, name));
}
}
}
private static class MyModalDialog extends ModalDialog {
private final PropertyPane propertyPane;
private MyModalDialog(PropertyPane propertyPane) {
super(SnapApp.getDefault().getMainFrame(),
Bundle.CTL_CreateVectorDataNodeActionText(),
ModalDialog.ID_OK_CANCEL_HELP,
HELP_ID);
this.propertyPane = propertyPane;
}
/**
* Called in order to perform input validation.
*
* @return {@code true} if and only if the validation was successful.
*/
@Override
protected boolean verifyUserInput() {
return !propertyPane.getBindingContext().hasProblems();
}
}
private static class DialogData {
private String name;
private String description;
private DialogData(ProductNodeGroup<VectorDataNode> vectorGroup) {
String defaultPrefix = getDefaultVectorDataNodeName() + "_";
name = defaultPrefix + (numItems++);
while (vectorGroup.contains(name)) {
name = defaultPrefix + (numItems++);
}
description = "";
}
}
private static class UndoableVectorDataNodeInsertion extends UndoableProductNodeInsertion<VectorDataNode> {
private String oldLayerId;
public UndoableVectorDataNodeInsertion(Product product, VectorDataNode vectorDataNode, String oldLayerId) {
super(product.getVectorDataGroup(), vectorDataNode);
this.oldLayerId = oldLayerId;
}
private static String getSelectedLayerId() {
ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView();
if (sceneView != null) {
Layer selectedLayer = sceneView.getSelectedLayer();
if (selectedLayer != null) {
return selectedLayer.getId();
}
}
return null;
}
@Override
public void undo() {
super.undo(); // removes VDN
setSelectedLayer(oldLayerId);
}
@Override
public void redo() {
oldLayerId = getSelectedLayerId();
super.redo(); // inserts VDN
selectVectorDataLayer(getProductNode());
}
private void setSelectedLayer(String layerId) {
if (layerId != null) {
ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView();
if (sceneView != null) {
Layer layer = LayerUtils.getChildLayerById(sceneView.getRootLayer(), layerId);
if (layer != null) {
sceneView.setSelectedLayer(layer);
}
}
}
}
}
}
| 11,264 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataNodeImporter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/VectorDataNodeImporter.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.actions.vector;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.locationtech.jts.geom.Polygonal;
import org.esa.snap.core.dataio.geometry.VectorDataNodeIO;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.SnapFileChooser;
import org.esa.snap.ui.product.ProductSceneView;
import org.opengis.feature.type.GeometryDescriptor;
import org.openide.util.HelpCtx;
import javax.swing.JFileChooser;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.prefs.Preferences;
import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.*;
// todo - test with shapefile that has no CRS (nf, 2012-04-05)
public class VectorDataNodeImporter implements HelpCtx.Provider {
private final String dialogTitle;
private final String shapeIoDirPreferencesKey;
private String helpId;
private SnapFileFilter filter;
private final VectorDataNodeReader reader;
public VectorDataNodeImporter(String helpId, SnapFileFilter filter, VectorDataNodeReader reader, String dialogTitle, String shapeIoDirPreferencesKey) {
this.helpId = helpId;
this.filter = filter;
this.reader = reader;
this.dialogTitle = dialogTitle;
this.shapeIoDirPreferencesKey = shapeIoDirPreferencesKey;
}
public void importGeometry(final SnapApp snapApp) {
final Preferences preferences = snapApp.getPreferences();
final SnapFileChooser fileChooser = new SnapFileChooser();
fileChooser.setDialogTitle(dialogTitle);
fileChooser.setFileFilter(filter);
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setCurrentDirectory(getIODir(preferences));
final int result = fileChooser.showOpenDialog(snapApp.getMainFrame());
if (result == JFileChooser.APPROVE_OPTION) {
final File[] files = fileChooser.getSelectedFiles();
if (files != null && files.length > 0) {
setIODir(preferences, files[0].getAbsoluteFile().getParentFile());
for(File file : files) {
importGeometry(snapApp, file);
}
}
}
}
private void importGeometry(final SnapApp snapApp, final File file) {
final Product product = snapApp.getSelectedProduct(AUTO);
if (product == null) {
return;
}
final GeoCoding geoCoding = product.getSceneGeoCoding();
if (geoCoding == null || !geoCoding.canGetPixelPos()) {
Dialogs.showError(dialogTitle, "Failed to import vector data.\n"
+
"Current geo-coding cannot convert from geographic to pixel coordinates."); /* I18N */
return;
}
VectorDataNode vectorDataNode;
try {
vectorDataNode = readGeometry(snapApp, file, product);
if (vectorDataNode == null) {
return;
}
} catch (Exception e) {
Dialogs.showError(dialogTitle, "Failed to import vector data.\n" + "An I/O Error occurred:\n"
+ e.getMessage()); /* I18N */
Debug.trace(e);
return;
}
if (vectorDataNode.getFeatureCollection().isEmpty()) {
Dialogs.showError(dialogTitle, "The vector data was loaded successfully,\n"
+ "but no part is located within the scene boundaries."); /* I18N */
return;
}
boolean individualShapes = false;
String attributeName = null;
GeometryDescriptor geometryDescriptor = vectorDataNode.getFeatureType().getGeometryDescriptor();
int featureCount = vectorDataNode.getFeatureCollection().size();
if (featureCount > 1
&& geometryDescriptor != null
&& Polygonal.class.isAssignableFrom(geometryDescriptor.getType().getBinding())) {
String text = "<html>" +
"The vector data set contains <b>" +
featureCount + "</b> polygonal shapes.<br>" +
"Shall they be imported separately?<br>" +
"<br>" +
"If you select <b>Yes</b>, the polygons can be used as individual masks<br>" +
"and they will be displayed on individual layers.</i>";
SeparateGeometriesDialog dialog = new SeparateGeometriesDialog(snapApp.getMainFrame(), vectorDataNode, helpId,
text);
int response = dialog.show();
if (response == ModalDialog.ID_CANCEL) {
return;
}
individualShapes = response == ModalDialog.ID_YES;
attributeName = dialog.getSelectedAttributeName();
}
VectorDataNode[] vectorDataNodes = VectorDataNodeIO.getVectorDataNodes(vectorDataNode, individualShapes, attributeName);
for (VectorDataNode vectorDataNode1 : vectorDataNodes) {
product.getVectorDataGroup().add(vectorDataNode1);
}
setLayersVisible(vectorDataNodes);
}
private void setLayersVisible(VectorDataNode[] vectorDataNodes) {
final ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView();
if (sceneView != null) {
sceneView.setLayersVisible(vectorDataNodes);
}
}
public static String findUniqueVectorDataNodeName(String suggestedName, ProductNodeGroup<VectorDataNode> vectorDataGroup) {
String name = suggestedName;
int index = 1;
while (vectorDataGroup.contains(name)) {
name = suggestedName + "_" + index;
index++;
}
return name;
}
private File getIODir(final Preferences preferences) {
final File dir = SystemUtils.getUserHomeDir();
return new File(preferences.get(shapeIoDirPreferencesKey, dir.getPath()));
}
public String getDialogTitle() {
return dialogTitle;
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(helpId);
}
public interface VectorDataNodeReader {
VectorDataNode readVectorDataNode(File file, Product product, ProgressMonitor pm) throws IOException;
}
private VectorDataNode readGeometry(final SnapApp snapApp,
final File file,
final Product product)
throws IOException, ExecutionException, InterruptedException {
ProgressMonitorSwingWorker<VectorDataNode, Object> worker = new ProgressMonitorSwingWorker<VectorDataNode, Object>(snapApp.getMainFrame(), "Loading vector data") {
@Override
protected VectorDataNode doInBackground(ProgressMonitor pm) throws Exception {
return reader.readVectorDataNode(file, product, pm);
}
@Override
protected void done() {
super.done();
}
};
worker.executeWithBlocking();
return worker.get();
}
private void setIODir(final Preferences preferences, final File dir) {
if (dir != null) {
preferences.put(shapeIoDirPreferencesKey, dir.getPath());
}
}
}
| 8,550 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImportVectorDataNodeFromShapefileAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/ImportVectorDataNodeFromShapefileAction.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.actions.vector;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.FeatureUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.layermanager.layersrc.shapefile.SLDUtils;
import org.geotools.feature.DefaultFeatureCollection;
import org.geotools.styling.Style;
import org.opengis.feature.simple.SimpleFeatureType;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
@ActionID(category = "File", id = "ImportVectorDataNodeFromShapefileAction")
@ActionRegistration(displayName = "#CTL_ImportVectorDataNodeFromShapefileActionText", lazy = false)
@ActionReferences({
@ActionReference(path = "Menu/File/Import/Vector Data", position = 20),
@ActionReference(path = "Menu/Vector/Import")
})
@NbBundle.Messages({
"CTL_ImportVectorDataNodeFromShapefileActionText=ESRI Shapefile",
"CTL_ImportVectorDataNodeFromShapefileActionDescription=Import Vector Data Node from Shapefile",
"CTL_ImportVectorDataNodeFromShapefileActionHelp=importShapefile"
})
public class ImportVectorDataNodeFromShapefileAction extends AbstractImportVectorDataNodeAction implements ContextAwareAction, LookupListener {
private VectorDataNodeImporter importer;
private Lookup lookup;
private final Lookup.Result<ProductNode> result;
private static final String vector_data_type = "SHAPEFILE";
public ImportVectorDataNodeFromShapefileAction() {
this(Utilities.actionsGlobalContext());
}
public ImportVectorDataNodeFromShapefileAction(Lookup lookup) {
this.lookup = lookup;
result = lookup.lookupResult(ProductNode.class);
result.addLookupListener(
WeakListeners.create(LookupListener.class, this, result));
setEnableState();
setHelpId(Bundle.CTL_ImportVectorDataNodeFromShapefileActionHelp());
putValue(Action.NAME, Bundle.CTL_ImportVectorDataNodeFromShapefileActionText());
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ImportVectorDataNodeFromShapefileActionDescription());
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ImportVectorDataNodeFromShapefileAction(lookup);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnableState();
}
private void setEnableState() {
boolean state = false;
ProductNode productNode = lookup.lookup(ProductNode.class);
if (productNode != null) {
Product product = productNode.getProduct();
state = product != null && product.getSceneGeoCoding() != null;
}
setEnabled(state);
}
@Override
public void actionPerformed(ActionEvent event) {
final SnapFileFilter filter = new SnapFileFilter(getVectorDataType(),
new String[]{".shp"},
"ESRI Shapefiles");
importer = new VectorDataNodeImporter(getHelpId(), filter, new VdnShapefileReader(), "Import Shapefile", "shape.io.dir");
importer.importGeometry(SnapApp.getDefault());
}
@Override
protected String getDialogTitle() {
return importer.getDialogTitle();
}
@Override
protected String getVectorDataType() {
return vector_data_type;
}
class VdnShapefileReader implements VectorDataNodeImporter.VectorDataNodeReader {
@Override
public VectorDataNode readVectorDataNode(File file, Product product, ProgressMonitor pm) throws IOException {
DefaultFeatureCollection featureCollection = FeatureUtils.loadShapefileForProduct(file,
product,
crsProvider,
pm);
Style[] styles = SLDUtils.loadSLD(file);
ProductNodeGroup<VectorDataNode> vectorDataGroup = product.getVectorDataGroup();
String name = VectorDataNodeImporter.findUniqueVectorDataNodeName(featureCollection.getSchema().getName().getLocalPart(),
vectorDataGroup);
if (styles.length > 0) {
SimpleFeatureType featureType = SLDUtils.createStyledFeatureType(featureCollection.getSchema());
VectorDataNode vectorDataNode = new VectorDataNode(name, featureType);
DefaultFeatureCollection styledCollection = vectorDataNode.getFeatureCollection();
String defaultCSS = vectorDataNode.getDefaultStyleCss();
SLDUtils.applyStyle(styles[0], defaultCSS, featureCollection, styledCollection);
return vectorDataNode;
} else {
return new VectorDataNode(name, featureCollection);
}
}
}
}
| 6,467 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
InsertWktGeometryAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/InsertWktGeometryAction.java | /*
* Copyright (C) 2014 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.actions.vector;
import com.bc.ceres.core.ProgressMonitor;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKTReader;
import org.esa.snap.core.datamodel.PlainFeatureFactory;
import org.esa.snap.core.util.FeatureUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.interactors.InsertFigureInteractorInterceptor;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.product.VectorDataLayer;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
/**
* An action that allows users to insert a Geometry from WKT.
*
* @author MarcoZ
* @since BEAM 5
*/
@ActionID(
category = "File",
id = "org.esa.snap.rcp.actions.vector.InsertWktGeometryAction"
)
@ActionRegistration(
displayName = "#CTL_InsertWktGeometryAction_MenuText",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/Vector", position = 11, separatorBefore = 10),
@ActionReference(path = "Context/ProductSceneView", position = 0)
})
@NbBundle.Messages({
"CTL_InsertWktGeometryAction_DialogTitle=Geometry from WKT",
"CTL_InsertWktGeometryAction_MenuText=Geometry from WKT",
"CTL_InsertWktGeometryAction_ShortDescription=Creates a geomtry from well-known-text (WKT) representation."
})
public class InsertWktGeometryAction extends AbstractAction implements ContextAwareAction,LookupListener {
private static final String DLG_TITLE = "Geometry from WKT";
private Lookup.Result<ProductSceneView> result;
private Lookup lookup;
private long currentFeatureId = System.nanoTime();
public InsertWktGeometryAction(){
this(Utilities.actionsGlobalContext());
}
public InsertWktGeometryAction(Lookup lookup) {
super(Bundle.CTL_InsertWktGeometryAction_MenuText());
this.lookup = lookup;
result = lookup.lookupResult(ProductSceneView.class);
result.addLookupListener(WeakListeners.create(LookupListener.class,this,result));
setEnabled(false);
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new InsertWktGeometryAction(actionContext);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
ProductSceneView productSceneView = lookup.lookup(ProductSceneView.class);
setEnabled(productSceneView != null);
}
@Override
public void actionPerformed(ActionEvent event) {
JTextArea textArea = new JTextArea(16, 32);
textArea.setEditable(true);
JPanel contentPanel = new JPanel(new BorderLayout(4, 4));
contentPanel.add(new JLabel("Geometry Well-Known-Text (WKT):"), BorderLayout.NORTH);
contentPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
SnapApp snapApp = SnapApp.getDefault();
ModalDialog modalDialog = new ModalDialog(snapApp.getMainFrame(),
Bundle.CTL_InsertWktGeometryAction_DialogTitle(),
ModalDialog.ID_OK_CANCEL, null);
modalDialog.setContent(contentPanel);
modalDialog.center();
if (modalDialog.show() == ModalDialog.ID_OK) {
String wellKnownText = textArea.getText();
if (wellKnownText == null || wellKnownText.isEmpty()) {
return;
}
ProductSceneView sceneView = snapApp.getSelectedProductSceneView();
VectorDataLayer vectorDataLayer = InsertFigureInteractorInterceptor.getActiveVectorDataLayer(sceneView);
if (vectorDataLayer == null) {
return;
}
SimpleFeatureType wktFeatureType = PlainFeatureFactory.createDefaultFeatureType(DefaultGeographicCRS.WGS84);
ListFeatureCollection newCollection = new ListFeatureCollection(wktFeatureType);
SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(wktFeatureType);
SimpleFeature wktFeature = featureBuilder.buildFeature("ID" + Long.toHexString(currentFeatureId++));
Geometry geometry;
try {
geometry = new WKTReader().read(wellKnownText);
} catch (ParseException e) {
snapApp.handleError("Failed to convert WKT into geometry", e);
return;
}
wktFeature.setDefaultGeometry(geometry);
newCollection.add(wktFeature);
FeatureCollection<SimpleFeatureType, SimpleFeature> productFeatures = FeatureUtils.clipFeatureCollectionToProductBounds(
newCollection,
sceneView.getProduct(),
null,
ProgressMonitor.NULL);
if (productFeatures.isEmpty()) {
Dialogs.showError(Bundle.CTL_InsertWktGeometryAction_MenuText(),
"The geometry is not contained in the product.");
} else {
vectorDataLayer.getVectorDataNode().getFeatureCollection().addAll(productFeatures);
}
}
}
}
| 6,883 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImportTrackAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/ImportTrackAction.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.actions.vector;
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.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.PlacemarkDescriptor;
import org.esa.snap.core.datamodel.PlacemarkDescriptorRegistry;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.FeatureUtils;
import org.esa.snap.core.util.io.CsvReader;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.AbstractSnapAction;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.product.ProductSceneView;
import org.geotools.data.collection.ListFeatureCollection;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.geometry.jts.GeometryCoordinateSequenceTransformer;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.AUTO;
//import org.esa.snap.visat.VisatApp;
/**
* Action that lets a user load text files that contain data associated with a geographic position,
* e.g. some kind of track. The format is:
* <pre>
* lat-1 TAB lon-1 TAB data-1 NEWLINE
* lat-2 TAB lon-2 TAB data-2 NEWLINE
* lat-3 TAB lon-3 TAB data-3 NEWLINE
* ...
* lat-n TAB lon-n TAB data-n NEWLINE
* </pre>
* <p>
* This is the format that is also used by SeaDAS 6.x in order to import ship tracks.
*
* @author Norman Fomferra
* @since BEAM 4.10
*/
@ActionID(
category = "File",
id = "ImportTrackAction"
)
@ActionRegistration(
displayName = "#CTL_ImportSeadasTrackActionName",
lazy = false
)
@ActionReferences({
@ActionReference(path = "Menu/File/Import/Vector Data", position = 50),
@ActionReference(path = "Menu/Vector/Import")
})
@NbBundle.Messages({
"CTL_ImportSeadasTrackActionText=SeaDAS 6.x Track",
"CTL_ImportSeadasTrackActionName=Import SeaDAS Track",
"CTL_ImportSeadasTrackActionHelp=importSeadasTrack"
})
public class ImportTrackAction extends AbstractSnapAction implements ContextAwareAction, LookupListener {
private Lookup lookup;
private final Lookup.Result<ProductNode> result;
public ImportTrackAction() {
this(Utilities.actionsGlobalContext());
}
public ImportTrackAction(Lookup lookup) {
this.lookup = lookup;
result = lookup.lookupResult(ProductNode.class);
result.addLookupListener(
WeakListeners.create(LookupListener.class, this, result));
setEnableState();
setHelpId(Bundle.CTL_ImportSeadasTrackActionHelp());
putValue(Action.NAME, Bundle.CTL_ImportSeadasTrackActionText());
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ImportSeadasTrackActionName());
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ImportTrackAction(lookup);
}
@Override
public void actionPerformed(ActionEvent ae) {
final File file =
Dialogs.requestFileForOpen(Bundle.CTL_ImportSeadasTrackActionName(), false, null, "importTrack.lastDir");
if (file == null) {
return;
}
final Product product = SnapApp.getDefault().getSelectedProduct(AUTO);
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection;
try {
featureCollection = readTrack(file, product.getSceneGeoCoding());
} catch (IOException e) {
Dialogs.showError(Bundle.CTL_ImportSeadasTrackActionName(), "Failed to load track file:\n" + e.getMessage());
return;
}
if (featureCollection.isEmpty()) {
Dialogs.showError(Bundle.CTL_ImportSeadasTrackActionName(), "No records found.");
return;
}
String name = FileUtils.getFilenameWithoutExtension(file);
final PlacemarkDescriptor placemarkDescriptor =
PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(featureCollection.getSchema());
placemarkDescriptor.setUserDataOf(featureCollection.getSchema());
VectorDataNode vectorDataNode = new VectorDataNode(name, featureCollection, placemarkDescriptor);
product.getVectorDataGroup().add(vectorDataNode);
final ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView();
if (view != null) {
view.setLayersVisible(vectorDataNode);
}
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnableState();
}
private void setEnableState() {
boolean state = false;
ProductNode productNode = lookup.lookup(ProductNode.class);
if (productNode != null) {
Product product = productNode.getProduct();
state = product != null && product.getSceneGeoCoding() != null;
}
setEnabled(state);
}
private static FeatureCollection<SimpleFeatureType, SimpleFeature> readTrack(File file, GeoCoding geoCoding) throws IOException {
try (Reader reader = new FileReader(file)) {
return readTrack(reader, geoCoding);
}
}
static FeatureCollection<SimpleFeatureType, SimpleFeature> readTrack(Reader reader, GeoCoding geoCoding) throws IOException {
CsvReader csvReader = new CsvReader(reader, new char[]{'\t', ' '}, true, "#");
SimpleFeatureType trackFeatureType = createTrackFeatureType(geoCoding);
ListFeatureCollection featureCollection = new ListFeatureCollection(trackFeatureType);
double[] record;
int pointIndex = 0;
while ((record = csvReader.readDoubleRecord()) != null) {
if (record.length < 3) {
throw new IOException("Illegal track file format.\n" +
"Expecting tab-separated lines containing 3 values: lat, lon, data.");
}
float lat = (float) record[0];
float lon = (float) record[1];
double data = record[2];
final SimpleFeature feature = createFeature(trackFeatureType, geoCoding, pointIndex, lat, lon, data);
if (feature != null) {
featureCollection.add(feature);
}
pointIndex++;
}
if (featureCollection.isEmpty()) {
throw new IOException("No track point found or all of them are located outside the scene boundaries.");
}
final CoordinateReferenceSystem mapCRS = geoCoding.getMapCRS();
if (!mapCRS.equals(DefaultGeographicCRS.WGS84)) {
try {
transformFeatureCollection(featureCollection, mapCRS);
} catch (TransformException e) {
throw new IOException("Cannot transform the ship track onto CRS '" + mapCRS.toWKT() + "'.", e);
}
}
return featureCollection;
}
private static void transformFeatureCollection(FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection, CoordinateReferenceSystem targetCRS) throws TransformException {
final GeometryCoordinateSequenceTransformer transform = FeatureUtils.getTransform(DefaultGeographicCRS.WGS84, targetCRS);
final FeatureIterator<SimpleFeature> features = featureCollection.features();
final GeometryFactory geometryFactory = new GeometryFactory();
while (features.hasNext()) {
final SimpleFeature simpleFeature = features.next();
final Point sourcePoint = (Point) simpleFeature.getDefaultGeometry();
final Point targetPoint = transform.transformPoint(sourcePoint, geometryFactory);
simpleFeature.setDefaultGeometry(targetPoint);
}
}
private static SimpleFeatureType createTrackFeatureType(GeoCoding geoCoding) {
SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
ftb.setName("org.esa.snap.TrackPoint");
/*0*/
ftb.add("pixelPos", Point.class, geoCoding.getImageCRS());
/*1*/
ftb.add("geoPos", Point.class, DefaultGeographicCRS.WGS84);
/*2*/
ftb.add("data", Double.class);
ftb.setDefaultGeometry(geoCoding instanceof CrsGeoCoding ? "geoPos" : "pixelPos");
// GeoTools Bug: this doesn't work
// ftb.userData("trackPoints", "true");
final SimpleFeatureType ft = ftb.buildFeatureType();
ft.getUserData().put("trackPoints", "true");
return ft;
}
private static SimpleFeature createFeature(SimpleFeatureType type, GeoCoding geoCoding, int pointIndex, float lat, float lon, double data) {
PixelPos pixelPos = geoCoding.getPixelPos(new GeoPos(lat, lon), null);
if (!pixelPos.isValid()) {
return null;
}
SimpleFeatureBuilder fb = new SimpleFeatureBuilder(type);
GeometryFactory gf = new GeometryFactory();
/*0*/
fb.add(gf.createPoint(new Coordinate(pixelPos.x, pixelPos.y)));
/*1*/
fb.add(gf.createPoint(new Coordinate(lon, lat)));
/*2*/
fb.add(data);
return fb.buildFeature(String.format("ID%08d", pointIndex));
}
}
| 11,119 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FeatureCrsDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/FeatureCrsDialog.java | package org.esa.snap.rcp.actions.vector;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.crs.CrsSelectionPanel;
import org.esa.snap.ui.crs.CustomCrsForm;
import org.esa.snap.ui.crs.PredefinedCrsForm;
import org.esa.snap.ui.crs.ProductCrsForm;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Insets;
/**
* Dialog for selection of a feature CRS in CSV import
*
* @author olafd
*/
public class FeatureCrsDialog extends ModalDialog {
private CrsSelectionPanel crsSelectionPanel;
private Product product;
private String title;
public FeatureCrsDialog(Product product, String title) {
super(SnapApp.getDefault().getMainFrame(), title, ModalDialog.ID_OK_CANCEL_HELP, "importCSV");
this.product = product;
this.title = title;
createUI();
}
private void createUI() {
final ProductCrsForm productCrsForm = new ProductCrsForm(SnapApp.getDefault().getAppContext(), product);
final CustomCrsForm customCrsForm = new CustomCrsForm(SnapApp.getDefault().getAppContext());
final PredefinedCrsForm predefinedCrsForm = new PredefinedCrsForm(SnapApp.getDefault().getAppContext());
crsSelectionPanel = new CrsSelectionPanel(productCrsForm, customCrsForm, predefinedCrsForm);
final TableLayout tableLayout = new TableLayout(1);
tableLayout.setTableWeightX(1.0);
tableLayout.setTableFill(TableLayout.Fill.BOTH);
tableLayout.setTablePadding(4, 4);
tableLayout.setCellPadding(0, 0, new Insets(4, 10, 4, 4));
final JPanel contentPanel = new JPanel(tableLayout);
final JLabel label = new JLabel();
label.setText("<html><b>" +
"The vector data are not associated with a coordinate reference system (CRS).<br/>" +
"Please specify a CRS so that coordinates can be interpreted correctly.</b>");
contentPanel.add(label);
contentPanel.add(crsSelectionPanel);
setContent(contentPanel);
}
public CoordinateReferenceSystem getFeatureCrs() {
CoordinateReferenceSystem crs = null;
try {
crs = crsSelectionPanel.getCrs(ProductUtils.getCenterGeoPos(product));
} catch (FactoryException e) {
Dialogs.showError(title,
"Cannot create coordinate reference system.\n" + e.getMessage());
}
return crs;
}
@Override
protected void onOK() {
super.onOK();
getParent().setVisible(true); // todo: Visat main window disappears otherwise, find better solution
}
@Override
protected void onCancel() {
super.onCancel();
getParent().setVisible(true); // todo: Visat main window disappears otherwise, find better solution
}
}
| 3,133 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SeparateGeometriesDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/SeparateGeometriesDialog.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.actions.vector;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.ui.ModalDialog;
import org.opengis.feature.type.AttributeType;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Window;
import java.util.ArrayList;
import java.util.List;
/**
* @author Olaf Danne
* @author Thomas Storm
*/
class SeparateGeometriesDialog extends ModalDialog {
private final JComboBox comboBox;
public SeparateGeometriesDialog(Window mainFrame, VectorDataNode vectorDataNode, String helpId, String text) {
super(mainFrame, "Import Geometry", ModalDialog.ID_YES_NO_HELP, helpId);
JPanel content = new JPanel(new BorderLayout());
content.add(new JLabel(text), BorderLayout.NORTH);
List<AttributeType> types = vectorDataNode.getFeatureType().getTypes();
ArrayList<String> names = new ArrayList<String>();
for (AttributeType type : types) {
if (type.getBinding().equals(String.class)) {
names.add(type.getName().getLocalPart());
}
}
comboBox = new JComboBox(names.toArray(new String[names.size()]));
if (names.size() > 0) {
JPanel content2 = new JPanel(new BorderLayout());
content2.add(new JLabel("Attribute for mask/layer naming: "), BorderLayout.WEST);
content2.add(comboBox, BorderLayout.CENTER);
content.add(content2, BorderLayout.SOUTH);
}
setContent(content);
}
String getSelectedAttributeName() {
if (comboBox.getItemCount() > 0) {
return comboBox.getSelectedItem().toString();
} else {
return null;
}
}
}
| 2,496 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TypeDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/TypeDialog.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.actions.vector;
import org.esa.snap.core.datamodel.GeometryDescriptor;
import org.esa.snap.core.datamodel.PlacemarkDescriptor;
import org.esa.snap.core.datamodel.PlacemarkDescriptorRegistry;
import org.esa.snap.core.datamodel.PointDescriptor;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.ModalDialog;
import org.opengis.feature.simple.SimpleFeatureType;
import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* @author Olaf Danne
* @author Thomas Storm
* @author Norman Fomferra
*/
class TypeDialog extends ModalDialog {
private InterpretationMethod interpretationMethod;
private PlacemarkDescriptor placemarkDescriptor;
TypeDialog(Window parent, SimpleFeatureType featureType) {
super(parent, "Point Data Interpretation", ModalDialog.ID_OK_CANCEL_HELP, "interpretPointData");
createUI(featureType);
}
private void createUI(SimpleFeatureType featureType) {
getJDialog().setPreferredSize(new Dimension(400, 250));
JPanel panel = new JPanel();
BoxLayout layout = new BoxLayout(panel, BoxLayout.Y_AXIS);
panel.setLayout(layout);
panel.add(new JLabel("<html>" + SnapApp.getDefault().getAppContext().getApplicationName() + " can interpret the imported point data in various ways.<br>" +
"Please select:<br><br></html>"));
List<AbstractButton> buttons = new ArrayList<AbstractButton>();
placemarkDescriptor = PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(GeometryDescriptor.class);
interpretationMethod = InterpretationMethod.LEAVE_UNCHANGED;
buttons.add(createButton("<html>Leave imported data <b>unchanged</b></html>.", true, InterpretationMethod.LEAVE_UNCHANGED, placemarkDescriptor));
buttons.add(createButton("<html>Interpret each point as vertex of a single <b>line or polygon</b><br>" +
"(This will remove all attributes from points)</html>", false, InterpretationMethod.CONVERT_TO_SHAPE,
PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(PointDescriptor.class)));
SortedSet<PlacemarkDescriptor> placemarkDescriptors = new TreeSet<PlacemarkDescriptor>(new Comparator<PlacemarkDescriptor>() {
@Override
public int compare(PlacemarkDescriptor o1, PlacemarkDescriptor o2) {
return o1.getRoleLabel().compareTo(o2.getRoleLabel());
}
});
placemarkDescriptors.addAll(PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptors(featureType));
placemarkDescriptors.remove(PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(GeometryDescriptor.class));
placemarkDescriptors.remove(PlacemarkDescriptorRegistry.getInstance().getPlacemarkDescriptor(PointDescriptor.class));
for (PlacemarkDescriptor descriptor : placemarkDescriptors) {
buttons.add(createButton("<html>Interpret each point as <b>" + descriptor.getRoleLabel() + "</br></html>",
false,
InterpretationMethod.APPLY_DESCRIPTOR,
descriptor));
}
ButtonGroup buttonGroup = new ButtonGroup();
for (AbstractButton button : buttons) {
buttonGroup.add(button);
panel.add(button);
}
setContent(panel);
}
private JRadioButton createButton(String text, boolean selected, final InterpretationMethod im, final PlacemarkDescriptor pd) {
JRadioButton button = new JRadioButton(text, selected);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
interpretationMethod = im;
placemarkDescriptor = pd;
}
});
return button;
}
public InterpretationMethod getInterpretationMethod() {
return interpretationMethod;
}
public PlacemarkDescriptor getPlacemarkDescriptor() {
return placemarkDescriptor;
}
public enum InterpretationMethod {
LEAVE_UNCHANGED,
CONVERT_TO_SHAPE,
APPLY_DESCRIPTOR
}
@Override
protected void onOK() {
super.onOK();
getParent().setVisible(true); // todo: Visat main window disappears otherwise, find better solution
}
@Override
protected void onCancel() {
super.onCancel();
getParent().setVisible(true);
}
@Override
protected void onHelp() {
// todo
super.onHelp();
}
}
| 5,776 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImportVectorDataNodeFromCsvAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/ImportVectorDataNodeFromCsvAction.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.actions.vector;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.core.dataio.geometry.VectorDataNodeIO;
import org.esa.snap.core.dataio.geometry.VectorDataNodeReader;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.rcp.SnapApp;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.Action;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
@ActionID(category = "File", id = "ImportVectorDataNodeFromCsvAction" )
@ActionRegistration(displayName = "#CTL_ImportVectorDataNodeFromCsvActionText", lazy = false )
@ActionReferences({
@ActionReference(path = "Menu/File/Import/Vector Data", position = 10),
@ActionReference(path = "Menu/Vector/Import")
})
@NbBundle.Messages({
"CTL_ImportVectorDataNodeFromCsvActionText=Vector from CSV",
"CTL_ImportVectorDataNodeFromCsvActionDescription=Import Vector Data Node From CSV",
"CTL_ImportVectorDataNodeFromCsvActionHelp=importCSV"
})
public class ImportVectorDataNodeFromCsvAction extends AbstractImportVectorDataNodeAction
implements ContextAwareAction, LookupListener {
private Lookup lookup;
private final Lookup.Result<ProductNode> result;
private VectorDataNodeImporter importer;
private static final String vector_data_type = "CSV";
public ImportVectorDataNodeFromCsvAction() {
this(Utilities.actionsGlobalContext());
}
public ImportVectorDataNodeFromCsvAction(Lookup lookup) {
this.lookup = lookup;
result = lookup.lookupResult(ProductNode.class);
result.addLookupListener(
WeakListeners.create(LookupListener.class, this, result));
setEnableState();
setHelpId(Bundle.CTL_ImportVectorDataNodeFromCsvActionHelp());
putValue(Action.NAME, Bundle.CTL_ImportVectorDataNodeFromCsvActionText());
putValue(Action.SHORT_DESCRIPTION, Bundle.CTL_ImportVectorDataNodeFromCsvActionDescription());
}
@Override
public Action createContextAwareInstance(Lookup lookup) {
return new ImportVectorDataNodeFromCsvAction(lookup);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
setEnableState();
}
private void setEnableState() {
boolean state = false;
ProductNode productNode = lookup.lookup(ProductNode.class);
if (productNode != null) {
Product product = productNode.getProduct();
state = product != null && product.getSceneGeoCoding() != null;
}
setEnabled(state);
}
@Override
public void actionPerformed(ActionEvent e) {
final SnapFileFilter filter = new SnapFileFilter(getVectorDataType(),
new String[]{".txt", ".dat", ".csv"},
"Plain text");
importer = new VectorDataNodeImporter(getHelpId(), filter, new DefaultVectorDataNodeReader(), "Import CSV file", "csv.io.dir");
importer.importGeometry(SnapApp.getDefault());
}
@Override
protected String getDialogTitle() {
return importer.getDialogTitle();
}
@Override
protected String getVectorDataType() {
return vector_data_type;
}
private class DefaultVectorDataNodeReader implements VectorDataNodeImporter.VectorDataNodeReader {
@Override
public VectorDataNode readVectorDataNode(File file, Product product, ProgressMonitor pm) throws IOException {
FileReader reader = null;
try {
CoordinateReferenceSystem modelCrs = product.getSceneCRS();
reader = new FileReader(file);
return VectorDataNodeReader.read(file.getName(), reader, product, crsProvider, placemarkDescriptorProvider,
modelCrs, VectorDataNodeIO.DEFAULT_DELIMITER_CHAR, pm);
} finally {
if (reader != null) {
reader.close();
}
}
}
}
}
| 5,425 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ShowGeometryWktAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/vector/ShowGeometryWktAction.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.actions.vector;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.FigureSelection;
import com.bc.ceres.swing.figure.support.DefaultFigureSelection;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKTWriter;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.product.SimpleFeatureFigure;
import org.geotools.geometry.jts.GeometryCoordinateSequenceTransformer;
import org.geotools.referencing.CRS;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.TransformException;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionReferences;
import org.openide.awt.ActionRegistration;
import org.openide.util.ContextAwareAction;
import org.openide.util.Lookup;
import org.openide.util.LookupEvent;
import org.openide.util.LookupListener;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.util.WeakListeners;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
/**
* An action that allows users to copy WKT from selected Geometries.
*
* @author Norman
* @since BEAM 5
*/
@ActionID(category = "File", id = "org.esa.snap.rcp.actions.vector.ShowGeometryWktAction")
@ActionRegistration(displayName = "#CTL_ShowGeometryWktAction_MenuText", lazy = false)
@ActionReferences({
@ActionReference(path = "Menu/Vector", position = 19, separatorAfter = 20),
@ActionReference(path = "Context/ProductSceneView", position = 10)
})
@NbBundle.Messages({
"CTL_ShowGeometryWktAction_MenuText=WKT from Geometry",
"CTL_ShowGeometryWktAction_ShortDescription=Get the well-known-text (WKT) representation of a selected geometry."
})
public class ShowGeometryWktAction extends AbstractAction implements LookupListener, ContextAwareAction {
private static final String DLG_TITLE = "WKT from Geometry";
private Lookup.Result<FigureSelection> result;
private Lookup lookup;
public ShowGeometryWktAction() {
this(Utilities.actionsGlobalContext());
}
public ShowGeometryWktAction(Lookup lookup) {
super(Bundle.CTL_ShowGeometryWktAction_MenuText());
this.lookup = lookup;
result = lookup.lookupResult(FigureSelection.class);
result.addLookupListener(WeakListeners.create(LookupListener.class, this, result));
setEnabled(false);
}
@Override
public void actionPerformed(ActionEvent event) {
exportToWkt();
}
@Override
public Action createContextAwareInstance(Lookup actionContext) {
return new ShowGeometryWktAction(actionContext);
}
@Override
public void resultChanged(LookupEvent lookupEvent) {
FigureSelection selection = this.lookup.lookup(FigureSelection.class);
setEnabled(selection != null);
}
private void exportToWkt() {
SimpleFeatureFigure selectedFeatureFigure = getSimpleFeatureFigure();
if (selectedFeatureFigure == null) {
Dialogs.showInformation(DLG_TITLE, "Please select a geometry.", null);
return;
}
SimpleFeature simpleFeature = selectedFeatureFigure.getSimpleFeature();
CoordinateReferenceSystem sourceCrs = simpleFeature.getDefaultGeometryProperty().getDescriptor().getCoordinateReferenceSystem();
CoordinateReferenceSystem targetCrs = DefaultGeographicCRS.WGS84;
Geometry sourceGeom = selectedFeatureFigure.getGeometry();
Geometry targetGeom;
try {
targetGeom = transformGeometry(sourceGeom, sourceCrs, targetCrs);
} catch (Exception e) {
Dialogs.showWarning(DLG_TITLE, "Failed to transform geometry to " + targetCrs.getName() + ".\n" +
"Using " + sourceCrs.getName() + " instead.", null);
targetGeom = sourceGeom;
targetCrs = sourceCrs;
}
WKTWriter wktWriter = new WKTWriter();
wktWriter.setFormatted(true);
wktWriter.setMaxCoordinatesPerLine(2);
wktWriter.setTab(3);
String wkt = wktWriter.writeFormatted(targetGeom);
JTextArea textArea = new JTextArea(16, 32);
textArea.setEditable(false);
textArea.setText(wkt);
textArea.selectAll();
JPanel contentPanel = new JPanel(new BorderLayout(4, 4));
contentPanel.add(new JLabel("Geometry Well-Known-Text (WKT):"), BorderLayout.NORTH);
contentPanel.add(new JScrollPane(textArea), BorderLayout.CENTER);
contentPanel.add(new JLabel("Geometry CRS: " + targetCrs.getName().toString()), BorderLayout.SOUTH);
ModalDialog modalDialog = new ModalDialog(SnapApp.getDefault().getMainFrame(), DLG_TITLE, ModalDialog.ID_OK, null);
modalDialog.setContent(contentPanel);
modalDialog.center();
modalDialog.show();
}
private SimpleFeatureFigure getSimpleFeatureFigure() {
DefaultFigureSelection selection = this.lookup.lookup(DefaultFigureSelection.class);
SimpleFeatureFigure selectedFeatureFigure = null;
Figure[] figures = selection.getFigures();
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
selectedFeatureFigure = (SimpleFeatureFigure) figure;
}
}
return selectedFeatureFigure;
}
private Geometry transformGeometry(Geometry sourceGeom,
CoordinateReferenceSystem sourceCrs,
CoordinateReferenceSystem targetCrs) throws FactoryException, TransformException {
MathTransform mt = CRS.findMathTransform(sourceCrs, targetCrs, true);
GeometryCoordinateSequenceTransformer gcst = new GeometryCoordinateSequenceTransformer();
gcst.setMathTransform(mt);
return gcst.transform(sourceGeom);
}
}
| 7,105 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNNodeBase.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNNodeBase.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.openide.awt.UndoRedo;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.util.Lookup;
/**
* A node that represents some {@link ProductNode} (=PN).
*
* @author Norman
*/
abstract class PNNodeBase extends AbstractNode implements ProductNodeListener, UndoRedo.Provider {
protected PNNodeBase() {
this(null, null);
}
protected PNNodeBase(PNGroupBase childFactory) {
this(childFactory, null);
}
protected PNNodeBase(PNGroupBase childFactory, Lookup lookup) {
super(childFactory != null ? Children.create(childFactory, false) : Children.LEAF, lookup);
}
@Override
public UndoRedo getUndoRedo() {
return PNNodeSupport.getUndoRedo(getParentNode());
}
public boolean isDirectChild(ProductNode productNode) {
return PNNodeSupport.isDirectChild(this.getChildren(), productNode);
}
}
| 1,241 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNode.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNode.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.MetadataElement;
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.ProductNodeGroup;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.file.CloseProductAction;
import org.openide.awt.UndoRedo;
import org.openide.nodes.Node;
import org.openide.nodes.PropertySupport;
import org.openide.nodes.Sheet;
import org.openide.util.WeakListeners;
import javax.swing.Action;
import java.io.File;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.prefs.PreferenceChangeEvent;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
import java.util.stream.Stream;
import static org.esa.snap.rcp.nodes.PNNodeSupport.performUndoableProductNodeEdit;
/**
* A node that represents a {@link Product} (=P).
* Every {@code PNode} holds a dedicated undo/redo context.
*
* @author Norman
*/
public class PNode extends PNNode<Product> implements PreferenceChangeListener {
private final PContent group;
public PNode(Product product) {
this(product, new PContent());
}
private PNode(Product product, PContent group) {
super(product, group);
this.group = group;
group.node = this;
setDisplayName(product.getDisplayName());
setShortDescription(product.getDescription());
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsProduct16.gif");
Preferences preferences = SnapApp.getDefault().getPreferences();
preferences.addPreferenceChangeListener(WeakListeners.create(PreferenceChangeListener.class, this, preferences));
}
public Product getProduct() {
return getProductNode();
}
@Override
public UndoRedo getUndoRedo() {
return SnapApp.getDefault().getUndoManager(getProduct());
}
@Override
public boolean canDestroy() {
return false;
}
@Override
public void destroy() {
new CloseProductAction(Collections.singletonList(getProduct())).execute();
}
@Override
public Action[] getActions(boolean context) {
return PNNodeSupport.getContextActions(getProductNode());
}
@Override
public Action getPreferredAction() {
//Define the action that will be invoked
//when the user double-clicks on the node:
return super.getPreferredAction();
}
@Override
public void preferenceChange(PreferenceChangeEvent evt) {
String key = evt.getKey();
if (GroupByNodeTypeAction.PREFERENCE_KEY.equals(key)) {
group.refresh();
}
}
@Override
public PropertySet[] getPropertySets() {
Sheet.Set set = new Sheet.Set();
set.setDisplayName("Product Properties");
set.put(new PropertySupport.ReadOnly<File>("fileLocation", File.class, "File", "File location") {
@Override
public File getValue() {
return getProduct().getFileLocation();
}
});
set.put(new PropertySupport.ReadWrite<String>("productType", String.class, "Product Type", "The product type identifier") {
@Override
public String getValue() {
return getProduct().getProductType();
}
@Override
public void setValue(String newValue) throws IllegalArgumentException {
String oldValue = getProduct().getProductType();
performUndoableProductNodeEdit("Edit Product Type",
getProduct(),
node -> node.setProductType(newValue),
node -> node.setProductType(oldValue));
}
});
set.put(new PropertySupport.ReadWrite<String>("startTime", String.class, "Sensing Start Time", "The product's sensing start time") {
@Override
public String getValue() {
ProductData.UTC startTime = getProduct().getStartTime();
return startTime != null ? startTime.format() : "";
}
@Override
public void setValue(String s) throws IllegalArgumentException {
ProductData.UTC oldValue = getProduct().getStartTime();
try {
ProductData.UTC newValue = ProductData.UTC.parse(s);
performUndoableProductNodeEdit("Edit Sensing Start Time",
getProduct(),
node -> node.setStartTime(newValue),
node -> node.setStartTime(oldValue));
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
});
set.put(new PropertySupport.ReadWrite<String>("endTime", String.class, "Sensing Stop Time", "The product's sensing stop time") {
@Override
public String getValue() {
ProductData.UTC endTime = getProduct().getEndTime();
return endTime != null ? endTime.format() : "";
}
@Override
public void setValue(String s) throws IllegalArgumentException {
Product product = getProduct();
ProductData.UTC oldValue = product.getEndTime();
try {
ProductData.UTC newValue = ProductData.UTC.parse(s);
performUndoableProductNodeEdit("Edit Sensing Stop Time",
product,
node -> node.setEndTime(newValue),
node -> node.setEndTime(oldValue));
} catch (ParseException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
});
set.put(new PropertySupport.ReadWrite<String>("bandGrouping", String.class, "Band Grouping", "The product's band grouping") {
@Override
public String getValue() {
final Product.AutoGrouping autoGrouping = getProduct().getAutoGrouping();
if (autoGrouping == null) {
return "";
} else {
return autoGrouping.toString();
}
}
@Override
public void setValue(String s) throws IllegalArgumentException {
Product.AutoGrouping oldValue = getProduct().getAutoGrouping();
Product.AutoGrouping newValue = Product.AutoGrouping.parse(s);
performUndoableProductNodeEdit("Edit Band-Grouping",
getProduct(),
node -> node.setAutoGrouping(newValue),
node -> node.setAutoGrouping(oldValue));
}
});
includeAbstractedMetadata(set);
return Stream.concat(Stream.of(super.getPropertySets()), Stream.of(set)).toArray(PropertySet[]::new);
}
private void includeAbstractedMetadata(final Sheet.Set set) {
final MetadataElement root = getProduct().getMetadataRoot();
if (root != null) {
final MetadataElement absRoot = root.getElement("Abstracted_Metadata");
if (absRoot != null) {
set.put(new PropertySupport.ReadOnly<String>("mission", String.class, "Mission", "Earth Observation Mission") {
@Override
public String getValue() {
return absRoot.getAttributeString("mission");
}
});
set.put(new PropertySupport.ReadOnly<String>("mode", String.class, "Acquisition Mode", "Sensor Acquisition Mode") {
@Override
public String getValue() {
return absRoot.getAttributeString("ACQUISITION_MODE");
}
});
set.put(new PropertySupport.ReadOnly<String>("pass", String.class, "Pass", "Orbital Pass") {
@Override
public String getValue() {
return absRoot.getAttributeString("pass");
}
});
set.put(new PropertySupport.ReadOnly<String>("track", String.class, "Track", "Relative Orbit") {
@Override
public String getValue() {
return absRoot.getAttributeString("REL_ORBIT");
}
});
set.put(new PropertySupport.ReadOnly<String>("orbit", String.class, "Orbit", "Absolute Orbit") {
@Override
public String getValue() {
return absRoot.getAttributeString("ABS_ORBIT");
}
});
}
}
}
private boolean isGroupByNodeType() {
return SnapApp.getDefault().getPreferences().getBoolean(GroupByNodeTypeAction.PREFERENCE_KEY,
GroupByNodeTypeAction.PREFERENCE_DEFAULT_VALUE);
}
/**
* A child factory for nodes below a {@link PNode} that holds a {@link Product}.
*
* @author Norman
*/
static class PContent extends PNGroupBase<Object> {
PNode node;
@Override
protected boolean createKeys(List<Object> list) {
Product product = node.getProduct();
ProductNodeGroup<MetadataElement> metadataElementGroup = product.getMetadataRoot().getElementGroup();
if (node.isGroupByNodeType()) {
if (metadataElementGroup != null) {
list.add(new PNGGroup.ME(metadataElementGroup));
}
if (product.getIndexCodingGroup().getNodeCount() > 0) {
list.add(new PNGGroup.IC(product.getIndexCodingGroup()));
}
if (product.getFlagCodingGroup().getNodeCount() > 0) {
list.add(new PNGGroup.FC(product.getFlagCodingGroup()));
}
if (product.getVectorDataGroup().getNodeCount() > 0) {
list.add(new PNGGroup.VDN(product.getVectorDataGroup()));
}
if (product.getTiePointGridGroup().getNodeCount() > 0) {
list.add(new PNGroupingGroup.TPG(product.getTiePointGridGroup()));
}
if (product.getQuicklookGroup().getNodeCount() > 0) {
list.add(new PNGGroup.QL(product.getQuicklookGroup()));
}
if (product.getBandGroup().getNodeCount() > 0) {
list.add(new PNGroupingGroup.B(product.getBandGroup()));
}
if (product.getMaskGroup().getNodeCount() > 0) {
list.add(new PNGroupingGroup.M(product.getMaskGroup()));
}
} else {
if (metadataElementGroup != null) {
list.addAll(Arrays.asList(metadataElementGroup.toArray()));
}
list.addAll(Arrays.asList(product.getIndexCodingGroup().toArray()));
list.addAll(Arrays.asList(product.getFlagCodingGroup().toArray()));
list.addAll(Arrays.asList(product.getVectorDataGroup().toArray()));
list.addAll(Arrays.asList(product.getTiePointGridGroup().toArray()));
list.addAll(Arrays.asList(product.getQuicklookGroup().toArray()));
list.addAll(Arrays.asList(product.getBandGroup().toArray()));
list.addAll(Arrays.asList(product.getMaskGroup().toArray()));
}
return true;
}
@Override
protected Node createNodeForKey(Object key) {
if (key instanceof ProductNode) {
return PNNode.create((ProductNode) key);
} else {
return new PNGroupNode((PNGroup) key);
}
}
}
}
| 12,575 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UndoableProductNodeInsertion.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/UndoableProductNodeInsertion.java | package org.esa.snap.rcp.nodes;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.openide.util.NbBundle;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
/**
* An undoable deletion of a {@code ProductNode}.
*
* @param <T> The product node type.
* @author Norman Fomferra
*/
@NbBundle.Messages("LBL_UndoableProductNodeInsertionName=Add ''{0}''")
public class UndoableProductNodeInsertion<T extends ProductNode> extends AbstractUndoableEdit {
private ProductNodeGroup<T> group;
private T productNode;
private final int index;
public UndoableProductNodeInsertion(ProductNodeGroup<T> productNodeGroup, T productNode) {
Assert.notNull(productNodeGroup, "group");
Assert.notNull(productNode, "node");
this.group = productNodeGroup;
this.productNode = productNode;
this.index = productNodeGroup.indexOf(productNode);
}
public T getProductNode() {
return productNode;
}
@Override
public String getPresentationName() {
return Bundle.LBL_UndoableProductNodeInsertionName(productNode.getName());
}
@Override
public void undo() throws CannotUndoException {
super.undo();
// todo - close all open document windows
group.remove(productNode);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
if (index < group.getNodeCount()) {
group.add(productNode);
} else {
group.add(index, productNode);
}
}
@Override
public void die() {
group = null;
productNode = null;
}
}
| 1,799 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNNode.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNNode.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import eu.esa.snap.netbeans.docwin.DocumentWindow;
import eu.esa.snap.netbeans.docwin.DocumentWindowManager;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.datamodel.quicklooks.Quicklook;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.window.OpenImageViewAction;
import org.esa.snap.rcp.actions.window.OpenMetadataViewAction;
import org.esa.snap.rcp.actions.window.OpenPlacemarkViewAction;
import org.esa.snap.rcp.actions.window.OpenQuicklookViewAction;
import org.esa.snap.rcp.util.Dialogs;
import org.esa.snap.rcp.util.ProgressHandleMonitor;
import org.netbeans.api.progress.BaseProgressUtils;
import org.opengis.feature.type.GeometryDescriptor;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.openide.awt.UndoRedo;
import org.openide.nodes.Node;
import org.openide.nodes.PropertySupport;
import org.openide.nodes.Sheet;
import org.openide.util.lookup.Lookups;
import javax.swing.*;
import java.awt.datatransfer.Transferable;
import java.beans.PropertyEditor;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.WeakHashMap;
import java.util.stream.Stream;
import static org.esa.snap.rcp.nodes.PNNodeSupport.performUndoableProductNodeEdit;
/**
* A node that represents some {@link ProductNode} (=PN).
*
* @author Norman
*/
abstract class PNNode<T extends ProductNode> extends PNNodeBase {
private final T productNode;
private final PNNodeSupport nodeSupport;
public PNNode(T productNode) {
this(productNode, null);
}
public PNNode(T productNode, PNGroupBase childFactory) {
super(childFactory, Lookups.singleton(productNode));
this.productNode = productNode;
setDisplayName(productNode.getName());
setShortDescription(productNode.getDescription());
nodeSupport = PNNodeSupport.create(this, childFactory);
}
public T getProductNode() {
return productNode;
}
void updateDisplayName(T productNode) {
setDisplayName(productNode.getName());
}
@Override
public void nodeChanged(ProductNodeEvent event) {
if (event.getSourceNode() == getProductNode()) {
if (ProductNode.PROPERTY_NAME_NAME.equals(event.getPropertyName())) {
setDisplayName(getProductNode().getName());
}
if (ProductNode.PROPERTY_NAME_DESCRIPTION.equals(event.getPropertyName())) {
setShortDescription(getProductNode().getDescription());
}
}
nodeSupport.nodeChanged(event);
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
nodeSupport.nodeDataChanged(event);
}
@Override
public void nodeAdded(ProductNodeEvent event) {
nodeSupport.nodeAdded(event);
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
nodeSupport.nodeRemoved(event);
}
@Override
public PropertySet[] getPropertySets() {
Sheet.Set set = new Sheet.Set();
set.setDisplayName("Product Node Properties");
set.put(new PropertySupport.ReadWrite<String>("name", String.class, "Name", "Name of the element") {
@Override
public String getValue() {
return getProductNode().getName();
}
@Override
public void setValue(String newValue) {
String oldValue = productNode.getName();
performUndoableProductNodeEdit("Rename",
productNode,
node -> node.setName(newValue),
node -> node.setName(oldValue)
);
}
});
set.put(new PropertySupport.ReadWrite<String>("description", String.class, "Description", "Human-readable description of the element") {
@Override
public String getValue() {
return getProductNode().getDescription();
}
@Override
public void setValue(String newValue) {
String oldValue = productNode.getDescription();
performUndoableProductNodeEdit("Edit Description",
productNode,
node -> node.setDescription(newValue),
node -> node.setDescription(oldValue)
);
}
});
set.put(new PropertySupport.ReadOnly<Boolean>("modified", Boolean.class, "Modified", "Has the element been modified?") {
@Override
public Boolean getValue() {
return getProductNode().isModified();
}
});
return new PropertySet[]{
set
};
}
@Override
public Action[] getActions(boolean context) {
ProductNode productNode1 = getProductNode();
return PNNodeSupport.getContextActions(productNode1);
}
public static Node create(ProductNode productNode) {
if (productNode instanceof FlagCoding) {
return new PNNode.FC((FlagCoding) productNode);
} else if (productNode instanceof IndexCoding) {
return new PNNode.IC((IndexCoding) productNode);
} else if (productNode instanceof MetadataElement) {
return new PNNode.ME((MetadataElement) productNode);
} else if (productNode instanceof VectorDataNode) {
return new PNNode.VDN((VectorDataNode) productNode);
} else if (productNode instanceof TiePointGrid) {
return new PNNode.TPG((TiePointGrid) productNode);
} else if (productNode instanceof Mask) {
return new PNNode.M((Mask) productNode);
} else if (productNode instanceof Band) {
return new PNNode.B((Band) productNode);
} else if (productNode instanceof Quicklook) {
return new PNNode.QL((Quicklook) productNode);
}
throw new IllegalStateException("unhandled product node type: " + productNode.getClass() + " named '" + productNode.getName() + "'");
}
private static <T extends ProductNode> void closeDocumentWindow(T productNode) {
WindowUtilities.getOpened(DocumentWindow.class)
.filter(dw -> (dw.getDocument() instanceof ProductNode) && (dw.getDocument() == productNode))
.forEach(dw -> DocumentWindowManager.getDefault().closeWindow(dw));
}
private static <T extends ProductNode> void deleteProductNode(Product product,
ProductNodeGroup<T> group,
T productNode) {
closeDocumentWindow(productNode);
final int index = group.indexOf(productNode);
group.remove(productNode);
UndoRedo.Manager manager = SnapApp.getDefault().getUndoManager(product);
if (manager != null) {
manager.addEdit(new UndoableProductNodeDeletion<>(group, productNode, index));
}
}
private static StringBuilder append(StringBuilder stringBuilder, String text) {
if (StringUtils.isNotNullAndNotEmpty(text)) {
if (stringBuilder.length() > 0) {
stringBuilder.append(", ");
}
stringBuilder.append(text);
}
return stringBuilder;
}
private static void setAncillaryVariables(Band band,
WeakHashMap<RasterDataNode, Integer> newNodes,
WeakHashMap<RasterDataNode, Integer> oldNodes) {
ArrayList<RasterDataNode> nodes = new ArrayList<>(newNodes.keySet());
nodes.sort(Comparator.comparingInt(newNodes::get));
for (RasterDataNode node : nodes) {
band.addAncillaryVariable(node);
}
oldNodes.keySet().stream().filter(oldVar -> !newNodes.containsKey(oldVar)).forEach(band::removeAncillaryVariable);
}
private static WeakHashMap<RasterDataNode, Integer> toWeakMap(RasterDataNode[] oldValue) {
WeakHashMap<RasterDataNode, Integer> oldNodes = new WeakHashMap<>();
for (int i = 0; i < oldValue.length; i++) {
RasterDataNode rasterDataNode = oldValue[i];
oldNodes.put(rasterDataNode, i);
}
return oldNodes;
}
private static void updateImages(RasterDataNode rasterDataNode, boolean validMaskPropertyChanged) {
if (rasterDataNode instanceof VirtualBand) {
VirtualBand virtualBand = (VirtualBand) rasterDataNode;
if (virtualBand.hasRasterData()) {
String title = "Recomputing Raster Data";
ProgressHandleMonitor pm = ProgressHandleMonitor.create(title);
Runnable operation = () -> {
try {
virtualBand.readRasterDataFully(pm);
} catch (IOException e) {
Dialogs.showError(e.getMessage());
}
};
BaseProgressUtils.runOffEventThreadWithProgressDialog(operation, title,
pm.getProgressHandle(),
true,
50, // time in ms after which wait cursor is shown
1000); // time in ms after which dialog with "Cancel" button is shown
}
}
OpenImageViewAction.updateProductSceneViewImages(new RasterDataNode[]{rasterDataNode}, view -> {
if (validMaskPropertyChanged) {
view.updateNoDataImage();
}
view.updateImage();
});
}
/**
* A node that represents a {@link MetadataElement} (=ME).
*
* @author Norman
*/
static class ME extends PNNode<MetadataElement> {
public ME(MetadataElement element) {
super(element, element.getElementGroup() != null ? new PNGGroup.ME(element.getElementGroup()) : null);
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsMetaData16.gif");
}
@Override
public boolean canDestroy() {
return getProductNode().getParentElement() != null;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getParentElement().getElementGroup(),
getProductNode());
}
@Override
public Action getPreferredAction() {
return new OpenMetadataViewAction();
}
}
/**
* A node that represents an {@link IndexCoding} (=IC).
*
* @author Norman
*/
static class IC extends PNNode<IndexCoding> {
public IC(IndexCoding indexCoding) {
super(indexCoding);
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsBandIndexes16.gif");
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getProduct().getIndexCodingGroup(),
getProductNode());
}
@Override
public Action getPreferredAction() {
return new OpenMetadataViewAction();
}
}
/**
* A node that represents a {@link FlagCoding} (=FC).
*
* @author Norman
*/
static class FC extends PNNode<FlagCoding> {
public FC(FlagCoding flagCoding) {
super(flagCoding);
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsBandFlags16.gif");
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getProduct().getFlagCodingGroup(),
getProductNode());
}
@Override
public Action getPreferredAction() {
return new OpenMetadataViewAction();
}
}
/**
* A node that represents a {@link VectorDataNode} (=VDN).
*
* @author Norman
*/
static class VDN extends PNNode<VectorDataNode> {
public VDN(VectorDataNode vectorDataNode) {
super(vectorDataNode);
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsVectorData16.gif");
setShortDescription(createToolTip(vectorDataNode));
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getProduct().getVectorDataGroup(),
getProductNode());
}
@Override
public Action getPreferredAction() {
return new OpenPlacemarkViewAction();
}
@Override
public PropertySet[] getPropertySets() {
Sheet.Set set = new Sheet.Set();
final VectorDataNode vdn = getProductNode();
set.setDisplayName("Vector Data Properties");
set.put(new PropertySupport.ReadOnly<String>("featureType", String.class, "Feature type",
"The feature type schema used for all features in the collection") {
@Override
public String getValue() {
return vdn.getFeatureType().getTypeName();
}
});
set.put(new PropertySupport.ReadOnly<String>("featureGeomType", String.class, "Feature geometry type",
"The geometry type used used for all feature geometries in the collection") {
@Override
public String getValue() {
Class<?> binding;
GeometryDescriptor geometryDescriptor = vdn.getFeatureType().getGeometryDescriptor();
if (geometryDescriptor != null) {
binding = geometryDescriptor.getType().getBinding();
} else {
binding = null;
}
return binding != null ? binding.getName() : "<unknown>";
}
});
set.put(new PropertySupport.ReadOnly<String>("featureCRS", String.class, "Feature geometry CRS",
"The coordinate reference system used used for all feature geometries in the collection") {
@Override
public String getValue() {
CoordinateReferenceSystem crs;
GeometryDescriptor geometryDescriptor = vdn.getFeatureType().getGeometryDescriptor();
if (geometryDescriptor != null) {
crs = geometryDescriptor.getType().getCoordinateReferenceSystem();
} else {
crs = null;
}
return crs != null ? crs.toString() : "<unknown>";
}
});
set.put(new PropertySupport.ReadOnly<Integer>("featureCount", Integer.class, "Feature count",
"The number of features in this collection") {
@Override
public Integer getValue() {
return vdn.getFeatureCollection().size();
}
});
return Stream.concat(Stream.of(super.getPropertySets()), Stream.of(set)).toArray(PropertySet[]::new);
}
private String createToolTip(final VectorDataNode vectorDataNode) {
final StringBuilder tooltip = new StringBuilder();
append(tooltip, vectorDataNode.getDescription());
append(tooltip, String.format("type %s, %d feature(s)", vectorDataNode.getFeatureType().getTypeName(),
vectorDataNode.getFeatureCollection().size()));
return tooltip.toString();
}
}
/**
* A node that represents a {@link TiePointGrid} (=TPG).
*
* @author Norman
*/
static class TPG extends PNNode<TiePointGrid> {
public TPG(TiePointGrid tiePointGrid) {
super(tiePointGrid);
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsBandAsTiePoint16.gif");
setShortDescription(createToolTip(tiePointGrid));
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getProduct().getTiePointGridGroup(),
getProductNode());
}
@Override
public Action getPreferredAction() {
return OpenImageViewAction.create(this.getProductNode());
}
@Override
public PropertySet[] getPropertySets() {
Sheet.Set set = new Sheet.Set();
final TiePointGrid tpg = getProductNode();
set.setDisplayName("Tie-Point Grid Properties");
set.put(new UnitProperty(tpg));
set.put(new RasterSizeProperty(tpg));
set.put(new ValidPixelExpressionProperty(tpg));
set.put(new NoDataValueUsedProperty(tpg));
set.put(new NoDataValueProperty(tpg));
return Stream.concat(Stream.of(super.getPropertySets()), Stream.of(set)).toArray(PropertySet[]::new);
}
private String createToolTip(final TiePointGrid tiePointGrid) {
StringBuilder tooltip = new StringBuilder();
append(tooltip, tiePointGrid.getDescription());
append(tooltip, String.format("%d x %d --> %d x %d pixels",
tiePointGrid.getGridWidth(), tiePointGrid.getGridHeight(),
tiePointGrid.getRasterWidth(), tiePointGrid.getRasterHeight()));
if (tiePointGrid.getUnit() != null) {
append(tooltip, String.format(" (%s)", tiePointGrid.getUnit()));
}
return tooltip.toString();
}
}
/**
* A node that represents a {@link Mask} (=M).
*
* @author Norman
*/
static class M extends PNNode<Mask> {
public M(Mask mask) {
super(mask);
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsMask16.gif");
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getProduct().getMaskGroup(),
getProductNode());
}
@Override
public Action getPreferredAction() {
return OpenImageViewAction.create(this.getProductNode());
}
}
/**
* A node that represents a {@link Band} (=B).
*
* @author Norman
*/
static class B extends PNNode<Band> {
public B(Band band) {
super(band);
if (band instanceof VirtualBand) {
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsBandVirtual16.gif");
} else if (band.isIndexBand()) {
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsBandIndexes16.gif");
} else if (band.isFlagBand()) {
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsBandFlags16.gif");
} else {
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsBandAsSwath.gif");
}
updateDisplayName(band);
setShortDescription(createToolTip(band));
}
void updateDisplayName(Band band) {
super.updateDisplayName(band);
if (band.getSpectralWavelength() > 0.0) {
setDisplayName(String.format("%s (%.1f nm)", band.getName(), band.getSpectralWavelength()));
}
}
@Override
public void nodeChanged(ProductNodeEvent event) {
if (event.getSourceNode() == getProductNode()) {
if (mustUpdateDisplayName(event)) {
updateDisplayName(getProductNode());
}
if (ProductNode.PROPERTY_NAME_DESCRIPTION.equals(event.getPropertyName())) {
setShortDescription(getProductNode().getDescription());
}
}
}
private boolean mustUpdateDisplayName(ProductNodeEvent event) {
return ProductNode.PROPERTY_NAME_NAME.equals(event.getPropertyName()) ||
Band.PROPERTY_NAME_SPECTRAL_WAVELENGTH.equals(event.getPropertyName());
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getProduct().getBandGroup(),
getProductNode());
}
@Override
public Transferable clipboardCopy() throws IOException {
return super.clipboardCopy();
}
@Override
public boolean canCopy() {
return true;
}
@Override
public Transferable clipboardCut() throws IOException {
return super.clipboardCut();
}
@Override
public boolean canCut() {
return true;
}
@Override
public Action getPreferredAction() {
return OpenImageViewAction.create(this.getProductNode());
}
@Override
public PropertySet[] getPropertySets() {
Sheet.Set set = new Sheet.Set();
final Band band = getProductNode();
set.setDisplayName("Raster Band Properties");
set.put(new UnitProperty(band));
set.put(new DataTypeProperty(band));
set.put(new RasterSizeProperty(band));
if (band instanceof VirtualBand) {
final VirtualBand virtualBand = (VirtualBand) band;
set.put(new PropertySupport.ReadWrite<String>("expression", String.class, "Pixel-Value Expression",
"Mathematical expression used to compute the raster's pixel values") {
@Override
public String getValue() {
return virtualBand.getExpression();
}
@Override
public void setValue(String newValue) {
String oldValue = virtualBand.getExpression();
performUndoableProductNodeEdit("Edit Pixel-Value Expression",
virtualBand,
node -> {
node.setExpression(newValue);
updateImages(node, false);
},
node -> {
node.setExpression(oldValue);
updateImages(node, false);
}
);
}
});
}
set.put(new ValidPixelExpressionProperty(band));
set.put(new NoDataValueUsedProperty(band));
set.put(new NoDataValueProperty(band));
set.put(new PropertySupport.ReadWrite<Float>("spectralWavelength", Float.class, "Spectral Wavelength",
"The spectral wavelength in nanometers") {
@Override
public Float getValue() {
return band.getSpectralWavelength();
}
@Override
public void setValue(Float newValue) {
float oldValue = band.getSpectralWavelength();
performUndoableProductNodeEdit("Edit Spectral Wavelength",
band,
node -> node.setSpectralWavelength(newValue),
node -> node.setSpectralWavelength(oldValue));
}
}
);
set.put(new PropertySupport.ReadWrite<Float>("spectralBandWidth", Float.class, "Spectral Bandwidth",
"The spectral bandwidth in nanometers") {
@Override
public Float getValue() {
return band.getSpectralBandwidth();
}
@Override
public void setValue(Float newValue) {
float oldValue = band.getSpectralBandwidth();
performUndoableProductNodeEdit("Edit Spectral Bandwidth",
band,
node -> node.setSpectralBandwidth(newValue),
node -> node.setSpectralBandwidth(oldValue));
}
}
);
Property<RasterDataNode[]> ancillaryVariables = new PropertySupport.ReadWrite<RasterDataNode[]>("ancillaryVariables",
RasterDataNode[].class,
"Ancillary Variables",
"Other rasters that are ancillary variables for this raster (NetCDF-U 'ancillary_variables' attribute)") {
private WeakReference<RastersPropertyEditor> propertyEditorRef;
@Override
public RasterDataNode[] getValue() {
return band.getAncillaryVariables();
}
@Override
public void setValue(RasterDataNode[] newValue) {
WeakHashMap<RasterDataNode, Integer> oldNodes = toWeakMap(band.getAncillaryVariables());
WeakHashMap<RasterDataNode, Integer> newNodes = toWeakMap(newValue);
performUndoableProductNodeEdit("Edit Ancillary Variables",
band,
node -> setAncillaryVariables(node, newNodes, oldNodes),
node -> setAncillaryVariables(node, oldNodes, newNodes));
}
@Override
public PropertyEditor getPropertyEditor() {
RastersPropertyEditor propertyEditor = null;
if (propertyEditorRef != null) {
propertyEditor = propertyEditorRef.get();
}
if (propertyEditor == null) {
propertyEditor = new RastersPropertyEditor(band.getProduct().getBands());
propertyEditorRef = new WeakReference<>(propertyEditor);
}
return propertyEditor;
}
};
set.put(ancillaryVariables);
set.put(new PropertySupport.ReadWrite<String[]>("ancillaryRelations",
String[].class,
"Ancillary Relations",
"Relation names if this raster is an ancillary variable (NetCDF-U 'rel' attribute)") {
@Override
public String[] getValue() {
return band.getAncillaryRelations();
}
@Override
public void setValue(String[] newValue) {
String[] oldValue = band.getAncillaryRelations();
performUndoableProductNodeEdit("Edit Ancillary Relations",
band,
node -> node.setAncillaryRelations(newValue),
node -> node.setAncillaryRelations(oldValue));
}
}
);
return Stream.concat(Stream.of(super.getPropertySets()), Stream.of(set)).toArray(PropertySet[]::new);
}
private String createToolTip(final Band band) {
StringBuilder tooltip = new StringBuilder();
append(tooltip, band.getDescription());
if (band.getSpectralWavelength() > 0.0) {
append(tooltip, String.format("%s nm", band.getSpectralWavelength()));
if (band.getSpectralBandwidth() > 0.0) {
append(tooltip, String.format("+/-%s nm", 0.5 * band.getSpectralBandwidth()));
}
}
append(tooltip, String.format("%d x %d pixels", band.getRasterWidth(), band.getRasterHeight()));
if (band instanceof VirtualBand) {
append(tooltip, String.format("Expr.: %s", ((VirtualBand) band).getExpression()));
}
if (band.getUnit() != null) {
append(tooltip, String.format(" (%s)", band.getUnit()));
}
return tooltip.toString();
}
}
/**
* A node that represents a {@link Quicklook} (=QL).
*
* @author Luis
*/
static class QL extends PNNode<Quicklook> {
public QL(Quicklook ql) {
super(ql);
setIconBaseWithExtension("org/esa/snap/rcp/icons/quicklook16.png");
}
@Override
public boolean canDestroy() {
return true;
}
@Override
public void destroy() {
deleteProductNode(getProductNode().getProduct(),
getProductNode().getProduct().getQuicklookGroup(),
getProductNode());
}
@Override
public Action getPreferredAction() {
return new OpenQuicklookViewAction();
}
}
private static class DataTypeProperty extends PropertySupport.ReadOnly<String> {
private final RasterDataNode raster;
public DataTypeProperty(RasterDataNode raster) {
super("dataType", String.class, "Data Type", "Raster data type");
this.raster = raster;
}
@Override
public String getValue() {
return ProductData.getTypeString(raster.getDataType());
}
}
private static class RasterSizeProperty extends PropertySupport.ReadOnly<String> {
private final RasterDataNode raster;
public RasterSizeProperty(RasterDataNode raster) {
super("rasterSize", String.class, "Raster size", "Width and height of the raster in pixels");
this.raster = raster;
}
@Override
public String getValue() {
return String.format("%d x %d", raster.getRasterWidth(), raster.getRasterHeight());
}
}
private static class UnitProperty extends PropertySupport.ReadWrite<String> {
private final RasterDataNode raster;
public UnitProperty(RasterDataNode raster) {
super("unit", String.class, "Unit", "Geophysical Unit");
this.raster = raster;
}
@Override
public String getValue() {
return raster.getUnit();
}
@Override
public void setValue(String newValue) {
String oldValue = raster.getUnit();
performUndoableProductNodeEdit("Edit Unit",
raster,
node -> node.setUnit(newValue),
node -> node.setUnit(oldValue)
);
}
}
private static class ValidPixelExpressionProperty extends PropertySupport.ReadWrite<String> {
private final RasterDataNode raster;
public ValidPixelExpressionProperty(RasterDataNode raster) {
super("validPixelExpression", String.class, "Valid-Pixel Expression", "Boolean expression which is used to identify valid pixels");
this.raster = raster;
}
@Override
public String getValue() {
final String expression = raster.getValidPixelExpression();
if (expression != null) {
return expression;
}
return "";
}
@Override
public void setValue(String newValue) {
try {
final Product product = raster.getProduct();
final RasterDataNode[] refRasters = BandArithmetic.getRefRasters(newValue, product);
if (refRasters.length > 0 &&
(!BandArithmetic.areRastersEqualInSize(product, newValue) ||
refRasters[0].getRasterHeight() != raster.getRasterHeight() ||
refRasters[0].getRasterWidth() != raster.getRasterWidth())) {
Dialogs.showInformation("Referenced rasters must all be the same size", null);
} else {
String oldValue = raster.getValidPixelExpression();
performUndoableProductNodeEdit("Edit Valid-Pixel Expression",
raster,
node -> {
node.setValidPixelExpression(newValue);
updateImages(node, true);
},
node -> {
node.setValidPixelExpression(oldValue);
updateImages(node, true);
}
);
}
} catch (ParseException e) {
Dialogs.showError("Expression is invalid: " + e.getMessage());
}
}
}
private static class NoDataValueProperty extends PropertySupport.ReadWrite<Double> {
private final RasterDataNode raster;
public NoDataValueProperty(RasterDataNode raster) {
super("noDataValue", Double.class, "No-Data Value", "No-data value used to indicate missing pixels");
this.raster = raster;
}
@Override
public Double getValue() {
return raster.getNoDataValue();
}
@Override
public void setValue(Double newValue) {
double oldValue = raster.getNoDataValue();
performUndoableProductNodeEdit("Edit No-Data Value",
raster,
node -> {
node.setNoDataValue(newValue);
updateImages(node, true);
},
node -> {
node.setNoDataValue(oldValue);
updateImages(node, true);
}
);
}
}
private static class NoDataValueUsedProperty extends PropertySupport.ReadWrite<Boolean> {
private final RasterDataNode raster;
public NoDataValueUsedProperty(RasterDataNode raster) {
super("noDataValueUsed", Boolean.class, "No-Data Value Used", "Is the no-data value in use?");
this.raster = raster;
}
@Override
public Boolean getValue() {
return raster.isNoDataValueUsed();
}
@Override
public void setValue(Boolean newValue) {
boolean oldValue = raster.isNoDataValueUsed();
performUndoableProductNodeEdit("Edit No-Data Value Used",
raster,
node -> {
node.setNoDataValueUsed(newValue);
updateImages(node, true);
},
node -> {
node.setNoDataValueUsed(oldValue);
updateImages(node, true);
}
);
}
}
}
| 36,169 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UndoableProductNodeEdit.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/UndoableProductNodeEdit.java | package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.ProductNode;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
/**
* An undoable edit of a {@code ProductNode}.
*
* @param <T> The product node type.
* @author Norman Fomferra
*/
public class UndoableProductNodeEdit<T extends ProductNode> extends AbstractUndoableEdit {
private final String name;
private final T node;
private final Edit<T> undo;
private final Edit<T> redo;
public UndoableProductNodeEdit(String name, T node, Edit<T> undo, Edit<T> redo) {
this.name = name;
this.node = node;
this.undo = undo;
this.redo = redo;
}
@Override
public String getPresentationName() {
return name;
}
@Override
public void undo() throws CannotUndoException {
if (undo != null) {
undo.edit(node);
}
}
@Override
public void redo() throws CannotRedoException {
if (redo != null) {
redo.edit(node);
}
}
@Override
public boolean canUndo() {
return undo != null;
}
@Override
public boolean canRedo() {
return redo != null;
}
interface Edit<T extends ProductNode> {
void edit(T node);
}
}
| 1,355 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RastersPropertyEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/RastersPropertyEditor.java | package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.openide.explorer.propertysheet.ExPropertyEditor;
import org.openide.explorer.propertysheet.PropertyEnv;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyEditorSupport;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A property editor for selected rasters.
*
* @author Norman Fomferra
*/
class RastersPropertyEditor extends PropertyEditorSupport implements ExPropertyEditor, VetoableChangeListener {
static final String SEPARATOR = ",";
private RasterDataNode[] validNodes;
private CustomEditor customEditor;
public RastersPropertyEditor(RasterDataNode... validNodes) {
this.validNodes = validNodes;
}
@Override
public String getAsText() {
RasterDataNode[] value = (RasterDataNode[]) getValue();
if (value == null) {
return "";
}
return Stream.of(value).map(ProductNode::getName).collect(Collectors.joining(SEPARATOR + " "));
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
if (text == null || text.trim().isEmpty()) {
setValue(new RasterDataNode[0]);
return;
}
HashMap<String, RasterDataNode> validNames = getValidNodeNames();
ArrayList<RasterDataNode> nodes = new ArrayList<>();
String[] names = text.split(SEPARATOR);
for (String name : names) {
name = name.trim();
RasterDataNode node = validNames.get(name);
if (node == null) {
throw new IllegalArgumentException("Illegal entry '" + name + "'!");
}
nodes.add(node);
}
setValue(nodes.toArray(new RasterDataNode[nodes.size()]));
}
@Override
public boolean supportsCustomEditor() {
return true;
}
@Override
public Component getCustomEditor() {
customEditor = new CustomEditor();
//System.out.println(":::::::::::::::: getCustomEditor: customEditor = " + customEditor);
customEditor.setSelectedNodes((RasterDataNode[]) getValue());
return customEditor;
}
@Override
public void attachEnv(PropertyEnv propertyEnv) {
//System.out.println(":::::::::::::::: attachEnv: propertyEnv = " + propertyEnv);
propertyEnv.addVetoableChangeListener(this);
propertyEnv.setState(PropertyEnv.STATE_NEEDS_VALIDATION);
}
@Override
public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
//System.out.println(":::::::::::::::: vetoableChange: evt = " + evt);
//System.out.println(":::::::::::::::: vetoableChange: customEditor = " + customEditor);
if (PropertyEnv.PROP_STATE.equals(evt.getPropertyName())) {
if (customEditor != null) {
RasterDataNode[] selectedNodes = customEditor.getSelectedNodes();
String collect = Stream.of(selectedNodes).map(n -> n.getName()).collect(Collectors.joining("; "));
//System.out.println(":::::::::::::::: vetoableChange: collect = " + collect);
if (PropertyEnv.STATE_VALID.equals(evt.getNewValue())) {
try {
setValue(selectedNodes);
} catch (IllegalArgumentException e) {
throw new PropertyVetoException(e.getMessage(), evt);
}
}
customEditor = null;
}
}
}
private HashMap<String, RasterDataNode> getValidNodeNames() {
HashMap<String, RasterDataNode> validNames = new HashMap<>();
for (RasterDataNode node : validNodes) {
validNames.put(node.getName(), node);
}
return validNames;
}
private class CustomEditor extends JPanel {
private final JList<String> list;
private final DefaultListModel<String> listModel;
public CustomEditor() {
super(new BorderLayout(4, 4));
setBorder(new EmptyBorder(8, 8, 8, 8));
listModel = new DefaultListModel<>();
list = new JList<>(listModel);
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
JScrollPane scrollPane = new JScrollPane(list);
add(new JLabel("Available rasters:"), BorderLayout.NORTH);
add(scrollPane, BorderLayout.CENTER);
}
public RasterDataNode[] getSelectedNodes() throws PropertyVetoException {
HashMap<String, RasterDataNode> validNodeNames = getValidNodeNames();
ArrayList<RasterDataNode> nodes = new ArrayList<>();
int[] selectedIndices = list.getSelectedIndices();
for (int index : selectedIndices) {
String name = listModel.get(index);
RasterDataNode node = validNodeNames.get(name);
if (node != null) {
nodes.add(node);
}
}
return nodes.toArray(new RasterDataNode[nodes.size()]);
}
public void setSelectedNodes(RasterDataNode[] selectedNodes) {
HashMap<RasterDataNode, Integer> indexMap = new HashMap<>();
listModel.clear();
for (int i = 0; i < validNodes.length; i++) {
RasterDataNode node = validNodes[i];
listModel.addElement(node.getName());
indexMap.put(node, i);
}
ArrayList<Integer> indexList = new ArrayList<>();
for (RasterDataNode selectedNode : selectedNodes) {
Integer index = indexMap.get(selectedNode);
if (index != null) {
indexList.add(index);
}
}
int[] indices = new int[indexList.size()];
for (int i = 0; i < indices.length; i++) {
indices[i] = indexList.get(i);
}
list.setSelectedIndices(indices);
}
}
}
| 6,530 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductGroupNode.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/ProductGroupNode.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A node that represents a {@link Product} (=P).
* Every {@code PNode} holds a dedicated undo/redo context.
*
* @author Norman
*/
public class ProductGroupNode extends AbstractNode {
private final ProductManager productManager;
private final PGroup group;
private final Map<Product, ProductNodeListener> productNodeListenerMap;
public ProductGroupNode(ProductManager productManager) {
super(Children.LEAF);
Assert.notNull(productManager, "productManager");
this.productManager = productManager;
this.group = new PGroup();
this.productNodeListenerMap = new HashMap<>();
setChildren(Children.create(group, false));
setDisplayName("Products");
productManager.addListener(new ProductManager.Listener() {
@Override
public void productAdded(ProductManager.Event event) {
group.refresh();
}
@Override
public void productRemoved(ProductManager.Event event) {
uninstallListener(event.getProduct());
group.refresh();
}
});
}
private void installListener(PNode node) {
Product newProduct = node.getProduct();
newProduct.addProductNodeListener(node);
productNodeListenerMap.put(newProduct, node);
}
private void uninstallListener(Product oldProduct) {
ProductNodeListener productNodeListener = productNodeListenerMap.remove(oldProduct);
if (productNodeListener != null) {
oldProduct.removeProductNodeListener(productNodeListener);
}
}
class PGroup extends PNGroupBase<Product> {
@Override
protected boolean createKeys(List<Product> list) {
list.addAll(Arrays.asList(productManager.getProducts()));
return true;
}
@Override
protected Node createNodeForKey(Product key) {
PNode node = new PNode(key);
installListener(node);
return node;
}
}
}
| 2,657 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNNodeSupport.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNNodeSupport.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.esa.snap.rcp.SnapApp;
import org.openide.awt.UndoRedo;
import org.openide.nodes.Children;
import org.openide.nodes.Node;
import org.openide.util.Utilities;
import javax.swing.Action;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
/**
* @author Norman
*/
abstract class PNNodeSupport implements ProductNodeListener {
static UndoRedo getUndoRedo(Node node) {
return node instanceof UndoRedo.Provider ? ((UndoRedo.Provider) node).getUndoRedo() : null;
}
static boolean isDirectChild(Children children, ProductNode productNode) {
return children != Children.LEAF
&& children.snapshot().stream()
.filter(node -> node instanceof PNNode)
.anyMatch(node -> ((PNNode) node).getProductNode() == productNode);
}
static final PNNodeSupport NONE = new PNNodeSupport() {
@Override
public void nodeChanged(ProductNodeEvent event) {
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
}
@Override
public void nodeAdded(ProductNodeEvent event) {
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
}
};
static Action[] getContextActions(ProductNode productNode) {
ArrayList<Action> actionList = new ArrayList<>();
Class<?> type = productNode.getClass();
do {
List<? extends Action> actions = Utilities.actionsForPath("Context/Product/" + type.getSimpleName());
actionList.addAll(actions);
type = type.getSuperclass();
} while (type != null && ProductNode.class.isAssignableFrom(type));
return actionList.toArray(new Action[actionList.size()]);
}
static <T extends ProductNode> void performUndoableProductNodeEdit(String name, T productNode, UndoableProductNodeEdit.Edit<T> action, UndoableProductNodeEdit.Edit<T> undo) {
action.edit(productNode);
Product product = productNode.getProduct();
// be paranoid
if (product != null) {
UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product);
// be paranoid again
if (undoManager != null) {
undoManager.addEdit(new UndoableProductNodeEdit<>(name, productNode, undo, action));
}
}
}
static class PNNodeSupportImpl extends PNNodeSupport {
private final PNNodeBase node;
private final PNGroupBase group;
public PNNodeSupportImpl(PNNodeBase node, PNGroupBase group) {
this.node = node;
this.group = group;
}
@Override
public void nodeChanged(ProductNodeEvent event) {
if (group.shallReactToPropertyChange(event.getPropertyName())) {
final boolean nodeExpanded = NodeExpansionManager.isNodeExpanded(node);
group.refresh();
if (nodeExpanded) {
NodeExpansionManager.expandNode(node);
}
}
delegateProductNodeEvent(l -> l.nodeChanged(event));
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
delegateProductNodeEvent(l -> l.nodeDataChanged(event));
}
@Override
public void nodeAdded(ProductNodeEvent event) {
refreshChildrenAfterAdd(event.getSourceNode());
delegateProductNodeEvent(l -> l.nodeAdded(event));
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
refreshChildrenAfterRemove(event.getSourceNode());
delegateProductNodeEvent(l -> l.nodeRemoved(event));
}
private void refreshChildrenAfterAdd(ProductNode productNode) {
if (group.isDirectChild(productNode)) {
group.refresh();
}
}
private void refreshChildrenAfterRemove(ProductNode productNode) {
if (node.isDirectChild(productNode)) {
group.refresh();
}
}
private void delegateProductNodeEvent(Consumer<ProductNodeListener> action) {
node.getChildren()
.snapshot()
.stream()
.filter(node -> node instanceof ProductNodeListener)
.map(node -> (ProductNodeListener) node)
.forEach(action);
}
}
public static PNNodeSupport create(PNNodeBase tpnNode, PNGroupBase childFactory) {
return childFactory != null ? new PNNodeSupportImpl(tpnNode, childFactory) : NONE;
}
}
| 5,080 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNGGroup.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNGGroup.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.FlagCoding;
import org.esa.snap.core.datamodel.IndexCoding;
import org.esa.snap.core.datamodel.Mask;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.quicklooks.Quicklook;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import java.util.List;
/**
* A group that gets its nodes from a {@link ProductNodeGroup} (=PNG).
*
* @author Norman
*/
@NbBundle.Messages({
"LBL_MetadataGroupName=Metadata",
"LBL_FlagCodingGroupName=Flag Codings",
"LBL_IndexCodingGroupName=Index Codings",
"LBL_VectorDataGroupName=Vector Data",
"LBL_QuicklookGroupName=Quicklooks",
})
abstract class PNGGroup<T extends ProductNode> extends PNGroup<T> {
private final String displayName;
private final ProductNodeGroup<T> group;
protected PNGGroup(String displayName, ProductNodeGroup<T> group) {
Assert.notNull(group, "group");
this.displayName = displayName;
this.group = group;
}
@Override
public Product getProduct() {
return group.getProduct();
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
boolean isDirectChild(ProductNode productNode) {
int nodeCount = group.getNodeCount();
for (int i = 0; i < nodeCount; i++) {
if (group.get(i) == productNode) {
return true;
}
}
return false;
}
@Override
protected boolean createKeys(List<T> list) {
int nodeCount = group.getNodeCount();
for (int i = 0; i < nodeCount; i++) {
list.add(group.get(i));
}
return true;
}
@Override
protected abstract Node createNodeForKey(T key);
public static class B extends PNGGroup<Band> {
private final Product product;
private final ProductNodeGroup<Band> group;
public B(String displayName, ProductNodeGroup<Band> group, Product product) {
super(displayName, group);
this.product = product;
this.group = group;
}
@Override
protected PNNode createNodeForKey(Band key) {
return new PNNode.B(key);
}
@Override
void refresh() {
refreshGroup();
super.refresh();
}
private void refreshGroup() {
final ProductNodeGroup<Band> productBandGroup = product.getBandGroup();
if (group != productBandGroup) {
final Product.AutoGrouping autoGrouping = product.getAutoGrouping();
if (autoGrouping != null) {
final int groupIndex = autoGrouping.indexOf(group.getDisplayName());
group.removeAll();
for (int i = 0; i < productBandGroup.getNodeCount(); i++) {
final Band band = productBandGroup.get(i);
if (autoGrouping.indexOf(band.getName()) == groupIndex) {
group.add(band);
}
}
}
}
}
@Override
public Product getProduct() {
return product;
}
}
public static class TPG extends PNGGroup<TiePointGrid> {
private final Product product;
private final ProductNodeGroup<TiePointGrid> group;
public TPG(String displayName, ProductNodeGroup<TiePointGrid> group, Product product) {
super(displayName, group);
this.product = product;
this.group = group;
}
@Override
protected PNNode createNodeForKey(TiePointGrid key) {
return new PNNode.TPG(key);
}
@Override
void refresh() {
refreshGroup();
super.refresh();
}
private void refreshGroup() {
final ProductNodeGroup<TiePointGrid> productTiePointGridGroup = product.getTiePointGridGroup();
if (group != productTiePointGridGroup) {
final Product.AutoGrouping autoGrouping = product.getAutoGrouping();
if (autoGrouping != null) {
final int groupIndex = autoGrouping.indexOf(group.getDisplayName());
group.removeAll();
for (int i = 0; i < productTiePointGridGroup.getNodeCount(); i++) {
final TiePointGrid tiePointGrid = productTiePointGridGroup.get(i);
if (autoGrouping.indexOf(tiePointGrid.getName()) == groupIndex) {
group.add(tiePointGrid);
}
}
}
}
}
@Override
public Product getProduct() {
return product;
}
}
public static class VDN extends PNGGroup<VectorDataNode> {
public VDN(ProductNodeGroup<VectorDataNode> group) {
super(Bundle.LBL_VectorDataGroupName(), group);
}
@Override
protected PNNode createNodeForKey(VectorDataNode key) {
return new PNNode.VDN(key);
}
}
public static class M extends PNGGroup<Mask> {
private final Product product;
private final ProductNodeGroup<Mask> group;
public M(String displayName, ProductNodeGroup<Mask> group, Product product) {
super(displayName, group);
this.product = product;
this.group = group;
}
@Override
protected PNNode createNodeForKey(Mask key) {
return new PNNode.M(key);
}
@Override
void refresh() {
refreshGroup();
super.refresh();
}
private void refreshGroup() {
final ProductNodeGroup<Mask> productMaskGroup = product.getMaskGroup();
if (group != productMaskGroup) {
final Product.AutoGrouping autoGrouping = product.getAutoGrouping();
if (autoGrouping != null) {
final int groupIndex = autoGrouping.indexOf(group.getDisplayName());
group.removeAll();
for (int i = 0; i < productMaskGroup.getNodeCount(); i++) {
final Mask mask = productMaskGroup.get(i);
if (autoGrouping.indexOf(mask.getName()) == groupIndex) {
group.add(mask);
}
}
}
}
}
@Override
public Product getProduct() {
return product;
}
}
public static class FC extends PNGGroup<FlagCoding> {
public FC(ProductNodeGroup<FlagCoding> group) {
super(Bundle.LBL_FlagCodingGroupName(), group);
}
@Override
protected PNNode createNodeForKey(FlagCoding key) {
return new PNNode.FC(key);
}
}
public static class IC extends PNGGroup<IndexCoding> {
public IC(ProductNodeGroup<IndexCoding> group) {
super(Bundle.LBL_IndexCodingGroupName(), group);
}
@Override
protected PNNode createNodeForKey(IndexCoding key) {
return new PNNode.IC(key);
}
}
public static class ME extends PNGGroup<MetadataElement> {
public ME(ProductNodeGroup<MetadataElement> group) {
super(Bundle.LBL_MetadataGroupName(), group);
}
@Override
protected PNNode createNodeForKey(MetadataElement key) {
return new PNNode.ME(key);
}
}
public static class QL extends PNGGroup<Quicklook> {
public QL(ProductNodeGroup<Quicklook> group) {
super(Bundle.LBL_QuicklookGroupName(), group);
}
@Override
protected PNNode createNodeForKey(Quicklook key) {
return new PNNode.QL(key);
}
}
}
| 8,488 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
NodeExpansionManager.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/NodeExpansionManager.java | package org.esa.snap.rcp.nodes;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.rcp.windows.ProductExplorerTopComponent;
import org.openide.nodes.Node;
/**
* @author Tonio Fincke
*/
public class NodeExpansionManager {
public static boolean isNodeExpanded(Node node) {
final ProductExplorerTopComponent topComponent =
WindowUtilities.getOpened(ProductExplorerTopComponent.class).findFirst().orElse(null);
if (topComponent != null) {
return topComponent.isNodeExpanded(node);
}
return false;
}
public static void expandNode(Node node) {
final ProductExplorerTopComponent topComponent =
WindowUtilities.getOpened(ProductExplorerTopComponent.class).findFirst().orElse(null);
if (topComponent != null) {
topComponent.expandNode(node);
}
}
}
| 895 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GroupByNodeTypeAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/GroupByNodeTypeAction.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import org.esa.snap.rcp.util.BooleanPreferenceKeyAction;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.NbBundle;
/**
* @author Norman, Marco
*/
@ActionID(
category = "View",
id = "GroupByNodeTypeAction"
)
@ActionRegistration(
displayName = "#CTL_GroupByNodeTypeActionName",
lazy = false
)
@ActionReference(
path = "Context/Product/Product",
position = 30,separatorAfter = 35,separatorBefore = 25
)
@NbBundle.Messages({
"CTL_GroupByNodeTypeActionName=Group Nodes by Type"
})
public class GroupByNodeTypeAction extends BooleanPreferenceKeyAction {
public static final String PREFERENCE_KEY = "group_by_node_type";
public static final boolean PREFERENCE_DEFAULT_VALUE = true;
public GroupByNodeTypeAction() {
super(PREFERENCE_KEY, PREFERENCE_DEFAULT_VALUE);
putValue(NAME, Bundle.CTL_GroupByNodeTypeActionName());
}
}
| 1,221 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNGroupNode.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNGroupNode.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.openide.util.lookup.Lookups;
/**
* A node that represents a group of some elements.
*
* @author Norman
*/
class PNGroupNode extends PNNodeBase {
private final PNNodeSupport nodeSupport;
PNGroupNode(PNGroup group) {
super(group, Lookups.fixed(group.getProduct()));
setDisplayName(group.getDisplayName());
setIconBaseWithExtension("org/esa/snap/rcp/icons/RsGroup16.gif");
nodeSupport = PNNodeSupport.create(this, group);
}
@Override
public void nodeChanged(ProductNodeEvent event) {
nodeSupport.nodeChanged(event);
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
nodeSupport.nodeDataChanged(event);
}
@Override
public void nodeAdded(ProductNodeEvent event) {
nodeSupport.nodeAdded(event);
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
nodeSupport.nodeRemoved(event);
}
}
| 1,220 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNGroupBase.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNGroupBase.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.ProductNode;
import org.openide.nodes.ChildFactory;
import java.util.ArrayList;
/**
* A group object serves as a key for {@link PNGroupNode}s and is a child factory for nodes
* representing {@link ProductNode}s.
*
* @author Norman
*/
abstract class PNGroupBase<T> extends ChildFactory.Detachable<T> {
void refresh() {
refresh(true);
}
boolean isDirectChild(ProductNode productNode) {
ArrayList list = new ArrayList<>();
//noinspection unchecked
createKeys(list);
return list.contains(productNode);
}
boolean shallReactToPropertyChange(String propertyName) {
return false;
}
}
| 911 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UndoableProductNodeDeletion.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/UndoableProductNodeDeletion.java | package org.esa.snap.rcp.nodes;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.openide.util.NbBundle;
import javax.swing.undo.AbstractUndoableEdit;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
/**
* An undoable insertion of a {@code ProductNode}.
*
* @param <T> The product node type.
* @author Norman Fomferra
* @author Tonio Fincke
*/
@NbBundle.Messages("LBL_UndoableProductNodeDeletionName=Delete ''{0}''")
public class UndoableProductNodeDeletion<T extends ProductNode> extends AbstractUndoableEdit {
private ProductNodeGroup<T> productNodeGroup;
private T productNode;
private final int index;
@SuppressWarnings("unchecked")
public UndoableProductNodeDeletion(ProductNodeGroup<T> productNodeGroup, T productNode, int index) {
Assert.notNull(productNodeGroup, "group");
Assert.notNull(productNode, "node");
this.productNodeGroup = productNodeGroup;
this.productNode = productNode;
this.index = index;
}
public T getProductNode() {
return productNode;
}
@Override
public String getPresentationName() {
return Bundle.LBL_UndoableProductNodeDeletionName(productNode.getName());
}
@Override
public void undo() throws CannotUndoException {
super.undo();
if (index < productNodeGroup.getNodeCount()) {
productNodeGroup.add(index, productNode);
} else {
productNodeGroup.add(productNode);
}
}
@Override
public void redo() throws CannotRedoException {
super.redo();
productNodeGroup.remove(productNode);
}
@Override
public void die() {
productNodeGroup = null;
productNode = null;
}
}
| 1,884 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNGroup.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNGroup.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
/**
* A group object serves as a key for {@link PNGroupNode}s and is a child factory for nodes
* representing {@link ProductNode}s.
*
* @author Norman
*/
abstract class PNGroup<T> extends PNGroupBase<T> {
public abstract Product getProduct();
public abstract String getDisplayName();
}
| 612 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PNGroupingGroup.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/nodes/PNGroupingGroup.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.nodes;
import com.bc.ceres.core.Assert;
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.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A group that gets its nodes from a {@link ProductNodeGroup} (=PNG)
* and can have a {@link ProductNodeGroup} as child
*
* @author Tonio Fincke
*/
@NbBundle.Messages({
"LBL_TiePointGroupName=Tie-Point Grids",
"LBL_BandGroupName=Bands",
"LBL_MaskGroupName=Masks",
})
abstract class PNGroupingGroup extends PNGroup<Object> {
private final String displayName;
private final ProductNodeGroup group;
List<Node> nodes;
Map<String, Boolean> nodesAreSelected;
protected PNGroupingGroup(String displayName, ProductNodeGroup group) {
Assert.notNull(group, "group");
this.displayName = displayName;
this.group = group;
nodes = new ArrayList<>();
nodesAreSelected = new HashMap<>();
}
@Override
public Product getProduct() {
return group.getProduct();
}
@Override
public String getDisplayName() {
return displayName;
}
@Override
boolean isDirectChild(ProductNode productNode) {
return group.contains(productNode);
}
@Override
void refresh() {
for (Node node : nodes) {
nodesAreSelected.put(node.getDisplayName(), NodeExpansionManager.isNodeExpanded(node));
}
nodes.clear();
super.refresh();
for (Node node : nodes) {
if (nodesAreSelected.containsKey(node.getDisplayName()) && nodesAreSelected.get(node.getDisplayName())) {
NodeExpansionManager.expandNode(node);
}
}
nodesAreSelected.clear();
}
@Override
boolean shallReactToPropertyChange(String propertyName) {
return propertyName.equals("autoGrouping");
}
/**
* A group that represents a {@link ProductNodeGroup}
* of {@link Band} members
*
* @author Tonio
*/
static class B extends PNGroupingGroup {
private final ProductNodeGroup<Band> group;
protected B(ProductNodeGroup<Band> group) {
super(Bundle.LBL_BandGroupName(), group);
this.group = group;
}
@Override
protected Node createNodeForKey(Object key) {
if (key instanceof Band) {
return new PNNode.B((Band) key);
} else {
final PNGroupNode pnGroupNode = new PNGroupNode((PNGroup) key);
nodes.add(pnGroupNode);
return pnGroupNode;
}
}
@Override
protected boolean createKeys(List<Object> list) {
final Product.AutoGrouping autoGrouping = getProduct().getAutoGrouping();
if (autoGrouping == null) {
for (int i = 0; i < group.getNodeCount(); i++) {
list.add(group.get(i));
}
return true;
}
ProductNodeGroup<Band>[] autogroupingNodes = new ProductNodeGroup[autoGrouping.size() + 1];
for (int i = 0; i < autoGrouping.size(); i++) {
autogroupingNodes[i] = new ProductNodeGroup<>(autoGrouping.get(i)[0]);
}
autogroupingNodes[autoGrouping.size()] = new ProductNodeGroup<>(Bundle.LBL_BandGroupName());
for (int i = 0; i < this.group.getNodeCount(); i++) {
final Band band = this.group.get(i);
final int index = autoGrouping.indexOf(band.getName());
if (index != -1) {
autogroupingNodes[index].add(band);
} else {
autogroupingNodes[autoGrouping.size()].add(band);
}
}
for (int i = 0; i < autoGrouping.size(); i++) {
if (autogroupingNodes[i].getNodeCount() > 0) {
list.add(new PNGGroup.B(autoGrouping.get(i)[0], autogroupingNodes[i], getProduct()));
}
}
for (int i = 0; i < autogroupingNodes[autoGrouping.size()].getNodeCount(); i++) {
list.add(autogroupingNodes[autoGrouping.size()].get(i));
}
return true;
}
}
/**
* A group that represents a {@link ProductNodeGroup}
* of {@link TiePointGrid} members
*
* @author Tonio
*/
static class TPG extends PNGroupingGroup {
private final ProductNodeGroup<TiePointGrid> group;
protected TPG(ProductNodeGroup<TiePointGrid> group) {
super(Bundle.LBL_TiePointGroupName(), group);
this.group = group;
}
@Override
protected Node createNodeForKey(Object key) {
if (key instanceof TiePointGrid) {
return new PNNode.TPG((TiePointGrid) key);
} else {
final PNGroupNode pnGroupNode = new PNGroupNode((PNGroup) key);
nodes.add(pnGroupNode);
return pnGroupNode;
}
}
@Override
protected boolean createKeys(List<Object> list) {
final Product.AutoGrouping autoGrouping = getProduct().getAutoGrouping();
if (autoGrouping == null) {
for (int i = 0; i < group.getNodeCount(); i++) {
list.add(group.get(i));
}
return true;
}
ProductNodeGroup<TiePointGrid>[] autogroupingNodes = new ProductNodeGroup[autoGrouping.size() + 1];
for (int i = 0; i < autoGrouping.size(); i++) {
autogroupingNodes[i] = new ProductNodeGroup<>(autoGrouping.get(i)[0]);
}
autogroupingNodes[autoGrouping.size()] = new ProductNodeGroup<>(Bundle.LBL_TiePointGroupName());
for (int i = 0; i < this.group.getNodeCount(); i++) {
final TiePointGrid tiePointGrid = this.group.get(i);
final int index = autoGrouping.indexOf(tiePointGrid.getName());
if (index != -1) {
autogroupingNodes[index].add(tiePointGrid);
} else {
autogroupingNodes[autoGrouping.size()].add(tiePointGrid);
}
}
for (int i = 0; i < autoGrouping.size(); i++) {
if (autogroupingNodes[i].getNodeCount() > 0) {
list.add(new PNGGroup.TPG(autoGrouping.get(i)[0], autogroupingNodes[i], getProduct()));
}
}
for (int i = 0; i < autogroupingNodes[autoGrouping.size()].getNodeCount(); i++) {
list.add(autogroupingNodes[autoGrouping.size()].get(i));
}
return true;
}
}
/**
* A group that represents a {@link ProductNodeGroup}
* of {@link Mask} members
*
* @author Tonio
*/
static class M extends PNGroupingGroup {
private final ProductNodeGroup<Mask> group;
protected M(ProductNodeGroup<Mask> group) {
super(Bundle.LBL_MaskGroupName(), group);
this.group = group;
}
@Override
protected Node createNodeForKey(Object key) {
if (key instanceof Mask) {
return new PNNode.M((Mask) key);
} else {
final PNGroupNode pnGroupNode = new PNGroupNode((PNGroup) key);
nodes.add(pnGroupNode);
return pnGroupNode;
}
}
@Override
protected boolean createKeys(List<Object> list) {
final Product.AutoGrouping autoGrouping = getProduct().getAutoGrouping();
if (autoGrouping == null) {
for (int i = 0; i < group.getNodeCount(); i++) {
list.add(group.get(i));
}
return true;
}
ProductNodeGroup<Mask>[] autogroupingNodes = new ProductNodeGroup[autoGrouping.size() + 1];
for (int i = 0; i < autoGrouping.size(); i++) {
autogroupingNodes[i] = new ProductNodeGroup<>(autoGrouping.get(i)[0]);
}
autogroupingNodes[autoGrouping.size()] = new ProductNodeGroup<>(Bundle.LBL_MaskGroupName());
for (int i = 0; i < this.group.getNodeCount(); i++) {
final Mask mask = this.group.get(i);
final int index = autoGrouping.indexOf(mask.getName());
if (index != -1) {
autogroupingNodes[index].add(mask);
} else {
autogroupingNodes[autoGrouping.size()].add(mask);
}
}
for (int i = 0; i < autoGrouping.size(); i++) {
if (autogroupingNodes[i].getNodeCount() > 0) {
list.add(new PNGGroup.M(autoGrouping.get(i)[0], autogroupingNodes[i], getProduct()));
}
}
for (int i = 0; i < autogroupingNodes[autoGrouping.size()].getNodeCount(); i++) {
list.add(autogroupingNodes[autoGrouping.size()].get(i));
}
return true;
}
}
} | 9,638 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PixelInfoTopComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/windows/PixelInfoTopComponent.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.windows;
import com.bc.ceres.glayer.support.ImageLayer;
import org.esa.snap.core.datamodel.*;
import org.locationtech.jts.geom.Point;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.pixelinfo.PixelInfoView;
import org.esa.snap.ui.PixelPositionListener;
import org.esa.snap.ui.product.ProductSceneView;
import org.netbeans.api.annotations.common.NonNull;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.NbBundle;
import org.openide.windows.TopComponent;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;
import java.awt.BorderLayout;
import java.awt.event.MouseEvent;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Experimental top component which displays information about selected pixel.
*/
@TopComponent.Description(
preferredID = "PixelInfoTopComponent",
iconBase = "org/esa/snap/rcp/icons/PixelInfo.png",
persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(mode = "explorer",
openAtStartup = true,
position = 20
)
@ActionID(category = "Window", id = "org.esa.snap.rcp.window.PixelInfoTopComponent")
@ActionReference(path = "Menu/View/Tool Windows", position = 0)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_PixelInfoTopComponentName",
preferredID = "PixelInfoTopComponent"
)
@NbBundle.Messages({
"CTL_PixelInfoTopComponentName=Pixel Info",
"CTL_PixelInfoTopComponentDescription=Displays information about current pixel",
})
public final class PixelInfoTopComponent extends ToolTopComponent {
private ProductSceneView currentView;
private PixelPositionListener pixelPositionListener;
private final PixelInfoView pixelInfoView;
private final PinSelectionChangeListener pinSelectionChangeListener;
private final PinChangedListener pinChangedListener;
private final JCheckBox pinCheckbox;
public PixelInfoTopComponent() {
setName(Bundle.CTL_PixelInfoTopComponentName());
setToolTipText(Bundle.CTL_PixelInfoTopComponentDescription());
putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.TRUE);
pixelPositionListener = new MyPixelPositionListener();
pinSelectionChangeListener = new PinSelectionChangeListener();
pinChangedListener = new PinChangedListener();
pixelInfoView = new PixelInfoView();
pinCheckbox = new JCheckBox("Snap to selected pin");
pinCheckbox.setName("pinCheckbox");
pinCheckbox.setSelected(false);
pinCheckbox.addActionListener(e -> updatePixelInfo());
setLayout(new BorderLayout());
add(pixelInfoView, BorderLayout.CENTER);
add(pinCheckbox, BorderLayout.SOUTH);
final SnapApp snapApp = SnapApp.getDefault();
snapApp.getProductManager().addListener(new PxInfoProductManagerListener());
setCurrentView(snapApp.getSelectedProductSceneView());
}
@Override
protected void productSceneViewSelected(@NonNull ProductSceneView view) {
setCurrentView(view);
if (isSnapToSelectedPin()) {
snapToSelectedPin();
}
}
@Override
protected void productSceneViewDeselected(@NonNull ProductSceneView view) {
setCurrentView(null);
if (isSnapToSelectedPin()) {
snapToSelectedPin();
}
}
private void setCurrentView(ProductSceneView view) {
if (currentView == view) {
return;
}
if (currentView != null) {
currentView.removePixelPositionListener(pixelPositionListener);
currentView.removePropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN,
pinSelectionChangeListener);
Product product = currentView.getProduct();
if (product != null) {
product.removeProductNodeListener(pinChangedListener);
}
} else {
pixelInfoView.clearProductNodeRefs();
}
currentView = view;
if (currentView != null) {
currentView.addPixelPositionListener(pixelPositionListener);
currentView.addPropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN,
pinSelectionChangeListener);
Product product = currentView.getProduct();
if (product != null) {
product.addProductNodeListener(pinChangedListener);
}
} else {
pixelInfoView.reset();
}
}
private void updatePixelInfo() {
if (isSnapToSelectedPin()) {
SwingUtilities.invokeLater(this::snapToSelectedPin);
} else {
pixelInfoView.updatePixelValues(currentView, -1, -1, 0, false);
}
}
private boolean isSnapToSelectedPin() {
return pinCheckbox.isSelected();
}
private void snapToSelectedPin() {
final Placemark pin = currentView != null ? currentView.getSelectedPin() : null;
if (pin != null) {
//todo [multisize_products] replace this very ugly code by using the scene raster transformer - tf 20151113
PixelPos rasterPos = new PixelPos();
final Point pinSceneCoords = (Point) pin.getFeature().getDefaultGeometry();
final Point2D.Double pinSceneCoordsDouble = new Point2D.Double(pinSceneCoords.getX(), pinSceneCoords.getY());
try {
currentView.getRaster().getImageToModelTransform().createInverse().transform(pinSceneCoordsDouble, rasterPos);
} catch (NoninvertibleTransformException e) {
rasterPos = pin.getPixelPos();
}
final int x = MathUtils.floorInt(rasterPos.x);
final int y = MathUtils.floorInt(rasterPos.y);
pixelInfoView.updatePixelValues(currentView, x, y, 0, true);
} else {
pixelInfoView.updatePixelValues(currentView, -1, -1, 0, false);
}
}
private class PinSelectionChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (isVisible()) {
updatePixelInfo();
}
}
}
private class PinChangedListener implements ProductNodeListener {
@Override
public void nodeChanged(ProductNodeEvent event) {
if (Placemark.PROPERTY_NAME_PIXELPOS.equals(event.getPropertyName())) {
handlePinEvent(event);
}
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
handlePinEvent(event);
}
@Override
public void nodeAdded(ProductNodeEvent event) {
handlePinEvent(event);
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
handlePinEvent(event);
}
private void handlePinEvent(ProductNodeEvent event) {
if (currentView != null
&& event.getSourceNode() == currentView.getSelectedPin()) {
updatePixelInfo();
}
}
}
private class MyPixelPositionListener implements PixelPositionListener {
@Override
public void pixelPosChanged(ImageLayer baseImageLayer, int pixelX, int pixelY, int currentLevel, boolean pixelPosValid, MouseEvent e) {
if (isActive()) {
pixelInfoView.updatePixelValues(currentView, pixelX, pixelY, currentLevel, pixelPosValid);
}
}
@Override
public void pixelPosNotAvailable() {
//do nothing
}
private boolean isActive() {
return isVisible() && !isSnapToSelectedPin();
}
}
private class PxInfoProductManagerListener implements ProductManager.Listener {
@Override
public void productAdded(ProductManager.Event event) {
// nothing to do here
}
@Override
public void productRemoved(ProductManager.Event event) {
pixelInfoView.reset();
}
}
}
| 8,713 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolTopComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/windows/ToolTopComponent.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.windows;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.ui.product.ProductSceneView;
import org.netbeans.api.annotations.common.NonNull;
import org.openide.windows.TopComponent;
/**
* A base class for the implementation of SNAP tool windows.
*
* @author Marco Peters
* @author Norman Fomferra
* @since SNAP 2.0
*/
public abstract class ToolTopComponent extends TopComponent {
protected ToolTopComponent() {
SnapApp.getDefault().getSelectionSupport(ProductSceneView.class).addHandler((oldValue, newValue) -> {
if (oldValue != null) {
productSceneViewDeselected(oldValue);
}
if (newValue != null) {
productSceneViewSelected(newValue);
}
});
}
public ProductSceneView getSelectedProductSceneView() {
return SnapApp.getDefault().getSelectedProductSceneView();
}
protected void productSceneViewSelected(@NonNull ProductSceneView view) {
}
protected void productSceneViewDeselected(@NonNull ProductSceneView view) {
}
}
| 1,814 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
NavigationTopComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/windows/NavigationTopComponent.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.windows;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.glayer.swing.LayerCanvasModel;
import com.bc.ceres.grender.AdjustableView;
import com.bc.ceres.grender.Viewport;
import eu.esa.snap.netbeans.docwin.WindowUtilities;
import org.esa.snap.core.datamodel.*;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.help.HelpAction;
import org.esa.snap.rcp.actions.tools.SyncImageCursorsAction;
import org.esa.snap.rcp.actions.tools.SyncImageViewsAction;
import org.esa.snap.rcp.nav.NavigationCanvas;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.ProductSceneView;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import javax.swing.*;
import javax.swing.text.NumberFormatter;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import static java.lang.Math.*;
@TopComponent.Description(
preferredID = "NavigationTopComponent",
iconBase = "org/esa/snap/rcp/icons/Navigation16.gif",
persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(
mode = "navigator",
openAtStartup = true,
position = 10
)
@ActionID(category = "Window", id = "org.esa.snap.rcp.window.NavigationTopComponent")
@ActionReference(path = "Menu/View/Tool Windows", position = 0)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_NavigationTopComponentName",
preferredID = "NavigationTopComponent"
)
@NbBundle.Messages({
"CTL_NavigationTopComponentName=Navigation",
"CTL_NavigationTopComponentDescription=Navigates through the currently selected image view",
})
public class NavigationTopComponent extends TopComponent {
public static final String ID = NavigationTopComponent.class.getName();
private static final int MIN_SLIDER_VALUE = -100;
private static final int MAX_SLIDER_VALUE = +100;
// TODO: Make sure help page is available for ID
private static final String HELP_ID = "showNavigationWnd";
private LayerCanvasModelChangeHandler layerCanvasModelChangeChangeHandler;
private ProductNodeListener productNodeChangeHandler;
private ProductSceneView currentView;
private NavigationCanvas canvas;
private AbstractButton zoomInButton;
private AbstractButton zoomDefaultButton;
private AbstractButton zoomOutButton;
private AbstractButton zoomAllButton;
private AbstractButton syncViewsButton;
private AbstractButton syncCursorButton;
private JTextField zoomFactorField;
private JFormattedTextField rotationAngleField;
private JSlider zoomSlider;
private boolean inUpdateMode;
private DecimalFormat scaleFormat;
private Color zeroRotationAngleBackground;
private final Color positiveRotationAngleBackground = new Color(221, 255, 221); //#ddffdd
private final Color negativeRotationAngleBackground = new Color(255, 221, 221); //#ffdddd
private JSpinner rotationAngleSpinner;
public NavigationTopComponent() {
initComponent();
SnapApp.getDefault().getSelectionSupport(ProductSceneView.class).addHandler((oldValue, newValue) -> setCurrentView(newValue));
}
public void initComponent() {
layerCanvasModelChangeChangeHandler = new LayerCanvasModelChangeHandler();
productNodeChangeHandler = createProductNodeListener();
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
scaleFormat = new DecimalFormat("#####.##", decimalFormatSymbols);
scaleFormat.setGroupingUsed(false);
scaleFormat.setDecimalSeparatorAlwaysShown(false);
zoomInButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomIn24.gif"), false);
zoomInButton.setToolTipText("Zoom in."); /*I18N*/
zoomInButton.setName("zoomInButton");
zoomInButton.addActionListener(e -> zoom(getCurrentView().getZoomFactor() * 1.2));
zoomOutButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomOut24.gif"), false);
zoomOutButton.setName("zoomOutButton");
zoomOutButton.setToolTipText("Zoom out."); /*I18N*/
zoomOutButton.addActionListener(e -> zoom(getCurrentView().getZoomFactor() / 1.2));
zoomDefaultButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomPixel24.gif"), false);
zoomDefaultButton.setToolTipText("Actual Pixels (image pixel = view pixel)."); /*I18N*/
zoomDefaultButton.setName("zoomDefaultButton");
zoomDefaultButton.addActionListener(e -> zoomToPixelResolution());
zoomAllButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomAll24.gif"), false);
zoomAllButton.setName("zoomAllButton");
zoomAllButton.setToolTipText("Zoom all."); /*I18N*/
zoomAllButton.addActionListener(e -> zoomAll());
syncViewsButton = ToolButtonFactory.createButton(new SyncImageViewsAction(), true);
syncViewsButton.setName("syncViewsButton");
syncViewsButton.setText(null);
syncCursorButton = ToolButtonFactory.createButton(new SyncImageCursorsAction(), true);
syncCursorButton.setName("syncCursorButton");
syncCursorButton.setText(null);
AbstractButton helpButton = ToolButtonFactory.createButton(new HelpAction(this), false);
helpButton.setName("helpButton");
final JPanel eastPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.NONE;
gbc.weightx = 0.0;
gbc.weighty = 0.0;
gbc.gridy = 0;
eastPane.add(zoomInButton, gbc);
gbc.gridy++;
eastPane.add(zoomOutButton, gbc);
gbc.gridy++;
eastPane.add(zoomDefaultButton, gbc);
gbc.gridy++;
eastPane.add(zoomAllButton, gbc);
gbc.gridy++;
eastPane.add(syncViewsButton, gbc);
gbc.gridy++;
eastPane.add(syncCursorButton, gbc);
gbc.gridy++;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.VERTICAL;
eastPane.add(new JLabel(" "), gbc); // filler
gbc.fill = GridBagConstraints.NONE;
gbc.weighty = 0.0;
gbc.gridy++;
eastPane.add(helpButton, gbc);
zoomFactorField = new JTextField();
zoomFactorField.setColumns(8);
zoomFactorField.setHorizontalAlignment(JTextField.CENTER);
zoomFactorField.addActionListener(e -> handleZoomFactorFieldUserInput());
zoomFactorField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(final FocusEvent e) {
handleZoomFactorFieldUserInput();
}
});
rotationAngleSpinner = new JSpinner(new SpinnerNumberModel(0.0, -1800.0, 1800.0, 5.0));
final JSpinner.NumberEditor editor = (JSpinner.NumberEditor) rotationAngleSpinner.getEditor();
rotationAngleField = editor.getTextField();
final DecimalFormat rotationFormat;
rotationFormat = new DecimalFormat("#####.##°", decimalFormatSymbols);
rotationFormat.setGroupingUsed(false);
rotationFormat.setDecimalSeparatorAlwaysShown(false);
rotationAngleField.setFormatterFactory(new JFormattedTextField.AbstractFormatterFactory() {
@Override
public JFormattedTextField.AbstractFormatter getFormatter(JFormattedTextField tf) {
return new NumberFormatter(rotationFormat);
}
});
rotationAngleField.setColumns(6);
rotationAngleField.setEditable(true);
rotationAngleField.setHorizontalAlignment(JTextField.CENTER);
rotationAngleField.addActionListener(e -> handleRotationAngleFieldUserInput());
rotationAngleField.addFocusListener(new FocusAdapter() {
@Override
public void focusLost(FocusEvent e) {
handleRotationAngleFieldUserInput();
}
});
rotationAngleField.addPropertyChangeListener("value", evt -> handleRotationAngleFieldUserInput());
zoomSlider = new JSlider(JSlider.HORIZONTAL);
zoomSlider.setValue(0);
zoomSlider.setMinimum(MIN_SLIDER_VALUE);
zoomSlider.setMaximum(MAX_SLIDER_VALUE);
zoomSlider.setPaintTicks(false);
zoomSlider.setPaintLabels(false);
zoomSlider.setSnapToTicks(false);
zoomSlider.setPaintTrack(true);
zoomSlider.addChangeListener(e -> {
if (!inUpdateMode) {
zoom(sliderValueToZoomFactor(zoomSlider.getValue()));
}
});
final JPanel zoomFactorPane = new JPanel(new BorderLayout());
zoomFactorPane.add(zoomFactorField, BorderLayout.WEST);
final JPanel rotationAnglePane = new JPanel(new BorderLayout());
rotationAnglePane.add(rotationAngleSpinner, BorderLayout.EAST);
rotationAnglePane.add(new JLabel(" "), BorderLayout.CENTER);
final JPanel sliderPane = new JPanel(new BorderLayout(2, 2));
sliderPane.add(zoomFactorPane, BorderLayout.WEST);
sliderPane.add(zoomSlider, BorderLayout.CENTER);
sliderPane.add(rotationAnglePane, BorderLayout.EAST);
canvas = createNavigationCanvas();
canvas.setBackground(new Color(138, 133, 128)); // image background
canvas.setForeground(new Color(153, 153, 204)); // slider overlay
final JPanel centerPane = new JPanel(new BorderLayout(4, 4));
centerPane.add(BorderLayout.CENTER, canvas);
centerPane.add(BorderLayout.SOUTH, sliderPane);
setLayout(new BorderLayout(4, 4));
setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4));
add(centerPane, BorderLayout.CENTER);
add(eastPane, BorderLayout.EAST);
setPreferredSize(new Dimension(320, 320));
updateCurrentView();
updateState();
}
private void updateCurrentView() {
setCurrentView(Utilities.actionsGlobalContext().lookup(ProductSceneView.class));
}
public ProductSceneView getCurrentView() {
return currentView;
}
public void setCurrentView(final ProductSceneView newView) {
if (currentView != newView) {
final ProductSceneView oldView = currentView;
if (oldView != null) {
Product product = oldView.getProduct();
if (product != null) {
product.removeProductNodeListener(productNodeChangeHandler);
}
LayerCanvas layerCanvas = oldView.getLayerCanvas();
if (layerCanvas != null) {
layerCanvas.getModel().removeChangeListener(layerCanvasModelChangeChangeHandler);
}
}
currentView = newView;
if (currentView != null) {
Product product = currentView.getProduct();
if (product != null) {
product.addProductNodeListener(productNodeChangeHandler);
}
LayerCanvas layerCanvas = currentView.getLayerCanvas();
if (layerCanvas != null) {
layerCanvas.getModel().addChangeListener(layerCanvasModelChangeChangeHandler);
}
}
canvas.handleViewChanged(oldView, newView);
updateState();
}
}
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx(HELP_ID);
}
NavigationCanvas createNavigationCanvas() {
return new NavigationCanvas(this);
}
private void handleZoomFactorFieldUserInput() {
Double zf = getZoomFactorFieldValue();
if (zf != null) {
updateScaleField(zf);
zoom(zf);
}
}
private void handleRotationAngleFieldUserInput() {
final double ra = Math.round(getRotationAngleFieldValue() / 5) * 5.0;
updateRotationField(ra);
rotate(ra);
}
private Double getZoomFactorFieldValue() {
final String text = zoomFactorField.getText();
if (text.contains(":")) {
return parseTextualValue(text);
} else {
try {
double v = Double.parseDouble(text);
return v > 0 ? v : null;
} catch (NumberFormatException e) {
return null;
}
}
}
private double getRotationAngleFieldValue() {
String text = rotationAngleField.getText();
if (text != null) {
while (text.endsWith("°")) {
text = text.substring(0, text.length() - 1);
}
try {
final double v = Double.parseDouble(text);
final double max = 360 * 100;
final double negMax = max * -1;
if (v > max || v < negMax) {
return 0.0;
}
return v;
} catch (NumberFormatException e) {
// ok
}
}
return 0.0;
}
private static Double parseTextualValue(String text) {
final String[] numbers = text.split(":");
if (numbers.length == 2) {
double dividend;
double divisor;
try {
dividend = Double.parseDouble(numbers[0]);
divisor = Double.parseDouble(numbers[1]);
} catch (NumberFormatException e) {
return null;
}
if (divisor == 0) {
return null;
}
double factor = dividend / divisor;
return factor > 0 ? factor : null;
} else {
return null;
}
}
public void setModelOffset(final double modelOffsetX, final double modelOffsetY) {
final ProductSceneView view = getCurrentView();
if (view != null) {
view.getLayerCanvas().getViewport().setOffset(modelOffsetX, modelOffsetY);
maybeSynchronizeCompatibleProductViews();
}
}
private void zoomToPixelResolution() {
final ProductSceneView view = getCurrentView();
if (view != null) {
final LayerCanvas layerCanvas = view.getLayerCanvas();
layerCanvas.getViewport().setZoomFactor(layerCanvas.getDefaultZoomFactor());
maybeSynchronizeCompatibleProductViews();
}
}
public void zoom(final double zoomFactor) {
final ProductSceneView view = getCurrentView();
if (view != null && zoomFactor > 0) {
view.getLayerCanvas().getViewport().setZoomFactor(zoomFactor);
maybeSynchronizeCompatibleProductViews();
}
}
private void rotate(Double rotationAngle) {
final ProductSceneView view = getCurrentView();
if (view != null) {
view.getLayerCanvas().getViewport().setOrientation(rotationAngle * MathUtils.DTOR);
maybeSynchronizeCompatibleProductViews();
}
}
public void zoomAll() {
final ProductSceneView view = getCurrentView();
if (view != null) {
view.getLayerCanvas().zoomAll();
maybeSynchronizeCompatibleProductViews();
}
}
private void maybeSynchronizeCompatibleProductViews() {
if (syncViewsButton.isSelected()) {
synchronizeCompatibleProductViews();
}
}
private void synchronizeCompatibleProductViews() {
final ProductSceneView currentView = getCurrentView();
if (currentView == null) {
return;
}
WindowUtilities.getOpened(ProductSceneViewTopComponent.class).forEach(productSceneViewTopComponent -> {
final ProductSceneView view = productSceneViewTopComponent.getView();
if (view != currentView) {
currentView.synchronizeViewportIfPossible(view);
}
});
}
/**
* @param sv a value between MIN_SLIDER_VALUE and MAX_SLIDER_VALUE
* @return a value between min and max zoom factor of the AdjustableView
*/
private double sliderValueToZoomFactor(final int sv) {
AdjustableView adjustableView = getCurrentView().getLayerCanvas();
double f1 = scaleExp2Min(adjustableView);
double f2 = scaleExp2Max(adjustableView);
double s1 = zoomSlider.getMinimum();
double s2 = zoomSlider.getMaximum();
double v1 = (sv - s1) / (s2 - s1);
double v2 = f1 + v1 * (f2 - f1);
return exp2(v2);
}
/**
* @param zf a value between min and max zoom factor of the AdjustableView
* @return a value between MIN_SLIDER_VALUE and MAX_SLIDER_VALUE
*/
private int zoomFactorToSliderValue(final double zf) {
AdjustableView adjustableView = getCurrentView().getLayerCanvas();
double f1 = scaleExp2Min(adjustableView);
double f2 = scaleExp2Max(adjustableView);
double s1 = zoomSlider.getMinimum();
double s2 = zoomSlider.getMaximum();
double v2 = log2(zf);
double v1 = max(0.0, min(1.0, (v2 - f1) / (f2 - f1)));
return (int) ((s1 + v1 * (s2 - s1)) + 0.5);
}
private void updateState() {
final boolean canNavigate = getCurrentView() != null;
zoomInButton.setEnabled(canNavigate);
zoomDefaultButton.setEnabled(canNavigate);
zoomOutButton.setEnabled(canNavigate);
zoomAllButton.setEnabled(canNavigate);
zoomSlider.setEnabled(canNavigate);
syncViewsButton.setEnabled(canNavigate);
syncCursorButton.setEnabled(canNavigate);
zoomFactorField.setEnabled(canNavigate);
rotationAngleSpinner.setEnabled(canNavigate);
updateTitle();
updateValues();
}
private void updateTitle() {
if (getCurrentView() != null) {
if (getCurrentView().isRGB()) {
setDisplayName(Bundle.CTL_NavigationTopComponentName() + " - " + getCurrentView().getProduct().getProductRefString() + " RGB");
} else {
setDisplayName(Bundle.CTL_NavigationTopComponentName() + " - " + getCurrentView().getRaster().getDisplayName());
}
} else {
setDisplayName(Bundle.CTL_NavigationTopComponentName());
}
}
private void updateValues() {
final ProductSceneView view = getCurrentView();
if (view != null) {
boolean oldState = inUpdateMode;
inUpdateMode = true;
double zf = view.getZoomFactor();
updateZoomSlider(zf);
updateScaleField(zf);
updateRotationField(view.getOrientation() * MathUtils.RTOD);
inUpdateMode = oldState;
}
}
private void updateZoomSlider(double zf) {
int sv = zoomFactorToSliderValue(zf);
zoomSlider.setValue(sv);
}
private void updateScaleField(double zf) {
String text;
if (zf > 1.0) {
text = scaleFormat.format(roundScale(zf)) + " : 1";
} else if (zf < 1.0) {
text = "1 : " + scaleFormat.format(roundScale(1.0 / zf));
} else {
text = "1 : 1";
}
zoomFactorField.setText(text);
}
private void updateRotationField(double ra) {
while (ra > 180) {
ra -= 360;
}
while (ra < -180) {
ra += 360;
}
rotationAngleField.setValue(ra);
if (zeroRotationAngleBackground == null) {
zeroRotationAngleBackground = rotationAngleField.getBackground();
}
if (ra > 0) {
rotationAngleField.setBackground(positiveRotationAngleBackground);
} else if (ra < 0) {
rotationAngleField.setBackground(negativeRotationAngleBackground);
} else {
rotationAngleField.setBackground(zeroRotationAngleBackground);
}
}
private static double roundScale(double x) {
double e = floor((log10(x)));
double f = 10.0 * pow(10.0, e);
double fx = x * f;
double rfx = round(fx);
if (abs((rfx + 0.5) - fx) <= abs(rfx - fx)) {
rfx += 0.5;
}
return rfx / f;
}
private static double scaleExp2Min(AdjustableView adjustableView) {
return floor(log2(adjustableView.getMinZoomFactor()));
}
private static double scaleExp2Max(AdjustableView adjustableView) {
return floor(log2(adjustableView.getMaxZoomFactor()) + 1);
}
private static double log2(double x) {
return log(x) / log(2.0);
}
private static double exp2(double x) {
return pow(2.0, x);
}
private ProductNodeListener createProductNodeListener() {
return new ProductNodeListenerAdapter() {
@Override
public void nodeChanged(final ProductNodeEvent event) {
if (event.getPropertyName().equalsIgnoreCase(Product.PROPERTY_NAME_NAME)) {
final ProductNode sourceNode = event.getSourceNode();
if ((getCurrentView().isRGB() && sourceNode == getCurrentView().getProduct())
|| sourceNode == getCurrentView().getRaster()) {
updateTitle();
}
}
}
};
}
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) {
updateValues();
}
}
}
| 23,200 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductExplorerTopComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/windows/ProductExplorerTopComponent.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package org.esa.snap.rcp.windows;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.DummyProductBuilder;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.actions.file.OpenProductAction;
import org.esa.snap.rcp.nodes.ProductGroupNode;
import org.esa.snap.runtime.Config;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.explorer.ExplorerManager;
import org.openide.explorer.ExplorerUtils;
import org.openide.explorer.view.BeanTreeView;
import org.openide.nodes.Node;
import org.openide.util.NbBundle;
import org.openide.windows.IOProvider;
import org.openide.windows.InputOutput;
import org.openide.windows.TopComponent;
import javax.swing.ActionMap;
import javax.swing.text.DefaultEditorKit;
import java.awt.BorderLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Level;
/**
* The product explorer tool window.
*
* @author Norman
*/
@TopComponent.Description(
preferredID = "ProductExplorerTopComponent",
iconBase = "org/esa/snap/rcp/icons/RsProduct16.gif",
persistenceType = TopComponent.PERSISTENCE_ALWAYS
)
@TopComponent.Registration(
mode = "explorer",
openAtStartup = true,
position = 10)
@ActionID(category = "Window", id = "org.esa.snap.rcp.window.ProductExplorerTopComponent")
@ActionReference(path = "Menu/View/Tool Windows", position = 0)
@TopComponent.OpenActionRegistration(
displayName = "#CTL_ProductExplorerTopComponentName",
preferredID = "ProductExplorerTopComponent"
)
@NbBundle.Messages({
"CTL_ProductExplorerTopComponentName=Product Explorer",
"CTL_ProductExplorerTopComponentDescription=Lists all open products",
})
public class ProductExplorerTopComponent extends TopComponent implements ExplorerManager.Provider {
private final ExplorerManager explorerManager = new ExplorerManager();
private DndBeanTreeView treeView;
public ProductExplorerTopComponent() {
initComponents();
setName("Product_Explorer");
setDisplayName(Bundle.CTL_ProductExplorerTopComponentName());
setToolTipText(Bundle.CTL_ProductExplorerTopComponentDescription());
putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE);
putClientProperty(TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.TRUE);
}
private void initComponents() {
setLayout(new BorderLayout());
// 1. Add an explorer view, in this case BeanTreeView:
// DndBeanTreeView has the purpose to enable Drag&Drop an the tree
treeView = new DndBeanTreeView();
treeView.setRootVisible(false);
add(treeView, BorderLayout.CENTER);
// 2. Create a node hierarchy:
if (Config.instance().preferences().getBoolean("snap.debug.loadTestProducts", false)) {
//Product[] products = TestProducts.createProducts();
SystemUtils.LOG.info("Loading test products...");
Product[] products = DummyProductBuilder.createTestProducts();
for (Product product : products) {
SystemUtils.LOG.info("Loading test product " + product.getName());
SnapApp.getDefault().getProductManager().addProduct(product);
}
}
Node rootNode = new ProductGroupNode(SnapApp.getDefault().getProductManager());
// 3. Set the root of the node hierarchy on the ExplorerManager:
explorerManager.setRootContext(rootNode);
ActionMap map = this.getActionMap();
map.put(DefaultEditorKit.copyAction, ExplorerUtils.actionCopy(explorerManager));
map.put(DefaultEditorKit.cutAction, ExplorerUtils.actionCut(explorerManager));
map.put(DefaultEditorKit.pasteAction, ExplorerUtils.actionPaste(explorerManager));
map.put("delete", ExplorerUtils.actionDelete(explorerManager, true));
associateLookup(ExplorerUtils.createLookup(explorerManager, map));
final InputOutput io = IOProvider.getDefault().getIO("Explorer Selection", true);
explorerManager.addPropertyChangeListener(new PropertyChangeListener() {
final DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss");
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals("selectedNodes")) {
Node[] selectedNode = (Node[]) evt.getNewValue();
for (Node node : selectedNode) {
String timeText = timeFormat.format(System.currentTimeMillis());
io.getOut().println(timeText + ": " + node.getDisplayName());
}
}
}
});
}
@Override
public ExplorerManager getExplorerManager() {
return explorerManager;
}
@Override
public void componentOpened() {
// add custom code on component opening
}
@Override
public void componentClosed() {
// add custom code on component closing
}
void writeProperties(java.util.Properties p) {
// better to version settings since initial version as advocated at
// http://wiki.apidesign.org/wiki/PropertyFiles
p.setProperty("version", "1.0");
// store your settings
}
void readProperties(java.util.Properties p) {
String version = p.getProperty("version");
// read your settings according to their version
}
public boolean isNodeExpanded(Node node) {
return treeView.isExpanded(node);
}
public void expandNode(Node node) {
treeView.expandNode(node);
}
private static class DndBeanTreeView extends BeanTreeView {
public DndBeanTreeView() {
tree.setDropTarget(new DropTarget(tree, new ProductExplorerDropTarget()));
}
}
private static class ProductExplorerDropTarget extends DropTargetAdapter {
@Override
public void drop(DropTargetDropEvent dtde) {
try {
final Transferable transferable = dtde.getTransferable();
if (transferable.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) {
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
final List<File> fileList = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
if (fileList.size() > 0) {
final OpenProductAction open = new OpenProductAction();
open.setFiles(fileList.toArray(new File[fileList.size()]));
dtde.dropComplete(Boolean.TRUE.equals(open.execute()));
}
} else {
dtde.rejectDrop();
}
} catch (UnsupportedFlavorException | IOException e) {
SystemUtils.LOG.log(Level.SEVERE, "Exception during drag-and-drop operation", e);
dtde.rejectDrop();
}
}
}
}
| 7,713 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.