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
ImageViewController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/ImageViewController.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.preferences.general; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyEditorRegistry; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.esa.snap.ui.product.ProductSceneView; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import javax.swing.JComponent; import javax.swing.JPanel; import java.awt.Insets; import static com.bc.ceres.swing.TableLayout.Anchor; import static com.bc.ceres.swing.TableLayout.Fill; /** * Panel handling general layer preferences. Sub-panel of the "Layer"-panel. * * @author thomas */ @org.openide.util.NbBundle.Messages({ "Options_DisplayName_LayerGeneral=Image View", "Options_Keywords_LayerGeneral=layer, general" }) @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#Options_DisplayName_LayerGeneral", keywords = "#Options_Keywords_LayerGeneral", keywordsCategory = "Image,Layer", id = "LayerGeneral", position = 3) public final class ImageViewController extends DefaultConfigController { protected PropertySet createPropertySet() { return createPropertySet(new GeneralLayerBean()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-imageview"); } @Override protected JPanel createPanel(BindingContext context) { TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(Anchor.NORTHWEST); tableLayout.setTablePadding(4, 10); tableLayout.setTableFill(Fill.BOTH); tableLayout.setTableWeightX(1.0); tableLayout.setRowWeightY(4, 1.0); JPanel pageUI = new JPanel(tableLayout); PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance(); Property showNavigationControl = context.getPropertySet().getProperty(ProductSceneView.PREFERENCE_KEY_IMAGE_NAV_CONTROL_SHOWN); Property showScrollBars = context.getPropertySet().getProperty(ProductSceneView.PREFERENCE_KEY_IMAGE_SCROLL_BARS_SHOWN); Property reverseZoom = context.getPropertySet().getProperty(ProductSceneView.PREFERENCE_KEY_INVERT_ZOOMING); JComponent[] showNavigationControlComponents = registry.findPropertyEditor(showNavigationControl.getDescriptor()).createComponents(showNavigationControl.getDescriptor(), context); JComponent[] showScrollBarsComponents = registry.findPropertyEditor(showScrollBars.getDescriptor()).createComponents(showScrollBars.getDescriptor(), context); JComponent[] reverseZoomComponents = registry.findPropertyEditor(showScrollBars.getDescriptor()).createComponents(reverseZoom.getDescriptor(), context); tableLayout.setRowPadding(0, new Insets(10, 80, 10, 4)); pageUI.add(showNavigationControlComponents[0]); pageUI.add(showScrollBarsComponents[0]); pageUI.add(reverseZoomComponents[0]); pageUI.add(tableLayout.createVerticalSpacer()); return pageUI; } @SuppressWarnings("UnusedDeclaration") static class GeneralLayerBean { @Preference(label = "Show a navigation control widget in image views", key = ProductSceneView.PREFERENCE_KEY_IMAGE_NAV_CONTROL_SHOWN) boolean showNavigationControl = true; @Preference(label = "Show scroll bars in image views", key = ProductSceneView.PREFERENCE_KEY_IMAGE_SCROLL_BARS_SHOWN) boolean showScrollBars = false; @Preference(label = "Invert mouse wheel scrolling (zoom-in/out)", key = ProductSceneView.PREFERENCE_KEY_INVERT_ZOOMING) boolean reverseZom = false; } }
4,606
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OtherOptionsController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/OtherOptionsController.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.preferences.general; import com.bc.ceres.binding.PropertySet; import org.esa.snap.core.util.VersionChecker; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; /** * Preferences tab for handling the UI behavior preferences. Sub-level panel to the "Miscellaneous"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#AdvancedOption_DisplayName_Other", keywords = "#AdvancedOption_Keywords_Other", keywordsCategory = "General, Other", id = "Other", position = 1000) @org.openide.util.NbBundle.Messages({ "AdvancedOption_DisplayName_Other=Other", "AdvancedOption_Keywords_Other=other" }) public final class OtherOptionsController extends DefaultConfigController { @Override protected PropertySet createPropertySet() { return createPropertySet(new OtherBean()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-other"); } static class OtherBean { @Preference(label = "Release check interval", config = "snap", key = VersionChecker.PK_CHECK_INTERVAL) VersionChecker.CHECK checkInterval = VersionChecker.CHECK.WEEKLY; } }
2,144
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WriteOptionsController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/WriteOptionsController.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.preferences.general; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.Enablement; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Panel for write options. Sub-level panel to the "Miscellaneous"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#Options_DisplayName_WriteOptions", keywords = "#Options_Keywords_WriteOptions", keywordsCategory = "Write Options", id = "WriteOptions", position = 5) @org.openide.util.NbBundle.Messages({ "Options_DisplayName_WriteOptions=Write Options", "Options_Keywords_WriteOptions=write, writing, save, header, MPH, SPH, history, annotation, incremental, caching" }) public final class WriteOptionsController extends DefaultConfigController { /** * Preferences key for save product headers (MPH, SPH) or not */ public static final String PREFERENCE_KEY_SAVE_PRODUCT_HEADERS = "save.product.headers"; /** * Preferences key for save product history or not */ public static final String PREFERENCE_KEY_SAVE_PRODUCT_HISTORY = "save.product.history"; /** * Preferences key for save product annotations (ADS) or not */ public static final String PREFERENCE_KEY_SAVE_PRODUCT_ANNOTATIONS = "save.product.annotations"; /** * Preferences key for incremental mode at save */ public static final String PREFERENCE_KEY_SAVE_INCREMENTAL = "save.incremental"; /** * Preferences key to switch dimap product writer caching */ public static final String PREFERENCE_KEY_DIMAP_WRITE_CACHE = "snap.dataio.writer.dimap.useCache"; /** * default value for preference save product headers (MPH, SPH) or not */ public static final boolean DEFAULT_VALUE_SAVE_PRODUCT_HEADERS = true; /** * default value for preference save product history (History) or not */ public static final boolean DEFAULT_VALUE_SAVE_PRODUCT_HISTORY = true; /** * default value for preference save product annotations (ADS) or not */ public static final boolean DEFAULT_VALUE_SAVE_PRODUCT_ANNOTATIONS = false; /** * default value for preference incremental mode at save */ public static final boolean DEFAULT_VALUE_SAVE_INCREMENTAL = true; /** * default value for preference for dimap caching */ public static final boolean DEFAULT_VALUE_DIMAP_WRITE_CACHE = true; protected PropertySet createPropertySet() { return createPropertySet(new WriteOptionsBean()); } @Override protected void configure(BindingContext context) { Enablement enablement = context.bindEnabledState(PREFERENCE_KEY_SAVE_PRODUCT_ANNOTATIONS, false, new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { return !((Boolean) bindingContext.getPropertySet().getProperty(PREFERENCE_KEY_SAVE_PRODUCT_HEADERS).getValue()); } }); context.getPropertySet().getProperty(PREFERENCE_KEY_SAVE_PRODUCT_HEADERS).addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { enablement.apply(); if (!((Boolean) evt.getNewValue())) { try { context.getPropertySet().getProperty(PREFERENCE_KEY_SAVE_PRODUCT_ANNOTATIONS).setValue(false); } catch (ValidationException e) { e.printStackTrace(); // very basic exception handling because exception is not expected to be thrown } } } }); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-write"); } @SuppressWarnings("UnusedDeclaration") static class WriteOptionsBean { @Preference(label = "Save product header (MPH, SPH, Global_Attributes)", key = PREFERENCE_KEY_SAVE_PRODUCT_HEADERS) boolean saveProductHeaders = DEFAULT_VALUE_SAVE_PRODUCT_HEADERS; @Preference(label = "Save product history (History)", key = PREFERENCE_KEY_SAVE_PRODUCT_HISTORY) boolean saveProductHistory = DEFAULT_VALUE_SAVE_PRODUCT_HISTORY; @Preference(label = "Save product annotation datasets (ADS)", key = PREFERENCE_KEY_SAVE_PRODUCT_ANNOTATIONS) boolean saveProductAds = DEFAULT_VALUE_SAVE_PRODUCT_ANNOTATIONS; @Preference(label = "Use incremental save (only save modified items)", key = PREFERENCE_KEY_SAVE_INCREMENTAL) boolean saveIncremental = DEFAULT_VALUE_SAVE_INCREMENTAL; @Preference(config = "snap", label = "Enable DIMAP write cache", key = PREFERENCE_KEY_DIMAP_WRITE_CACHE) boolean useDimapCache = DEFAULT_VALUE_DIMAP_WRITE_CACHE; @Preference(config = "snap", label = "Write raster data concurrently", key = ProductIO.SYSTEM_PROPERTY_CONCURRENT) boolean writeConcurrent = ProductIO.DEFAULT_WRITE_RASTER_CONCURRENT; } }
6,208
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GeoLocationController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/GeoLocationController.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.preferences.general; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyEditorRegistry; import org.esa.snap.core.dataio.geocoding.util.XYInterpolator; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.esa.snap.rcp.preferences.PreferenceUtils; import org.esa.snap.ui.GridBagUtils; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import javax.swing.JComponent; import javax.swing.JPanel; import java.awt.GridBagConstraints; import java.awt.Insets; import static com.bc.ceres.swing.TableLayout.Anchor; import static com.bc.ceres.swing.TableLayout.Fill; import static org.esa.snap.core.dataio.geocoding.util.XYInterpolator.SYSPROP_GEOCODING_INTERPOLATOR; import static org.esa.snap.rcp.pixelinfo.PixelInfoView.PREFERENCE_DEFAULT_SHOW_GEO_POS_DECIMALS; import static org.esa.snap.rcp.pixelinfo.PixelInfoView.PREFERENCE_DEFAULT_SHOW_PIXEL_POS_DECIMALS; import static org.esa.snap.rcp.pixelinfo.PixelInfoView.PREFERENCE_DEFAULT_SHOW_PIXEL_POS_OFFSET_1; import static org.esa.snap.rcp.pixelinfo.PixelInfoView.PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS; import static org.esa.snap.rcp.pixelinfo.PixelInfoView.PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS; import static org.esa.snap.rcp.pixelinfo.PixelInfoView.PREFERENCE_KEY_SHOW_PIXEL_POS_OFFSET_ONE; /** * The preferences panel handling geo-location details. Sub-level panel to the "Miscellaneous"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#TXT_GeoLocationController_DisplayName", keywords = "#TXT_GeoLocationController_Keyword", keywordsCategory = "Pixel Display, Geolocation", id = "GeolocationController", position = 2) @NbBundle.Messages({ "TXT_GeoLocationController_DisplayName=Geo-Location", "TXT_GeoLocationController_Keyword=geo, location, geo-location, compatibility, differ" }) public final class GeoLocationController extends DefaultConfigController { private static final String PREFERENCE_KEY_ADJUST_PIN_GEO_POS = Placemark.PREFERENCE_KEY_ADJUST_PIN_GEO_POS; private static final String PREFERENCE_KEY_PIXEL_GEO_CODING_FRACTION_ACCURACY = "snap.pixelGeoCoding.fractionAccuracy"; private static final String PREFERENCE_KEY_TIE_POINT_INVERSE_HIGH_PRECISION = "snap.tiePointGeoCoding.maxPrecision"; protected PropertySet createPropertySet() { return createPropertySet(new GeoLocationBean()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-geolocation"); } @Override protected JPanel createPanel(BindingContext context) { final PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance(); final PropertySet propertySet = context.getPropertySet(); final Property snapToExactGeolocationProperty = propertySet.getProperty(PREFERENCE_KEY_ADJUST_PIN_GEO_POS); final Property pixelGeocodingFractionAccuracyProperty = propertySet.getProperty(PREFERENCE_KEY_PIXEL_GEO_CODING_FRACTION_ACCURACY); final Property pixelGeoCodingFractionInterpolatorProperty = propertySet.getProperty(SYSPROP_GEOCODING_INTERPOLATOR); final Property tiePointInverseHighPrecisionProperty = propertySet.getProperty(PREFERENCE_KEY_TIE_POINT_INVERSE_HIGH_PRECISION); final Property showGeoPosAsDecimals = propertySet.getProperty(PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS); final Property showPixelPosAsDecimals = propertySet.getProperty(PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS); final Property showPixelPosOffset = propertySet.getProperty(PREFERENCE_KEY_SHOW_PIXEL_POS_OFFSET_ONE); PropertyDescriptor descriptor = snapToExactGeolocationProperty.getDescriptor(); final JComponent[] snapToExactGeolocationComponents = registry.findPropertyEditor(descriptor).createComponents(descriptor, context); descriptor = pixelGeocodingFractionAccuracyProperty.getDescriptor(); final JComponent[] pixelGeocodingfractionAccuracyComponents = registry.findPropertyEditor(descriptor).createComponents(descriptor, context); descriptor = pixelGeoCodingFractionInterpolatorProperty.getDescriptor(); final JComponent[] pixelGeocodingFractionInterpolatorComponents = registry.findPropertyEditor(descriptor).createComponents(descriptor, context); descriptor = tiePointInverseHighPrecisionProperty.getDescriptor(); JComponent[] tiePointInverseHighPrecisionComponents = registry.findPropertyEditor(descriptor).createComponents(descriptor, context); descriptor = showGeoPosAsDecimals.getDescriptor(); JComponent[] showGeoPosAsDecimalsComponents = registry.findPropertyEditor(descriptor).createComponents(descriptor, context); descriptor = showPixelPosAsDecimals.getDescriptor(); JComponent[] showPixelPosAsDecimalsComponents = registry.findPropertyEditor(descriptor).createComponents(descriptor, context); descriptor = showPixelPosOffset.getDescriptor(); JComponent[] showPixelPosOffsetComponents = registry.findPropertyEditor(descriptor).createComponents(descriptor, context); TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(Anchor.NORTHWEST); tableLayout.setTablePadding(new Insets(4, 10, 0, 0)); tableLayout.setTableFill(Fill.BOTH); tableLayout.setTableWeightX(1.0); tableLayout.setTableWeightY(0.0); tableLayout.setRowWeightY(8, 1.0); final JPanel pageUI = new JPanel(tableLayout); pageUI.add(PreferenceUtils.createTitleLabel("General Settings")); pageUI.add(snapToExactGeolocationComponents[0]); pageUI.add(pixelGeocodingfractionAccuracyComponents[0]); pageUI.add(pixelGeocodingFractionInterpolatorComponents[1]); pageUI.add(pixelGeocodingFractionInterpolatorComponents[0]); pageUI.add(tiePointInverseHighPrecisionComponents[0]); tableLayout.createHorizontalSpacer(); pageUI.add(PreferenceUtils.createTitleLabel("Display Settings")); pageUI.add(showGeoPosAsDecimalsComponents[0]); pageUI.add(showPixelPosAsDecimalsComponents[0]); pageUI.add(showPixelPosOffsetComponents[0]); pageUI.add(tableLayout.createVerticalSpacer()); return createPageUIContentPane(pageUI); } private static JPanel createPageUIContentPane(JPanel pane) { JPanel contentPane = GridBagUtils.createPanel(); final GridBagConstraints gbc = GridBagUtils.createConstraints("fill=HORIZONTAL,anchor=NORTHWEST"); gbc.insets.top = 15; gbc.weightx = 1; gbc.weighty = 0; contentPane.add(pane, gbc); GridBagUtils.addVerticalFiller(contentPane, gbc); return contentPane; } static class GeoLocationBean { @Preference(label = "Use sub-pixel fraction accuracy for pixel-based geo-coding", key = PREFERENCE_KEY_PIXEL_GEO_CODING_FRACTION_ACCURACY, config = "snap") boolean getPixelPosWithFractionAccuracy = false; @Preference(label = "Select interpolation method for sub-pixel fraction accuracy for pixel-based geo-coding", key = SYSPROP_GEOCODING_INTERPOLATOR, config = "snap") XYInterpolator.Type geodeticInterpolator = XYInterpolator.Type.EUCLIDIAN; @Preference(label = "Use high precision approximations for inverse tie point geo-coding", key = PREFERENCE_KEY_TIE_POINT_INVERSE_HIGH_PRECISION, config = "snap") boolean getTiePointInverseHighPrecision = false; @Preference(label = "Snap pins to exact geo-location after import, transfer to another product, or geo-coding change", key = PREFERENCE_KEY_ADJUST_PIN_GEO_POS, config = "snap") boolean snapToExactGeoLocation = true; @Preference(label = "Show geographical coordinates in decimal degrees", key = PREFERENCE_KEY_SHOW_GEO_POS_DECIMALS) boolean showGeoPosAsDecimals = PREFERENCE_DEFAULT_SHOW_GEO_POS_DECIMALS; @Preference(label = "Show pixel coordinates with fractional part", key = PREFERENCE_KEY_SHOW_PIXEL_POS_DECIMALS) boolean showPixelPosAsDecimals = PREFERENCE_DEFAULT_SHOW_PIXEL_POS_DECIMALS; @Preference(label = "Show pixel coordinates starting at (1,1)", key = PREFERENCE_KEY_SHOW_PIXEL_POS_OFFSET_ONE, description = "Show pixel coordinates so that the upper left image corner is (1,1), instead of (0,0).") boolean showPixelPosWithOffset1 = PREFERENCE_DEFAULT_SHOW_PIXEL_POS_OFFSET_1; } }
9,639
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
NoDataLayerController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/layer/NoDataLayerController.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.preferences.layer; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyEditorRegistry; import org.esa.snap.core.layer.NoDataLayerType; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.esa.snap.rcp.preferences.PreferenceUtils; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Insets; /** * Panel handling no-data layer preferences. Sub-panel of the "Layer"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "LayerPreferences", displayName = "#Options_DisplayName_LayerNoData", keywords = "#Options_Keywords_LayerNoData", keywordsCategory = "Layer", id = "LayerNoData") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_LayerNoData=No-Data Layer", "Options_Keywords_LayerNoData=layer, no-data" }) public final class NoDataLayerController extends DefaultConfigController { /** * Preferences key for the no-data overlay color */ public static final String PROPERTY_KEY_NO_DATA_OVERLAY_COLOR = "noDataOverlay.color"; /** * Preferences key for the no-data overlay transparency */ public static final String PROPERTY_KEY_NO_DATA_OVERLAY_TRANSPARENCY = "noDataOverlay.transparency"; protected PropertySet createPropertySet() { return createPropertySet(new NoDataBean()); } @Override protected JPanel createPanel(BindingContext context) { TableLayout tableLayout = new TableLayout(2); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTablePadding(new Insets(4, 10, 0, 0)); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setColumnWeightX(1, 1.0); JPanel pageUI = new JPanel(tableLayout); PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance(); Property noDataOverlayColor = context.getPropertySet().getProperty(PROPERTY_KEY_NO_DATA_OVERLAY_COLOR); Property noDataOverlayTransparency = context.getPropertySet().getProperty(PROPERTY_KEY_NO_DATA_OVERLAY_TRANSPARENCY); JComponent[] noDataOverlayColorComponents = PreferenceUtils.createColorComponents(noDataOverlayColor); JComponent[] noDataOverlayTransparencyComponents = registry.findPropertyEditor(noDataOverlayTransparency.getDescriptor()).createComponents(noDataOverlayTransparency.getDescriptor(), context); pageUI.add(noDataOverlayColorComponents[0]); pageUI.add(noDataOverlayColorComponents[1]); pageUI.add(noDataOverlayTransparencyComponents[1]); pageUI.add(noDataOverlayTransparencyComponents[0]); pageUI.add(tableLayout.createVerticalSpacer()); JPanel parent = new JPanel(new BorderLayout()); parent.add(pageUI, BorderLayout.CENTER); parent.add(Box.createHorizontalStrut(100), BorderLayout.EAST); return parent; } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-nodatalayer"); } @SuppressWarnings("UnusedDeclaration") static class NoDataBean { @Preference(label = "No-data overlay colour", key = PROPERTY_KEY_NO_DATA_OVERLAY_COLOR) Color noDataOverlayColor = NoDataLayerType.DEFAULT_COLOR; @Preference(label = "No-data overlay transparency", key = PROPERTY_KEY_NO_DATA_OVERLAY_TRANSPARENCY, interval = "[0.0,1.0]") double noDataOverlayTransparency = 0.3; } }
4,593
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
package-info.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/layer/package-info.java
/** * This package contains the layer preferences handling. * * @author thomas */ @OptionsPanelController.ContainerRegistration( id = "LayerPreferences", categoryName = "#OptionsCategory_Name_Layer", iconBase = "org/esa/snap/rcp/icons/Layers_32x32.png", keywords = "#OptionsCategory_Keywords_Layers", keywordsCategory = "#OptionsCategory_Keywords_Layer_Prefs", position = 2) @org.openide.util.NbBundle.Messages({ "OptionsCategory_Name_Layer=Layer", "OptionsCategory_Keywords_Layers=layer, application, platform", "OptionsCategory_Keywords_Layer_Prefs=layer" }) package org.esa.snap.rcp.preferences.layer; import org.netbeans.spi.options.OptionsPanelController;
737
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraticuleLayerController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/layer/GraticuleLayerController.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.preferences.layer; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.Enablement; import com.bc.ceres.swing.binding.PropertyEditorRegistry; import com.bc.ceres.swing.binding.PropertyPane; import org.esa.snap.core.layer.GraticuleLayerType; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import javax.swing.*; import java.awt.*; /** * * Panel handling graticule layer preferences. Sub-panel of the "Layer"-panel. * * @author thomas * @author Daniel Knowles */ //JAN2018 - Daniel Knowles - updated with SeaDAS gridline revisions @OptionsPanelController.SubRegistration(location = "LayerPreferences", displayName = "#Options_DisplayName_LayerGraticule", keywords = "#Options_Keywords_LayerGraticule", keywordsCategory = "Layer", id = "LayerGraticule") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_LayerGraticule=Graticule Layer", "Options_Keywords_LayerGraticule=layer, graticule" }) public final class GraticuleLayerController extends DefaultConfigController { Property restoreDefaults; Enablement enablementGridlinesWidth; Enablement enablementGridlinesDashedPhase; Enablement enablementGridlinesTransparency; Enablement enablementGridlinesColor; Enablement enablementTickmarksInside; Enablement enablementTickmarksLength; Enablement enablementTickmarksColor; Enablement enablementBorderWidth; Enablement enablementBorderColor; boolean propertyValueChangeEventsEnabled = true; protected PropertySet createPropertySet() { return createPropertySet(new GraticuleBean()); } @Override protected JPanel createPanel(BindingContext context) { // // Initialize the default value contained within each property descriptor // This is done so subsequently the restoreDefaults actions can be performed // initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_NAME, true); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_NAME, GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRID_SPACING_LON_NAME, GraticuleLayerType.PROPERTY_GRID_SPACING_LON_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_SECTION_NAME, true); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_NORTH_NAME, GraticuleLayerType.PROPERTY_LABELS_NORTH_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_SOUTH_NAME, GraticuleLayerType.PROPERTY_LABELS_SOUTH_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_WEST_NAME, GraticuleLayerType.PROPERTY_LABELS_WEST_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_EAST_NAME, GraticuleLayerType.PROPERTY_LABELS_EAST_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_NAME, GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_NAME, GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, GraticuleLayerType.PROPERTY_LABELS_INSIDE_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_ITALIC_NAME, GraticuleLayerType.PROPERTY_LABELS_ITALIC_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_BOLD_NAME, GraticuleLayerType.PROPERTY_LABELS_BOLD_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_FONT_NAME, GraticuleLayerType.PROPERTY_LABELS_FONT_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_NAME, GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_NAME, GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_SIZE_NAME, GraticuleLayerType.PROPERTY_LABELS_SIZE_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_LABELS_COLOR_NAME, GraticuleLayerType.PROPERTY_LABELS_COLOR_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_NAME, true); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_NAME, GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_NAME, GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_NAME, GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_NAME, GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_BORDER_SECTION_NAME, true); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME, GraticuleLayerType.PROPERTY_BORDER_SHOW_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_BORDER_WIDTH_NAME, GraticuleLayerType.PROPERTY_BORDER_WIDTH_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_BORDER_COLOR_NAME, GraticuleLayerType.PROPERTY_BORDER_COLOR_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_TICKMARKS_SECTION_NAME, true); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_NAME, GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_NAME, GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_NAME, GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_NAME, true); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_NAME, GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_NAME, GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_NAME, GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_NAME, GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_NAME, true); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_NAME, GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_DEFAULT); initPropertyDefaults(context, GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_NAME, GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_DEFAULT); restoreDefaults = initPropertyDefaults(context, GraticuleLayerType.PROPERTY_RESTORE_DEFAULTS_NAME, GraticuleLayerType.PROPERTY_RESTORE_TO_DEFAULTS_DEFAULT); // // Create UI // TableLayout tableLayout = new TableLayout(2); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTablePadding(new Insets(4, 10, 0, 0)); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setColumnWeightX(1, 1.0); JPanel pageUI = new JPanel(tableLayout); PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance(); PropertySet propertyContainer = context.getPropertySet(); Property[] properties = propertyContainer.getProperties(); int currRow = 0; for (Property property : properties) { PropertyDescriptor descriptor = property.getDescriptor(); PropertyPane.addComponent(currRow, tableLayout, pageUI, context, registry, descriptor); currRow++; } pageUI.add(tableLayout.createVerticalSpacer()); JPanel parent = new JPanel(new BorderLayout()); parent.add(pageUI, BorderLayout.CENTER); parent.add(Box.createHorizontalStrut(50), BorderLayout.EAST); return parent; } @Override protected void configure(BindingContext context) { configureGridlinesEnablement(context); configureTickmarksEnablement(context); configureBorderEnablement(context); // Handle resetDefaults events - set all other components to defaults restoreDefaults.addPropertyChangeListener(evt -> { handleRestoreDefaults(context); }); // Add listeners to all components in order to uncheck restoreDefaults checkbox accordingly PropertySet propertyContainer = context.getPropertySet(); Property[] properties = propertyContainer.getProperties(); for (Property property : properties) { if (property != restoreDefaults) { property.addPropertyChangeListener(evt -> { handlePreferencesPropertyValueChange(context); }); } } } /** * Test all properties to determine whether the current value is the default value * * @param context * @return * @author Daniel Knowles */ private boolean isDefaults(BindingContext context) { PropertySet propertyContainer = context.getPropertySet(); Property[] properties = propertyContainer.getProperties(); for (Property property : properties) { if (property != restoreDefaults && property.getDescriptor().getDefaultValue() != null) if (!property.getValue().equals(property.getDescriptor().getDefaultValue())) { return false; } } return true; } /** * Handles the restore defaults action * * @param context * @author Daniel Knowles */ private void handleRestoreDefaults(BindingContext context) { if (propertyValueChangeEventsEnabled) { propertyValueChangeEventsEnabled = false; try { if (restoreDefaults.getValue()) { PropertySet propertyContainer = context.getPropertySet(); Property[] properties = propertyContainer.getProperties(); for (Property property : properties) { if (property != restoreDefaults && property.getDescriptor().getDefaultValue() != null) property.setValue(property.getDescriptor().getDefaultValue()); } } } catch (ValidationException e) { e.printStackTrace(); } propertyValueChangeEventsEnabled = true; context.setComponentsEnabled(GraticuleLayerType.PROPERTY_RESTORE_DEFAULTS_NAME, false); } } /** * Configure enablement of the tickmarks components * * @param context * @author Daniel Knowles */ private void configureTickmarksEnablement(BindingContext context) { enablementTickmarksInside = context.bindEnabledState(GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_NAME, true, GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, true); enablementTickmarksLength = context.bindEnabledState(GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_NAME, true, GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, true); enablementTickmarksColor = context.bindEnabledState(GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_NAME, true, GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, true); // handle it the first time so bound properties get properly enabled handleTickmarksEnablement(); } /** * Handles enablement of the tickmarks components * * @author Daniel Knowles */ private void handleTickmarksEnablement() { enablementTickmarksInside.apply(); enablementTickmarksLength.apply(); enablementTickmarksColor.apply(); } /** * Configure enablement of the gridlines components * * @param context * @author Daniel Knowles */ private void configureGridlinesEnablement(BindingContext context) { enablementGridlinesWidth = context.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_NAME, true, GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, true); enablementGridlinesDashedPhase = context.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_NAME, true, GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, true); enablementGridlinesTransparency = context.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_NAME, true, GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, true); enablementGridlinesColor = context.bindEnabledState(GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_NAME, true, GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, true); // handle it the first time so bound properties get properly enabled handleGridlinesEnablement(); } /** * Handles enablement of the gridlines components * * @author Daniel Knowles */ private void handleGridlinesEnablement() { enablementGridlinesWidth.apply(); enablementGridlinesDashedPhase.apply(); enablementGridlinesTransparency.apply(); enablementGridlinesColor.apply(); } /** * Configure enablement of the border components * * @param context * @author Daniel Knowles */ private void configureBorderEnablement(BindingContext context) { enablementBorderWidth = context.bindEnabledState(GraticuleLayerType.PROPERTY_BORDER_WIDTH_NAME, true, GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME, true); enablementBorderColor = context.bindEnabledState(GraticuleLayerType.PROPERTY_BORDER_COLOR_NAME, true, GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME, true); // handle it the first time so bound properties get properly enabled handleBorderEnablement(); } /** * Handles enablement of the gridlines components * * @author Daniel Knowles */ private void handleBorderEnablement() { enablementBorderWidth.apply(); enablementBorderColor.apply(); enablementGridlinesTransparency.apply(); enablementGridlinesColor.apply(); } /** * Set restoreDefault component because a property has changed * @param context * @author Daniel Knowles */ private void handlePreferencesPropertyValueChange(BindingContext context) { if (propertyValueChangeEventsEnabled) { propertyValueChangeEventsEnabled = false; try { restoreDefaults.setValue(isDefaults(context)); context.setComponentsEnabled(GraticuleLayerType.PROPERTY_RESTORE_DEFAULTS_NAME, !isDefaults(context)); } catch (ValidationException e) { e.printStackTrace(); } propertyValueChangeEventsEnabled = true; } } /** * Initialize the property descriptor default value * * @param context * @param propertyName * @param propertyDefault * @return * @author Daniel Knowles */ private Property initPropertyDefaults(BindingContext context, String propertyName, Object propertyDefault) { Property property = context.getPropertySet().getProperty(propertyName); property.getDescriptor().setDefaultValue(propertyDefault); return property; } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-graticulelayer"); } @SuppressWarnings("UnusedDeclaration") static class GraticuleBean { // Grid Spacing Section @Preference(label = GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_LABEL, key = GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_NAME, description = GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_TOOLTIP) boolean gridSpacingSection = true; @Preference(label = GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_LABEL, key = GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_NAME, description = GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_TOOLTIP, interval = "[0.00,90.0]") double gridSpacingLat = GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_GRID_SPACING_LON_LABEL, key = GraticuleLayerType.PROPERTY_GRID_SPACING_LON_NAME, description = GraticuleLayerType.PROPERTY_GRID_SPACING_LON_TOOLTIP, interval = "[0.00,90.0]") double gridSpacingLon = GraticuleLayerType.PROPERTY_GRID_SPACING_LON_DEFAULT; // Labels Section @Preference(label = GraticuleLayerType.PROPERTY_LABELS_SECTION_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_SECTION_NAME, description = GraticuleLayerType.PROPERTY_LABELS_SECTION_TOOLTIP) boolean labelsSection = true; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_NORTH_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_NORTH_NAME, description = GraticuleLayerType.PROPERTY_LABELS_NORTH_TOOLTIP) boolean labelsNorth = GraticuleLayerType.PROPERTY_LABELS_NORTH_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_SOUTH_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_SOUTH_NAME, description = GraticuleLayerType.PROPERTY_LABELS_SOUTH_TOOLTIP) boolean labelsSouth = GraticuleLayerType.PROPERTY_LABELS_SOUTH_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_WEST_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_WEST_NAME, description = GraticuleLayerType.PROPERTY_LABELS_WEST_TOOLTIP) boolean labelsWest = GraticuleLayerType.PROPERTY_LABELS_WEST_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_EAST_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_EAST_NAME, description = GraticuleLayerType.PROPERTY_LABELS_EAST_TOOLTIP) boolean labelsEast = GraticuleLayerType.PROPERTY_LABELS_EAST_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_NAME, description = GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_TOOLTIP) boolean labelsSuffix = GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_NAME, description = GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_TOOLTIP) boolean labelsDecimal = GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_INSIDE_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME, description = GraticuleLayerType.PROPERTY_LABELS_INSIDE_TOOLTIP) boolean labelsInside = GraticuleLayerType.PROPERTY_LABELS_INSIDE_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_ITALIC_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_ITALIC_NAME, description = GraticuleLayerType.PROPERTY_LABELS_ITALIC_TOOLTIP) boolean labelsItalic = GraticuleLayerType.PROPERTY_LABELS_ITALIC_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_BOLD_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_BOLD_NAME, description = GraticuleLayerType.PROPERTY_LABELS_BOLD_TOOLTIP) boolean labelsBold = GraticuleLayerType.PROPERTY_LABELS_BOLD_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_FONT_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_FONT_NAME, description = GraticuleLayerType.PROPERTY_LABELS_FONT_TOOLTIP, valueSet = {GraticuleLayerType.PROPERTY_LABELS_FONT_VALUE_1, GraticuleLayerType.PROPERTY_LABELS_FONT_VALUE_2, GraticuleLayerType.PROPERTY_LABELS_FONT_VALUE_3, GraticuleLayerType.PROPERTY_LABELS_FONT_VALUE_4}) String labelsFont = GraticuleLayerType.PROPERTY_LABELS_FONT_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_NAME, description = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_TOOLTIP, interval = "[0.00,90.0]") double labelsRotationLon = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_NAME, description = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_TOOLTIP, interval = "[0.00,90.0]") double labelsRotationLat = GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_SIZE_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_SIZE_NAME, description = GraticuleLayerType.PROPERTY_LABELS_SIZE_TOOLTIP, interval = GraticuleLayerType.PROPERTY_LABELS_SIZE_INTERVAL) int labelsSize = GraticuleLayerType.PROPERTY_LABELS_SIZE_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_LABELS_COLOR_LABEL, key = GraticuleLayerType.PROPERTY_LABELS_COLOR_NAME, description = GraticuleLayerType.PROPERTY_LABELS_COLOR_TOOLTIP) Color labelsColor = GraticuleLayerType.PROPERTY_LABELS_COLOR_DEFAULT; // Gridlines Section @Preference(label = GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_LABEL, key = GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_NAME, description = GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_TOOLTIP) boolean gridlinesSection = true; @Preference(label = GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_LABEL, key = GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME, description = GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_TOOLTIP) boolean gridlinesShow = GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_LABEL, key = GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_NAME, description = GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_TOOLTIP) double gridlinesWidth = GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_LABEL, key = GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_NAME, description = GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_TOOLTIP) double gridlinesDashed = GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_LABEL, key = GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_NAME, description = GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_TOOLTIP, interval = "[0.0,1.0]") double gridlinesTransparency = GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_LABEL, key = GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_NAME, description = GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_TOOLTIP) Color gridlinesColor = GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_DEFAULT; // Border Section @Preference(label = GraticuleLayerType.PROPERTY_BORDER_SECTION_LABEL, key = GraticuleLayerType.PROPERTY_BORDER_SECTION_NAME, description = GraticuleLayerType.PROPERTY_BORDER_SECTION_TOOLTIP) boolean borderSection = true; @Preference(label = GraticuleLayerType.PROPERTY_BORDER_SHOW_LABEL, key = GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME, description = GraticuleLayerType.PROPERTY_BORDER_SHOW_TOOLTIP) boolean borderShow = GraticuleLayerType.PROPERTY_BORDER_SHOW_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_BORDER_WIDTH_LABEL, key = GraticuleLayerType.PROPERTY_BORDER_WIDTH_NAME, description = GraticuleLayerType.PROPERTY_BORDER_WIDTH_TOOLTIP) double borderWidth = GraticuleLayerType.PROPERTY_BORDER_WIDTH_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_BORDER_COLOR_LABEL, key = GraticuleLayerType.PROPERTY_BORDER_COLOR_NAME, description = GraticuleLayerType.PROPERTY_BORDER_COLOR_TOOLTIP) Color borderColor = GraticuleLayerType.PROPERTY_BORDER_COLOR_DEFAULT; // Tickmarks Section @Preference(label = GraticuleLayerType.PROPERTY_TICKMARKS_SECTION_LABEL, key = GraticuleLayerType.PROPERTY_TICKMARKS_SECTION_NAME, description = GraticuleLayerType.PROPERTY_TICKMARKS_SECTION_TOOLTIP) boolean tickmarksSection = true; @Preference(label = GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_LABEL, key = GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME, description = GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_TOOLTIP) boolean tickmarksShow = GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_LABEL, key = GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_NAME, description = GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_TOOLTIP) boolean tickmarkInside = GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_LABEL, key = GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_NAME, description = GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_TOOLTIP) double tickmarksLength = GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_LABEL, key = GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_NAME, description = GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_TOOLTIP) Color tickmarksColor = GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_DEFAULT; // Corner Labels Section @Preference(label = GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_LABEL, key = GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_NAME, description = GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_TOOLTIP) boolean cornerLabelsSection = true; @Preference(label = GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_LABEL, key = GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_NAME, description = GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_TOOLTIP) boolean cornerLabelsNorth = GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_LABEL, key = GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_NAME, description = GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_TOOLTIP) boolean cornerLabelsSouth = GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_LABEL, key = GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_NAME, description = GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_TOOLTIP) boolean cornerLabelsWest = GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_LABEL, key = GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_NAME, description = GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_TOOLTIP) boolean cornerLabelsEast = GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_DEFAULT; // Inside Labels Section @Preference(label = GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_LABEL, key = GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_NAME, description = GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_TOOLTIP) boolean insideLabelsSection = true; @Preference(label = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_LABEL, key = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_NAME, description = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_TOOLTIP, interval = "[0.0,1.0]") double insideLabelsBgTransparency = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_DEFAULT; @Preference(label = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_LABEL, key = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_NAME, description = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_TOOLTIP) Color insideLabelsBgColor = GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_DEFAULT; // Restore Defaults Section @Preference(label = GraticuleLayerType.PROPERTY_RESTORE_TO_DEFAULTS_LABEL, key = GraticuleLayerType.PROPERTY_RESTORE_DEFAULTS_NAME, description = GraticuleLayerType.PROPERTY_RESTORE_TO_DEFAULTS_TOOLTIP) boolean restoreDefaults = GraticuleLayerType.PROPERTY_RESTORE_TO_DEFAULTS_DEFAULT; } }
31,784
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WorldMapLayerController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/layer/WorldMapLayerController.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.preferences.layer; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.layer.WorldMapLayerType; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import javax.swing.Box; import javax.swing.DefaultComboBoxModel; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Insets; import java.util.ArrayList; import java.util.List; /** * Panel handling world map layer preferences. Sub-panel of the "Layer"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "LayerPreferences", displayName = "#Options_DisplayName_LayerWorldMap", keywords = "#Options_Keywords_LayerWorldMap", keywordsCategory = "Layer", id = "LayerWorldMap") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_LayerWorldMap=World Map Layer", "Options_Keywords_LayerWorldMap=layer, worldmap" }) public final class WorldMapLayerController extends DefaultConfigController { /** * Preferences key for the world map type */ public static final String PROPERTY_KEY_WORLDMAP_TYPE = "worldmap.type"; protected PropertySet createPropertySet() { return createPropertySet(new WorldMapBean()); } @Override protected JPanel createPanel(BindingContext context) { List<WorldMapLayerType> worldMapLayerTypes = new ArrayList<>(); for (LayerType layerType : LayerTypeRegistry.getLayerTypes()) { if (layerType instanceof WorldMapLayerType) { WorldMapLayerType worldMapLayerType = (WorldMapLayerType) layerType; worldMapLayerTypes.add(worldMapLayerType); } } TableLayout tableLayout = new TableLayout(2); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTablePadding(new Insets(4, 10, 0, 0)); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setColumnWeightX(1, 1.0); JPanel pageUI = new JPanel(tableLayout); Property property = context.getPropertySet().getProperty(PROPERTY_KEY_WORLDMAP_TYPE); JComboBox<WorldMapLayerType> box = new JComboBox<>(); box.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { Component rendererComponent = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof WorldMapLayerType && rendererComponent instanceof JLabel) { WorldMapLayerType worldMapLayerType = (WorldMapLayerType) value; JLabel label = (JLabel) rendererComponent; label.setText(worldMapLayerType.getLabel()); } return rendererComponent; } }); box.addActionListener(e -> { try { property.setValue(box.getSelectedItem().toString()); } catch (ValidationException e1) { e1.printStackTrace(); // very basic exception handling because exception is not expected to be thrown } }); DefaultComboBoxModel<WorldMapLayerType> model = new DefaultComboBoxModel<>(worldMapLayerTypes.toArray(new WorldMapLayerType[worldMapLayerTypes.size()])); box.setModel(model); for (WorldMapLayerType layerType : worldMapLayerTypes) { if (layerType.getName().equals(property.getValue())) { box.setSelectedItem(layerType); } } pageUI.add(new JLabel(property.getDescriptor().getDisplayName() + ":")); pageUI.add(box); pageUI.add(tableLayout.createVerticalSpacer()); JPanel parent = new JPanel(new BorderLayout()); parent.add(pageUI, BorderLayout.CENTER); parent.add(Box.createHorizontalStrut(100), BorderLayout.EAST); return parent; } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-worldmaplayer"); } @SuppressWarnings("UnusedDeclaration") static class WorldMapBean { @Preference(label = "World Map Layer", key = PROPERTY_KEY_WORLDMAP_TYPE) String worldMapLayerType = "BlueMarbleLayerType"; } }
5,744
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageLayerController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/layer/ImageLayerController.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.preferences.layer; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.Enablement; import com.bc.ceres.swing.binding.PropertyEditorRegistry; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.rcp.preferences.Preference; import org.esa.snap.rcp.preferences.PreferenceUtils; import org.esa.snap.ui.product.ProductSceneView; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import javax.swing.Box; import javax.swing.JComponent; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Insets; /** * * Panel handling image layer preferences. Sub-panel of the "Layer"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "LayerPreferences", displayName = "#Options_DisplayName_LayerImage", keywords = "#Options_Keywords_LayerImage", keywordsCategory = "Layer", id = "LayerImage") @org.openide.util.NbBundle.Messages({ "Options_DisplayName_LayerImage=Image Layer", "Options_Keywords_LayerImage=layer, image" }) public final class ImageLayerController extends DefaultConfigController { /** * Preferences key for the background color */ public static final String PROPERTY_KEY_IMAGE_BG_COLOR = "image.background.color"; /** * Preferences key for showing image border */ public static final String PROPERTY_KEY_IMAGE_BORDER_SHOWN = "image.border.shown"; /** * Preferences key for image border size */ public static final String PROPERTY_KEY_IMAGE_BORDER_SIZE = "image.border.size"; /** * Preferences key for image border color */ public static final String PROPERTY_KEY_IMAGE_BORDER_COLOR = "image.border.color"; /** * Preferences key for showing pixel image border */ public static final String PROPERTY_KEY_PIXEL_BORDER_SHOWN = "pixel.border.shown"; /** * Preferences key for pixel border size */ public static final String PROPERTY_KEY_PIXEL_BORDER_SIZE = "pixel.border.size"; /** * Preferences key for pixel border color */ public static final String PROPERTY_KEY_PIXEL_BORDER_COLOR = "pixel.border.color"; private JComponent[] imageBorderColorComponents; private JComponent[] pixelBorderColorComponents; protected PropertySet createPropertySet() { return createPropertySet(new ImageLayerBean()); } @Override protected JPanel createPanel(BindingContext context) { TableLayout tableLayout = new TableLayout(2); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTablePadding(new Insets(4, 10, 0, 0)); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setColumnWeightX(1, 1.0); tableLayout.setCellColspan(1, 0, 2); tableLayout.setCellColspan(4, 0, 2); JPanel pageUI = new JPanel(tableLayout); PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance(); Property backgroundColor = context.getPropertySet().getProperty(PROPERTY_KEY_IMAGE_BG_COLOR); Property showImageBorder = context.getPropertySet().getProperty(PROPERTY_KEY_IMAGE_BORDER_SHOWN); Property imageBorderSize = context.getPropertySet().getProperty(PROPERTY_KEY_IMAGE_BORDER_SIZE); Property imageBorderColor = context.getPropertySet().getProperty(PROPERTY_KEY_IMAGE_BORDER_COLOR); Property showPixelBorder = context.getPropertySet().getProperty(PROPERTY_KEY_PIXEL_BORDER_SHOWN); Property pixelBorderSize = context.getPropertySet().getProperty(PROPERTY_KEY_PIXEL_BORDER_SIZE); Property pixelBorderColor = context.getPropertySet().getProperty(PROPERTY_KEY_PIXEL_BORDER_COLOR); JComponent[] backgroundColorComponents = PreferenceUtils.createColorComponents(backgroundColor); JComponent[] showImageBorderComponents = registry.findPropertyEditor(showImageBorder.getDescriptor()).createComponents(showImageBorder.getDescriptor(), context); JComponent[] imageBorderSizeComponents = registry.findPropertyEditor(imageBorderSize.getDescriptor()).createComponents(imageBorderSize.getDescriptor(), context); imageBorderColorComponents = PreferenceUtils.createColorComponents(imageBorderColor); JComponent[] showPixelBorderComponents = registry.findPropertyEditor(showPixelBorder.getDescriptor()).createComponents(showPixelBorder.getDescriptor(), context); JComponent[] pixelBorderSizeComponents = registry.findPropertyEditor(pixelBorderSize.getDescriptor()).createComponents(pixelBorderSize.getDescriptor(), context); pixelBorderColorComponents = PreferenceUtils.createColorComponents(pixelBorderColor); // row 0 pageUI.add(backgroundColorComponents[0]); pageUI.add(backgroundColorComponents[1]); // row 1 pageUI.add(showImageBorderComponents[0]); // row 2 pageUI.add(imageBorderSizeComponents[1]); pageUI.add(imageBorderSizeComponents[0]); // row 3 pageUI.add(imageBorderColorComponents[0]); pageUI.add(imageBorderColorComponents[1]); // row 4 pageUI.add(showPixelBorderComponents[0]); // row 5 pageUI.add(pixelBorderSizeComponents[1]); pageUI.add(pixelBorderSizeComponents[0]); // row 6 pageUI.add(pixelBorderColorComponents[0]); pageUI.add(pixelBorderColorComponents[1]); // row 7+ pageUI.add(tableLayout.createVerticalSpacer()); JPanel parent = new JPanel(new BorderLayout()); parent.add(pageUI, BorderLayout.CENTER); parent.add(Box.createHorizontalStrut(100), BorderLayout.EAST); return parent; } @Override protected void configure(BindingContext context) { Enablement enablementImageBorderSize = context.bindEnabledState(PROPERTY_KEY_IMAGE_BORDER_SIZE, false, PROPERTY_KEY_IMAGE_BORDER_SHOWN, false); context.getPropertySet().getProperty(PROPERTY_KEY_IMAGE_BORDER_SHOWN).addPropertyChangeListener(evt -> { enablementImageBorderSize.apply(); for (JComponent imageBorderColorComponent : imageBorderColorComponents) { imageBorderColorComponent.setEnabled(((Boolean) evt.getNewValue())); } }); Enablement enablementPixelBorderSize = context.bindEnabledState(PROPERTY_KEY_PIXEL_BORDER_SIZE, false, PROPERTY_KEY_PIXEL_BORDER_SHOWN, false); context.getPropertySet().getProperty(PROPERTY_KEY_PIXEL_BORDER_SHOWN).addPropertyChangeListener(evt -> { enablementPixelBorderSize.apply(); for (JComponent pixelBorderColorComponent : pixelBorderColorComponents) { pixelBorderColorComponent.setEnabled(((Boolean) evt.getNewValue())); } }); for (JComponent imageBorderColorComponent : imageBorderColorComponents) { imageBorderColorComponent.setEnabled(ImageLayer.DEFAULT_BORDER_SHOWN); } } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-imagelayer"); } @SuppressWarnings("UnusedDeclaration") static class ImageLayerBean { @Preference(label = "Background colour", key = PROPERTY_KEY_IMAGE_BG_COLOR) Color backgroundColor = ProductSceneView.DEFAULT_IMAGE_BACKGROUND_COLOR; @Preference(label = "Show image border", key = PROPERTY_KEY_IMAGE_BORDER_SHOWN) boolean showImageBorder = ImageLayer.DEFAULT_BORDER_SHOWN; @Preference(label = "Image border size", key = PROPERTY_KEY_IMAGE_BORDER_SIZE) double imageBorderSize = ImageLayer.DEFAULT_BORDER_WIDTH; @Preference(label = "Image border colour", key = PROPERTY_KEY_IMAGE_BORDER_COLOR) Color imageBorderColor = ImageLayer.DEFAULT_BORDER_COLOR; @Preference(label = "Show pixel borders in magnified views", key = PROPERTY_KEY_PIXEL_BORDER_SHOWN) boolean showPixelBorder = ImageLayer.DEFAULT_PIXEL_BORDER_SHOWN; @Preference(label = "Pixel border size", key = PROPERTY_KEY_PIXEL_BORDER_SIZE) double pixelBorderSize = ImageLayer.DEFAULT_PIXEL_BORDER_WIDTH; @Preference(label = "Pixel border colour", key = PROPERTY_KEY_PIXEL_BORDER_COLOR) Color pixelBorderColor = ImageLayer.DEFAULT_PIXEL_BORDER_COLOR; } }
9,403
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TileCacheMonitor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/developer/TileCacheMonitor.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.developer; import com.sun.media.jai.util.CacheDiagnostics; import com.sun.media.jai.util.SunTileCache; import org.esa.snap.core.image.RasterDataNodeOpImage; import org.esa.snap.core.image.SingleBandedOpImage; import org.esa.snap.core.image.VirtualBandOpImage; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CombinedDomainXYPlot; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.title.LegendTitle; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.chart.util.UnitType; import org.jfree.data.time.Millisecond; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import javax.media.jai.CachedTile; import javax.media.jai.JAI; import javax.media.jai.PlanarImage; import javax.media.jai.TileCache; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.table.AbstractTableModel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.image.RenderedImage; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; public class TileCacheMonitor { private JTabbedPane tabbedPane; private static final String CACHE_INFO_TAB = "Cache Info"; private static final String CACHE_CHART_TAB = "Cache Chart"; private static final String IMAGES_TAB = "Images in Cache"; private static class CachedTileInfo { Object uid; String imageName; int level; int numTiles; long size; String comment; } private static class TileCacheTableModel extends AbstractTableModel { private final static String[] COLUM_NAMES = {"Image", "#Tiles", "Size (kB)", "Level", "Comment"}; private final static Class[] COLUM_CLASSES = {String.class, Integer.class, Long.class, Integer.class, String.class}; List<CachedTileInfo> data = new ArrayList<CachedTileInfo>(50); @Override public int getRowCount() { return data.size(); } @Override public int getColumnCount() { return COLUM_NAMES.length; } @Override public String getColumnName(int columnIndex) { return COLUM_NAMES[columnIndex]; } @Override public Class<?> getColumnClass(int columnIndex) { return COLUM_CLASSES[columnIndex]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public Object getValueAt(int row, int column) { CachedTileInfo cachedTileInfo = data.get(row); switch (column) { case 0: return cachedTileInfo.imageName; case 1: return cachedTileInfo.numTiles; case 2: return cachedTileInfo.size / 1024; case 3: return cachedTileInfo.level; case 4: return cachedTileInfo.comment; } return null; } public void reset() { for (CachedTileInfo tileInfo : data) { tileInfo.numTiles = 0; tileInfo.size = 0; } } public void cleanUp() { Iterator<CachedTileInfo> iterator = data.iterator(); while (iterator.hasNext()) { CachedTileInfo tileInfo = iterator.next(); if (tileInfo.numTiles == 0) { iterator.remove(); } } } public void addRow(CachedTileInfo tileInfo) { data.add(tileInfo); } } /** * The datasets. */ private TimeSeriesCollection[] datasets; private TileCacheTableModel tableModel; private JTextArea textarea; /** * Creates a new monitor panel. * * @return the monitor panel */ public JPanel createPanel() { JPanel mainPanel = new JPanel(new BorderLayout()); CombinedDomainXYPlot plot = new CombinedDomainXYPlot(new DateAxis("Time")); this.datasets = new TimeSeriesCollection[4]; this.datasets[0] = addSubPlot(plot, "#Tiles"); this.datasets[1] = addSubPlot(plot, "#Hits"); this.datasets[2] = addSubPlot(plot, "#Misses"); this.datasets[3] = addSubPlot(plot, "Mem (kB)"); JFreeChart chart = new JFreeChart(plot); LegendTitle legend = (LegendTitle) chart.getSubtitle(0); legend.setPosition(RectangleEdge.RIGHT); legend.setMargin(new RectangleInsets(UnitType.ABSOLUTE, 0, 4, 0, 4)); chart.setBorderPaint(Color.black); chart.setBorderVisible(true); chart.setBackgroundPaint(Color.white); plot.setBackgroundPaint(Color.lightGray); plot.setDomainGridlinePaint(Color.white); plot.setRangeGridlinePaint(Color.white); plot.setAxisOffset(new RectangleInsets(4, 4, 4, 4)); ValueAxis axis = plot.getDomainAxis(); axis.setAutoRange(true); axis.setFixedAutoRange(60000.0); // 60 seconds textarea = new JTextArea(); tableModel = new TileCacheTableModel(); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 470)); chartPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); tabbedPane = new JTabbedPane(); tabbedPane.add(CACHE_INFO_TAB, new JScrollPane(textarea)); tabbedPane.add(CACHE_CHART_TAB, chartPanel); tabbedPane.add(IMAGES_TAB, new JScrollPane(new JTable(tableModel))); tabbedPane.setSelectedIndex(0); mainPanel.add(tabbedPane); return mainPanel; } public synchronized void updateState() { final TileCache tileCache = JAI.getDefaultInstance().getTileCache(); int selectedIndex = tabbedPane.getSelectedIndex(); //System.out.println("selectedIndex = " + selectedIndex); if (selectedIndex == 1) { // (1) if graph view visible if (tileCache instanceof CacheDiagnostics) { CacheDiagnostics cacheDiagnostics = (CacheDiagnostics) tileCache; cacheDiagnostics.enableDiagnostics(); final Millisecond t = new Millisecond(); update(0, t, cacheDiagnostics.getCacheTileCount()); update(1, t, cacheDiagnostics.getCacheHitCount()); update(2, t, cacheDiagnostics.getCacheMissCount()); update(3, t, cacheDiagnostics.getCacheMemoryUsed() / 1024); } } else if (selectedIndex == 2) { // (2) if table view visible if (tileCache instanceof SunTileCache) { SunTileCache stc = (SunTileCache) tileCache; synchronized (stc) { Hashtable cachedObject = (Hashtable) stc.getCachedObject(); Collection<CachedTile> tiles = cachedObject.values(); // dumpImageTree(tiles); updateTableModel(tiles); } } } else if (selectedIndex == 0) { // (3) if info view visible StringBuilder sb = new StringBuilder(); if (tileCache != null) { sb.append("tileCache.memoryCapacity: \t"); sb.append(tileCache.getMemoryCapacity() / (1024 * 1024)); sb.append(" MB\n"); sb.append("tileCache.memoryThreshold: \t"); sb.append(tileCache.getMemoryThreshold()); sb.append("\n"); sb.append("tileCache.tileComparator: \t"); sb.append(tileCache.getTileComparator()); sb.append("\n"); sb.append("tileCache.class: \t"); sb.append(tileCache.getClass().getName()); sb.append("\n"); } if (tileCache instanceof SunTileCache) { SunTileCache sunTileCache = (SunTileCache) tileCache; sb.append("sunTileCache.cacheMemoryUsed: \t"); sb.append(sunTileCache.getCacheMemoryUsed() / (1024 * 1024)); sb.append(" MB\n"); sb.append("sunTileCache.cacheHitCount: \t"); sb.append(sunTileCache.getCacheHitCount()); sb.append("\n"); sb.append("sunTileCache.cacheMissCount: \t"); sb.append(sunTileCache.getCacheMissCount()); sb.append("\n"); sb.append("sunTileCache.cacheTileCount: \t"); sb.append(sunTileCache.getCacheTileCount()); sb.append("\n"); } textarea.setText(sb.toString()); } } private void updateTableModel(Collection<CachedTile> tiles) { tableModel.reset(); for (CachedTile sct : tiles) { RenderedImage owner = sct.getOwner(); if (owner == null || !(owner instanceof PlanarImage)) { continue; } PlanarImage image = (PlanarImage) owner; Object imageID = image.getImageID(); CachedTileInfo cachedTileInfo = null; for (CachedTileInfo info : tableModel.data) { if (info.uid.equals(imageID)) { cachedTileInfo = info; break; } } if (cachedTileInfo == null) { cachedTileInfo = new CachedTileInfo(); cachedTileInfo.uid = imageID; cachedTileInfo.imageName = getImageName(image); cachedTileInfo.level = getImageLevel(image); cachedTileInfo.comment = getImageComment(image); tableModel.data.add(cachedTileInfo); } cachedTileInfo.numTiles++; cachedTileInfo.size += sct.getTileSize(); } tableModel.cleanUp(); tableModel.fireTableDataChanged(); } private String getImageName(RenderedImage image) { return image.getClass().getSimpleName(); } private int getImageLevel(RenderedImage image) { if (image instanceof SingleBandedOpImage) { SingleBandedOpImage sboi = (SingleBandedOpImage) image; return sboi.getLevel(); } return -1; } private String getImageComment(RenderedImage image) { if (image instanceof RasterDataNodeOpImage) { RasterDataNodeOpImage rdnoi = (RasterDataNodeOpImage) image; return rdnoi.getRasterDataNode().getName(); } else if (image instanceof VirtualBandOpImage) { VirtualBandOpImage vboi = (VirtualBandOpImage) image; return vboi.getExpression(); } else { final String s = image.toString(); final int p1 = s.indexOf('['); final int p2 = s.indexOf(']', p1 + 1); if (p1 > 0 && p2 > p1) { return s.substring(p1 + 1, p2 - 1); } return s; } } private void dumpImageTree(Collection<CachedTile> tiles) { final Map<RenderedImage, Integer> ownerMap = new HashMap<RenderedImage, Integer>(100); final Map<RenderedImage, Long> sizeMap = new HashMap<RenderedImage, Long>(100); for (CachedTile sct : tiles) { RenderedImage owner = sct.getOwner(); if (owner == null) { continue; } Integer count = ownerMap.get(owner); if (count == null) { ownerMap.put(owner, Integer.valueOf(1)); } else { ownerMap.put(owner, Integer.valueOf(count.intValue() + 1)); } Long size = sizeMap.get(owner); if (size == null) { sizeMap.put(owner, Long.valueOf(sct.getTileSize())); } else { sizeMap.put(owner, Long.valueOf(size + sct.getTileSize())); } } Set<RenderedImage> rootEntries = new HashSet<RenderedImage>(ownerMap.keySet()); for (RenderedImage image : ownerMap.keySet()) { Vector<RenderedImage> sources = image.getSources(); eleminateSources(sources, rootEntries); } for (RenderedImage image : rootEntries) { printImage(image, ownerMap.get(image), sizeMap.get(image)); printSources("", image.getSources(), ownerMap, sizeMap); } System.out.println("======================================"); } private void eleminateSources(Vector<RenderedImage> sources, Set<RenderedImage> rootEntries) { if (sources != null) { for (RenderedImage renderedImage : sources) { if (rootEntries.contains(renderedImage)) { rootEntries.remove(renderedImage); } eleminateSources(renderedImage.getSources(), rootEntries); } } } private void printSources(String prefix, Vector<RenderedImage> sources, Map<RenderedImage, Integer> ownerMap, Map<RenderedImage, Long> sizeMap) { if (sources != null) { for (RenderedImage image : sources) { System.out.print(prefix + "->"); if (ownerMap.containsKey(image)) { printImage(image, ownerMap.get(image), sizeMap.get(image)); } else { printImage(image, 0, 0L); } printSources("--" + prefix, image.getSources(), ownerMap, sizeMap); } } } private void printImage(RenderedImage image, int numTiles, Long size) { System.out.print("(" + getImageName(image) + ") "); if (numTiles > 0) { System.out.print("#tiles=" + numTiles + " "); System.out.printf("size=%8.2fMB ", (size / (1024.0 * 1024.0))); } final int level = getImageLevel(image); if (level >= 0) { System.out.print("level=" + level + " "); } System.out.print(getImageComment(image)); System.out.println(); } private static TimeSeriesCollection addSubPlot(CombinedDomainXYPlot plot, String label) { final TimeSeriesCollection seriesCollection = new TimeSeriesCollection(new TimeSeries(label)); NumberAxis rangeAxis = new NumberAxis(); rangeAxis.setAutoRangeIncludesZero(false); XYPlot subplot = new XYPlot(seriesCollection, null, rangeAxis, new StandardXYItemRenderer()); subplot.setBackgroundPaint(Color.lightGray); subplot.setDomainGridlinePaint(Color.white); subplot.setRangeGridlinePaint(Color.white); plot.add(subplot); return seriesCollection; } private void update(int i, Millisecond t, double value) { this.datasets[i].getSeries(0).add(t, value); } }
16,260
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ActionContextMonitorTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/developer/ActionContextMonitorTopComponent.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.developer; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; 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.windows.TopComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import java.awt.BorderLayout; import java.util.Collection; /** * Displays the state of SNAP's global action context. * * @author Norman Fomferra */ @TopComponent.Description( preferredID = "ActionContextMonitorTopComponent", persistenceType = TopComponent.PERSISTENCE_NEVER ) @TopComponent.Registration(mode = "rightSlidingSide", openAtStartup = false, position = 100, roles={"developer"}) @ActionID(category = "Window", id = "org.esa.snap.rcp.developer.ActionContextMonitorTopComponent") @ActionReference(path = "Menu/View/Tool Windows/Developer", position = 10) @TopComponent.OpenActionRegistration( displayName = "#CTL_ActionContextMonitorTopComponentName", preferredID = "ActionContextMonitorTopComponent" ) @NbBundle.Messages({ "CTL_ActionContextMonitorTopComponentName=Action Context Monitor", "CTL_ActionContextMonitorTopComponentDescription=Displays the state of SNAP's global action context.", }) public final class ActionContextMonitorTopComponent extends TopComponent implements LookupListener { private JLabel infoLabel; private JTable infoTable; private Lookup.Result<Object> result; public ActionContextMonitorTopComponent() { initComponents(); setName(Bundle.CTL_ActionContextMonitorTopComponentName()); setToolTipText(Bundle.CTL_ActionContextMonitorTopComponentDescription()); putClientProperty(TopComponent.PROP_MAXIMIZATION_DISABLED, Boolean.TRUE); putClientProperty(TopComponent.PROP_KEEP_PREFERRED_SIZE_WHEN_SLIDED_IN, Boolean.TRUE); } private void initComponents() { setLayout(new BorderLayout(4, 4)); setBorder(new EmptyBorder(4, 4, 4, 4)); infoLabel = new JLabel(""); infoTable = new JTable(); add(infoLabel, BorderLayout.NORTH); add(new JScrollPane(infoTable), BorderLayout.CENTER); } @Override public void resultChanged(LookupEvent lookupEvent) { Collection<? extends Object> selectedObjects = result.allInstances(); if (!selectedObjects.isEmpty()) { Object[][] data = new Object[selectedObjects.size()][3]; int i = 0; for (Object selectedObject : selectedObjects) { data[i][0] = i + 1; data[i][1] = selectedObject.getClass().getSimpleName(); data[i][2] = String.valueOf(selectedObject); i++; } infoLabel.setText(selectedObjects.size() + " objects(s) selected:"); infoTable.setModel(new DefaultTableModel(data, new String[]{"#", "Type", "Name"})); infoTable.getColumnModel().getColumn(0).setPreferredWidth(20); infoTable.getColumnModel().getColumn(1).setPreferredWidth(80); } else { infoLabel.setText("No objects selected."); infoTable.setModel(new DefaultTableModel()); } } @Override public void componentOpened() { result = Utilities.actionsGlobalContext().lookupResult(Object.class); result.addLookupListener(this); } @Override public void componentClosed() { result.removeLookupListener(this); } }
3,862
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TileCacheMonitorTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/developer/TileCacheMonitorTopComponent.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.developer; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.JPanel; import javax.swing.Timer; import java.awt.BorderLayout; /** * Displays the state of SNAP's global image tile cache. * * @author Norman Fomferra */ @TopComponent.Description( preferredID = "TileCacheMonitorTopComponent", persistenceType = TopComponent.PERSISTENCE_NEVER ) @TopComponent.Registration(mode = "rightSlidingSide", openAtStartup = false, position = 200, roles={"developer"}) @ActionID(category = "Window", id = "org.esa.snap.rcp.developer.TileCacheMonitorTopComponent") @ActionReference(path = "Menu/View/Tool Windows/Developer", position = 20) @TopComponent.OpenActionRegistration( displayName = "#CTL_TileCacheMonitorTopComponentName", preferredID = "TileCacheMonitorTopComponent" ) @NbBundle.Messages({ "CTL_TileCacheMonitorTopComponentName=Tile Cache Monitor", "CTL_TileCacheMonitorTopComponentDescription=Displays the state SNAP's global image tile cache", }) public class TileCacheMonitorTopComponent extends TopComponent { public static final String ID = TileCacheMonitorTopComponent.class.getName(); private Timer timer; private TileCacheMonitor tileCacheMonitor; public TileCacheMonitorTopComponent() { setLayout(new BorderLayout()); setName(Bundle.CTL_TileCacheMonitorTopComponentName()); setToolTipText(Bundle.CTL_TileCacheMonitorTopComponentDescription()); tileCacheMonitor = new TileCacheMonitor(); JPanel panel = tileCacheMonitor.createPanel(); timer = new Timer(2000, e -> { if (isVisible()) { tileCacheMonitor.updateState(); } }); timer.setRepeats(true); timer.start(); add(panel, BorderLayout.CENTER); } /** * The default implementation does nothing. * <p>Clients shall not call this method directly.</p> */ @Override public void componentOpened() { timer.restart(); } /** * The default implementation does nothing. * <p>Clients shall not call this method directly.</p> */ @Override public void componentClosed() { timer.stop(); } }
3,069
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MetadataViewTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/metadata/MetadataViewTopComponent.java
package org.esa.snap.rcp.metadata; import eu.esa.snap.netbeans.docwin.DocumentTopComponent; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.datamodel.MetadataElement; import org.esa.snap.ui.product.metadata.MetadataTableInnerElement; import org.netbeans.swing.outline.Outline; import org.openide.explorer.ExplorerManager; import org.openide.explorer.view.OutlineView; import org.openide.nodes.Node; import javax.swing.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumnModel; import java.awt.*; public class MetadataViewTopComponent extends DocumentTopComponent<MetadataElement, OutlineView> implements ExplorerManager.Provider { private static final String[] COLUMN_NAMES = new String[]{ "Value", "Value", "Type", "Type", "Unit", "Unit", "Description", "Description" }; private static final int[] COLUMN_WIDTHS = { 180, // 0 180, // 1 50, // 2 40, // 3 200 // 4 }; private static final String nodesColumnName = "Name"; private ExplorerManager em = new ExplorerManager(); private OutlineView outlineView; public MetadataViewTopComponent(MetadataElement element) { super(element); updateDisplayName(); setName(getDisplayName()); initView(); final MetadataTableInnerElement tableInnerElement = new MetadataTableInnerElement(element); em.setRootContext(tableInnerElement.createNode()); } @Override public OutlineView getView() { return outlineView; } private void initView() { setLayout(new BorderLayout()); outlineView = new OutlineView(nodesColumnName); outlineView.setPropertyColumns(COLUMN_NAMES); final Outline outline = outlineView.getOutline(); outline.setRootVisible(false); DefaultTableCellRenderer decimalTableCellRenderer = new StringDecimalFormatRenderer(); outline.setDefaultRenderer(Double.class, decimalTableCellRenderer); outline.setDefaultRenderer(Float.class, decimalTableCellRenderer); outline.setDefaultRenderer(Node.Property.class, new MetadataOutlineCellRenderer()); final TableColumnModel columnModel = outline.getColumnModel(); columnModel.getColumn(0).setCellRenderer(new MetadataOutlineCellRenderer()); final int[] columnWidths = COLUMN_WIDTHS; for (int i = 0; i < columnModel.getColumnCount(); i++) { columnModel.getColumn(i).setPreferredWidth(columnWidths[i]); } add(outlineView, BorderLayout.CENTER); } private void updateDisplayName() { setDisplayName(WindowUtilities.getUniqueTitle(getDocument().getDisplayName(), MetadataViewTopComponent.class)); } @Override public ExplorerManager getExplorerManager() { return em; } public static class StringDecimalFormatRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (comp instanceof JLabel) { JLabel label = (JLabel) comp; label.setHorizontalAlignment(JLabel.LEFT); if (value instanceof Float || value instanceof Double) { label.setText(String.valueOf(value)); } else { label.setText("n/a"); } } return comp; } } }
3,772
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MetadataOutlineCellRenderer.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/metadata/MetadataOutlineCellRenderer.java
package org.esa.snap.rcp.metadata; import org.netbeans.swing.outline.DefaultOutlineCellRenderer; import org.openide.awt.HtmlRenderer; import org.openide.nodes.Node.Property; import org.openide.util.Exceptions; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import java.awt.Color; import java.awt.Component; import java.lang.reflect.InvocationTargetException; /** * @author https://jnkjava.wordpress.com/2011/11/28/recipe-7-how-do-i-decorate-a-read-only-outlineview/ */ class MetadataOutlineCellRenderer extends DefaultOutlineCellRenderer { /** * Gray Color for the odd lines in the view. */ private static final Color VERY_LIGHT_GRAY = new Color(236, 236, 236); /** * Highlight the non editable cells making the foreground lighter. */ @Override @SuppressWarnings("unchecked") public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected, final boolean hasFocus, final int row, final int column) { Component cell = null; Object valueToDisplay = value; if (value instanceof Property) { try { valueToDisplay = ((Property) value).getValue(); } catch (IllegalAccessException | InvocationTargetException ex) { Exceptions.printStackTrace(ex); } } if (valueToDisplay != null) { TableCellRenderer renderer = table.getDefaultRenderer(valueToDisplay.getClass()); if (renderer != null) { cell = renderer.getTableCellRendererComponent(table, valueToDisplay, isSelected, hasFocus, row, column); } } else { cell = super.getTableCellRendererComponent(table, valueToDisplay, isSelected, hasFocus, row, column); } if (cell != null) { if (cell instanceof HtmlRenderer.Renderer) { ((HtmlRenderer.Renderer) cell).setIndent(5); } else if (cell instanceof DefaultTableCellRenderer.UIResource) { ((UIResource) cell).setHorizontalAlignment(JLabel.LEFT); } Color foregroundColor = table.getForeground(); cell.setForeground(foregroundColor); cell.setBackground(row % 2 == 0 ? Color.WHITE : VERY_LIGHT_GRAY); if (isSelected) { cell.setBackground(table.getSelectionBackground()); } } return cell; } }
2,854
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CreateSubsetFromViewAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/subset/CreateSubsetFromViewAction.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.subset; 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.NbBundle; import javax.swing.AbstractAction; import java.awt.Rectangle; import java.awt.event.ActionEvent; /** * This action opens a product subset dialog with the initial spatial bounds * taken from the currently visible image area. * * @author Norman Fomferra */ @ActionID(category = "Raster", id = "CreateSubsetFromViewAction") @ActionRegistration( displayName = "#CTL_CreateSubsetFromViewAction_Name" ) @ActionReferences({ @ActionReference(path = "Context/ProductSceneView", position = 100), }) @NbBundle.Messages({ "CTL_CreateSubsetFromViewAction_Name=Spatial Subset from View...", "CTL_CreateSubsetFromViewAction_Title=Spatial Subset from View" }) public class CreateSubsetFromViewAction extends AbstractAction { private final ProductSceneView view; public CreateSubsetFromViewAction(ProductSceneView view) { this.view = view; } @Override public void actionPerformed(ActionEvent ignored) { Rectangle bounds = view.getVisibleImageBounds(); if (bounds == null) { Dialogs.showWarning(Bundle.CTL_CreateSubsetFromViewAction_Title(), "The selected area is entirely outside the product's spatial boundaries.", null); } CreateSubsetAction.createSubset(view.getProduct(), bounds, view.getRaster()); } }
2,375
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CreateSubsetAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/subset/CreateSubsetAction.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.subset; import org.esa.snap.core.dataio.ProductSubsetDef; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.gpf.common.SubsetOp; import org.esa.snap.core.subset.PixelSubsetRegion; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.ui.product.ProductSubsetDialog; 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.Rectangle; import java.awt.event.ActionEvent; /** * This action opens a product subset dialog with the initial spatial bounds * taken from the currently visible image area, if any. * * @author Norman Fomferra */ @ActionID(category = "Raster", id = "CreateSubsetAction") @ActionRegistration(displayName = "#CTL_CreateSubsetAction_Name") @ActionReferences({@ActionReference(path = "Menu/Raster", position = 50)}) @NbBundle.Messages({ "CTL_CreateSubsetAction_Name=Subset...", "CTL_CreateSubsetAction_Title=Subset" }) public class CreateSubsetAction extends AbstractAction { static int subsetNumber; private final ProductNode sourceNode; public CreateSubsetAction(ProductNode sourceNode) { this.sourceNode = sourceNode; } @Override public void actionPerformed(ActionEvent ignored) { Product product = sourceNode.getProduct(); RasterDataNode rasterDataNode = null; ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); if (view != null && view.getProduct() == product && view.getRaster() != null) { rasterDataNode = view.getRaster(); } if (product != null) { createSubset(product, getInitialBounds(product), rasterDataNode); } } public static void createSubset(Product sourceProduct, Rectangle bounds, RasterDataNode rdn) { final String subsetName = "subset_" + CreateSubsetAction.subsetNumber + "_of_" + sourceProduct.getName(); final ProductSubsetDef initSubset = new ProductSubsetDef(); initSubset.setSubsetRegion(new PixelSubsetRegion(bounds, 0)); if(sourceProduct.isMultiSize() && rdn != null) { initSubset.setRegionMap(SubsetOp.computeRegionMap(initSubset.getRegion(),rdn.getName(),sourceProduct,null)); } else if(sourceProduct.isMultiSize()) { initSubset.setRegionMap(SubsetOp.computeRegionMap(initSubset.getRegion(),sourceProduct,null)); } initSubset.setNodeNames(sourceProduct.getBandNames()); initSubset.addNodeNames(sourceProduct.getTiePointGridNames()); initSubset.setIgnoreMetadata(false); final ProductSubsetDialog subsetDialog = new ProductSubsetDialog(SnapApp.getDefault().getMainFrame(), sourceProduct, initSubset); if (subsetDialog.show() != ProductSubsetDialog.ID_OK) { return; } final ProductSubsetDef subsetDef = subsetDialog.getProductSubsetDef(); if (subsetDef == null) { Dialogs.showInformation(Bundle.CTL_CreateSubsetFromViewAction_Title(), "No product subset created.", null); return; } try { final Product subset = sourceProduct.createSubset(subsetDef, subsetName, sourceProduct.getDescription()); SnapApp.getDefault().getProductManager().addProduct(subset); CreateSubsetAction.subsetNumber++; } catch (Exception e) { final String msg = "An error occurred while creating the product subset:\n" + e.getMessage(); SnapApp.getDefault().handleError(msg, e); } } public static void createSubset(Product sourceProduct, Rectangle bounds) { createSubset(sourceProduct, bounds, null); } private Rectangle getInitialBounds(Product product) { Rectangle bounds = null; ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); if (view != null && view.getProduct() == product) { bounds = view.getVisibleImageBounds(); } else { bounds = new Rectangle(0,0,product.getSceneRasterWidth(),product.getSceneRasterHeight()); } return bounds; } }
5,393
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WorldMapTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/worldmap/WorldMapTopComponent.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.worldmap; 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.esa.snap.rcp.util.SelectionSupport; import org.esa.snap.rcp.windows.ToolTopComponent; import org.esa.snap.ui.WorldMapPane; import org.esa.snap.ui.WorldMapPaneDataModel; import org.esa.snap.ui.product.ProductSceneView; import org.netbeans.api.annotations.common.NonNull; import org.netbeans.api.annotations.common.NullAllowed; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Dimension; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.VIEW; @TopComponent.Description( preferredID = "WorldMapTopComponent", iconBase = "org/esa/snap/rcp/icons/WorldMap.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "navigator", openAtStartup = false, position = 40 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.worldmap.WorldMapTopComponent") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 60), @ActionReference(path = "Toolbars/Tool Windows") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_WorldMapTopComponent_Name", preferredID = "WorldMapTopComponent" ) @NbBundle.Messages({ "CTL_WorldMapTopComponent_Name=World Map", "CTL_WorldMapTopComponent_HelpId=showWorldMapWnd" }) /** * The window displaying the world map. * * @author Sabine Embacher * @author Norman Fomferra * @author Marco Peters * @version $Revision$ $Date$ */ public class WorldMapTopComponent extends ToolTopComponent { public static final String ID = WorldMapTopComponent.class.getName(); protected WorldMapPaneDataModel worldMapDataModel; public WorldMapTopComponent() { setDisplayName(Bundle.CTL_WorldMapTopComponent_Name()); initUI(); } public void initUI() { setLayout(new BorderLayout()); final JPanel mainPane = new JPanel(new BorderLayout(4, 4)); mainPane.setPreferredSize(new Dimension(320, 160)); worldMapDataModel = new WorldMapPaneDataModel(); final WorldMapPane worldMapPane = new WorldMapPane(worldMapDataModel); worldMapPane.setNavControlVisible(true); mainPane.add(worldMapPane, BorderLayout.CENTER); final SnapApp snapApp = SnapApp.getDefault(); snapApp.getProductManager().addListener(new WorldMapProductManagerListener()); snapApp.getSelectionSupport(ProductNode.class).addHandler(new SelectionSupport.Handler<ProductNode>() { @Override public void selectionChange(@NullAllowed ProductNode oldValue, @NullAllowed ProductNode newValue) { if(newValue != null) { setSelectedProduct(newValue.getProduct()); } } }); setProducts(snapApp.getProductManager().getProducts()); setSelectedProduct(snapApp.getSelectedProduct(VIEW)); add(mainPane, BorderLayout.CENTER); } public void setSelectedProduct(Product product) { worldMapDataModel.setSelectedProduct(product); } public Product getSelectedProduct() { return worldMapDataModel.getSelectedProduct(); } public void setProducts(Product[] products) { worldMapDataModel.setProducts(products); } @Override protected void productSceneViewSelected(@NonNull ProductSceneView view) { setSelectedProduct(view.getProduct()); } private class WorldMapProductManagerListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { final Product product = event.getProduct(); worldMapDataModel.addProduct(product); setSelectedProduct(product); } @Override public void productRemoved(ProductManager.Event event) { final Product product = event.getProduct(); if (getSelectedProduct() == product) { setSelectedProduct(null); } worldMapDataModel.removeProduct(product); } } }
5,187
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskIOAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskIOAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.openide.windows.TopComponent; import javax.swing.JOptionPane; import java.io.File; abstract class MaskIOAction extends MaskAction { private final TopComponent maskTopComponent; public MaskIOAction(TopComponent maskTopComponent, MaskForm maskForm, String iconPath, String buttonName, String description ) { super(maskForm, iconPath, buttonName, description); this.maskTopComponent = maskTopComponent; } void showErrorDialog(final String message) { Dialogs.showMessage(maskTopComponent.getDisplayName() + " - Error", message, JOptionPane.ERROR_MESSAGE, null); } void setDirectory(final File directory) { SnapApp.getDefault().getPreferences().put("mask.io.dir", directory.getPath()); } File getDirectory() { File directory = SystemUtils.getUserHomeDir(); return new File(SnapApp.getDefault().getPreferences().get("mask.io.dir", directory.getPath())); } }
1,849
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskToolTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskToolTopComponent.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.core.datamodel.Mask; 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.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.windows.ToolTopComponent; import org.esa.snap.ui.help.HelpDisplayer; import org.esa.snap.ui.product.ProductSceneView; import org.netbeans.api.annotations.common.NonNull; import org.openide.util.HelpCtx; import javax.swing.AbstractButton; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.EXPLORER; public abstract class MaskToolTopComponent extends ToolTopComponent implements HelpCtx.Provider { private MaskForm maskForm; public void initUI() { setLayout(new BorderLayout()); maskForm = createMaskForm(this, e -> { final ProductSceneView sceneView = getSelectedProductSceneView(); if (sceneView != null) { Mask selectedMask = maskForm.getSelectedMask(); if (selectedMask != null) { VectorDataNode vectorDataNode = Mask.VectorDataType.getVectorData(selectedMask); if (vectorDataNode != null) { sceneView.selectVectorDataLayer(vectorDataNode); } } } }); AbstractButton helpButton = maskForm.getHelpButton(); if (helpButton != null) { helpButton.addActionListener(e -> HelpDisplayer.show(getHelpCtx())); helpButton.setName("helpButton"); } updateMaskForm(getSelectedProductSceneView()); SnapApp.getDefault().getProductManager().addListener(new MaskPTL()); SnapApp.getDefault().getSelectionSupport(Product.class).addHandler((oldValue, newValue) -> updateMaskForm(getSelectedProductSceneView())); maskForm.updateState(); setDisplayName(getTitle()); add(maskForm.createContentPanel(), BorderLayout.CENTER); } private void updateMaskForm(ProductSceneView view) { if (view == null) { final ProductNode selectedProductNode = SnapApp.getDefault().getSelectedProductNode(EXPLORER); if (selectedProductNode instanceof RasterDataNode) { final RasterDataNode rdn = (RasterDataNode) selectedProductNode; maskForm.reconfigureMaskTable(rdn.getProduct(), rdn); } else if (selectedProductNode instanceof Product) { final Product product = (Product) selectedProductNode; maskForm.reconfigureMaskTable(product, null); } else if (selectedProductNode != null && selectedProductNode.getProduct() != null) { maskForm.reconfigureMaskTable(selectedProductNode.getProduct(), null); } else { maskForm.clearMaskTable(); } } else { maskForm.reconfigureMaskTable(view.getProduct(), view.getRaster()); } } private class MaskPTL implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { //do nothing } @Override public void productRemoved(ProductManager.Event event) { if (maskForm.getProduct() == event.getProduct()) { updateMaskForm(getSelectedProductSceneView()); } } } @Override protected void productSceneViewSelected(@NonNull ProductSceneView view) { updateMaskForm(view); } @Override protected void productSceneViewDeselected(@NonNull ProductSceneView view) { updateMaskForm(getSelectedProductSceneView()); } protected abstract MaskForm createMaskForm(ToolTopComponent topComponent, ListSelectionListener selectionListener); protected abstract String getTitle(); }
4,751
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskViewerTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskViewerTopComponent.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.rcp.windows.ToolTopComponent; import javax.swing.event.ListSelectionListener; public class MaskViewerTopComponent extends MaskToolTopComponent { public static final String ID = MaskViewerTopComponent.class.getName(); @Override protected MaskForm createMaskForm(ToolTopComponent topComponent, ListSelectionListener selectionListener) { return new MaskViewerForm(selectionListener); } @Override protected String getTitle() { return "Mask Viewer"; } }
1,270
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskForm.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.RasterDataNode; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.JPanel; import javax.swing.JTable; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; abstract class MaskForm { private final MaskTable maskTable; protected MaskForm(boolean maskManagmentMode, ListSelectionListener selectionListener) { maskTable = new MaskTable(maskManagmentMode); maskTable.getSelectionModel().addListSelectionListener(selectionListener); maskTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { updateState(); } }); maskTable.getModel().addTableModelListener(new TableModelListener() { @Override public void tableChanged(TableModelEvent e) { updateState(); } }); maskTable.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { if (e.getClickCount() == 2) { Action action = getDoubleClickAction(); if (action.isEnabled()) { action.actionPerformed(new ActionEvent(e.getSource(), e.getID(), null)); } } } }); } public JTable getMaskTable() { return maskTable; } public Action getDoubleClickAction() { return null; } public AbstractButton getHelpButton() { return null; } public void updateState() { } public abstract JPanel createContentPanel(); public Product getProduct() { return maskTable.getProduct(); } public RasterDataNode getRaster() { return maskTable.getModel().getVisibleBand(); } public Mask getSelectedMask() { return maskTable.getSelectedMask(); } public Mask[] getSelectedMasks() { return maskTable.getSelectedMasks(); } public Mask getMask(int rowIndex) { return maskTable.getMask(rowIndex); } public void addMask(Mask mask) { maskTable.addMask(mask); } public void insertMask(Mask mask, int index) { maskTable.insertMask(mask, index); } public void removeMask(Mask mask) { maskTable.removeMask(mask); } public boolean isInManagementMode() { return maskTable.isInManagmentMode(); } public int getSelectedRowCount() { return maskTable.getSelectedRowCount(); } public int getSelectedRow() { return maskTable.getSelectedRow(); } public void setSelectedRow(int rowIndex) { maskTable.getSelectionModel().setSelectionInterval(rowIndex, rowIndex); } public int getRowCount() { return maskTable.getRowCount(); } void reconfigureMaskTable(Product product, RasterDataNode visibleBand) { maskTable.setProduct(product, visibleBand); } void clearMaskTable() { maskTable.clear(); } Dimension getTargetMaskSize() { RasterDataNode raster = getRaster(); if (raster != null) { return new Dimension(raster.getRasterWidth(), raster.getRasterHeight()); } Product product = getProduct(); if (product != null) { return new Dimension(product.getSceneRasterWidth(), product.getSceneRasterHeight()); } return null; } }
4,631
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ComputeMaskAreaAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/ComputeMaskAreaAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.glevel.MultiLevelImage; import com.bc.ceres.swing.progress.DialogProgressMonitor; import org.esa.snap.core.datamodel.GeoCoding; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.util.AreaCalculator; import org.esa.snap.core.util.Debug; 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.GridBagUtils; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.product.ProductSceneView; 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.BoxLayout; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingWorker; import java.awt.BorderLayout; import java.awt.Dialog; import java.awt.GridBagConstraints; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; @ActionID(category = "Tools", id = "ComputeMaskAreaAction") @ActionRegistration( displayName = "#CTL_ComputeMaskAreaAction_MenuText", popupText = "#CTL_ComputeMaskAreaAction_ShortDescription", lazy = false ) @ActionReference(path = "Menu/Raster/Masks", position = 300) @NbBundle.Messages({ "CTL_ComputeMaskAreaAction_MenuText=Mask Area...", "CTL_ComputeMaskAreaAction_DialogTitle=Compute Mask Area", "CTL_ComputeMaskAreaAction_ShortDescription=Displays information about the spatial area of the mask." }) public class ComputeMaskAreaAction extends AbstractAction implements LookupListener, ContextAwareAction, HelpCtx.Provider { private static final String HELP_ID = "computeMaskArea"; private final Lookup lookup; private Lookup.Result<ProductSceneView> result; public ComputeMaskAreaAction() { this(Utilities.actionsGlobalContext()); } public ComputeMaskAreaAction(Lookup lookup) { super(Bundle.CTL_ComputeMaskAreaAction_MenuText()); this.lookup = lookup; result = lookup.lookupResult(ProductSceneView.class); result.addLookupListener(WeakListeners.create(LookupListener.class, this, result)); setEnableState(); } private void setEnableState() { setEnabled(lookup.lookup(ProductSceneView.class) != null); } @Override public void actionPerformed(ActionEvent event) { computeMaskArea(); } private void computeMaskArea() { final String errMsgBase = "Failed to compute Mask area:\n"; // Get selected Snap view showing a product's band final ProductSceneView view = lookup.lookup(ProductSceneView.class); if (view == null) { Dialogs.showError(Bundle.CTL_ComputeMaskAreaAction_DialogTitle(), errMsgBase + "No view."); return; } // Get the current raster data node (band or tie-point grid) RasterDataNode raster = view.getRaster(); assert raster != null; Product product = raster.getProduct(); final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup(); final List<String> maskNameList = new ArrayList<>(); for (int i = 0; i < maskGroup.getNodeCount(); i++) { final Mask mask = maskGroup.get(i); //todo [multisize_products] ask about scenerastertransform, not size if ((raster.getRasterSize().equals(mask.getRasterSize()))) { maskNameList.add(mask.getName()); } } String[] maskNames = maskNameList.toArray(new String[maskNameList.size()]); String maskName; if (maskNames.length == 0) { Dialogs.showInformation(Bundle.CTL_ComputeMaskAreaAction_DialogTitle(), "No compatible mask available", null); return; } else if (maskNames.length == 1) { maskName = maskNames[0]; } else { JPanel selectPanel = new JPanel(); selectPanel.setLayout(new BoxLayout(selectPanel, BoxLayout.X_AXIS)); selectPanel.add(new JLabel("Select Mask: ")); JComboBox<String> maskCombo = new JComboBox<>(maskNames); selectPanel.add(maskCombo); JPanel dialogPanel = selectPanel; if (product.isMultiSize()) { final JPanel wrapperPanel = new JPanel(new BorderLayout(4, 3)); wrapperPanel.add(selectPanel, BorderLayout.CENTER); wrapperPanel.add(new JLabel("<html><i>Product has rasters of different size. <br/>Only compatible masks are shown.</i>"), BorderLayout.SOUTH); dialogPanel = wrapperPanel; } ModalDialog modalDialog = new ModalDialog(SnapApp.getDefault().getMainFrame(), Bundle.CTL_ComputeMaskAreaAction_DialogTitle(), dialogPanel, ModalDialog.ID_OK_CANCEL | ModalDialog.ID_HELP, getHelpCtx().getHelpID()); if (modalDialog.show() == AbstractDialog.ID_OK) { maskName = (String) maskCombo.getSelectedItem(); if (maskName == null) { return; } } else { return; } } final Mask mask = maskGroup.get(maskName); RenderedImage maskImage = mask.getSourceImage(); if (maskImage == null) { Dialogs.showError(Bundle.CTL_ComputeMaskAreaAction_DialogTitle(), errMsgBase + "No Mask image available."); return; } final SwingWorker<MaskAreaStatistics, Object> swingWorker = new MaskAreaSwingWorker(mask, errMsgBase); swingWorker.execute(); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new ComputeMaskAreaAction(actionContext); } @Override public void resultChanged(LookupEvent ev) { setEnableState(); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(HELP_ID); } private static class MaskAreaStatistics { private double earthRadius; private double maskArea; private double pixelAreaMin; private double pixelAreaMax; private int numPixels; private MaskAreaStatistics(double earthRadius) { this.earthRadius = earthRadius; maskArea = 0.0; pixelAreaMax = Double.NEGATIVE_INFINITY; pixelAreaMin = Double.POSITIVE_INFINITY; numPixels = 0; } public double getEarthRadius() { return earthRadius; } public double getMaskArea() { return maskArea; } public void setMaskArea(double maskArea) { this.maskArea = maskArea; } public double getPixelAreaMin() { return pixelAreaMin; } public void setPixelAreaMin(double pixelAreaMin) { this.pixelAreaMin = pixelAreaMin; } public double getPixelAreaMax() { return pixelAreaMax; } public void setPixelAreaMax(double pixelAreaMax) { this.pixelAreaMax = pixelAreaMax; } public int getNumPixels() { return numPixels; } public void setNumPixels(int numPixels) { this.numPixels = numPixels; } } private class MaskAreaSwingWorker extends SwingWorker<MaskAreaStatistics, Object> { private final RasterDataNode mask; private final String errMsgBase; private MaskAreaSwingWorker(RasterDataNode mask, String errMsgBase) { this.mask = mask; this.errMsgBase = errMsgBase; } @Override protected MaskAreaStatistics doInBackground() throws Exception { ProgressMonitor pm = new DialogProgressMonitor(SnapApp.getDefault().getMainFrame(), "Computing Mask area", Dialog.ModalityType.APPLICATION_MODAL); return computeMaskAreaStatistics(pm); } private MaskAreaStatistics computeMaskAreaStatistics(ProgressMonitor pm) { final MultiLevelImage maskImage = mask.getSourceImage(); final int minTileX = maskImage.getMinTileX(); final int minTileY = maskImage.getMinTileY(); final int numXTiles = maskImage.getNumXTiles(); final int numYTiles = maskImage.getNumYTiles(); final int w = mask.getRasterWidth(); final int h = mask.getRasterHeight(); final Rectangle imageRect = new Rectangle(0, 0, w, h); final PixelPos[] pixelPoints = new PixelPos[5]; final GeoPos[] geoPoints = new GeoPos[5]; for (int i = 0; i < geoPoints.length; i++) { pixelPoints[i] = new PixelPos(); geoPoints[i] = new GeoPos(); } GeoCoding geoCoding = mask.getGeoCoding(); AreaCalculator areaCalculator = new AreaCalculator(geoCoding); MaskAreaStatistics areaStatistics = new MaskAreaStatistics(areaCalculator.getEarthRadius() / 1000.0); pm.beginTask("Computing Mask area...", numXTiles * numYTiles); try { for (int tileX = minTileX; tileX < minTileX + numXTiles; ++tileX) { for (int tileY = minTileY; tileY < minTileY + numYTiles; ++tileY) { if (pm.isCanceled()) { break; } 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) { double pixelArea = areaCalculator.calculatePixelSize(x, y) / Math.pow(1000.0, 2); areaStatistics.setPixelAreaMin(Math.min(areaStatistics.getPixelAreaMin(), pixelArea)); areaStatistics.setPixelAreaMax(Math.max(areaStatistics.getPixelAreaMax(), pixelArea)); areaStatistics.setMaskArea(areaStatistics.getMaskArea() + pixelArea); areaStatistics.setNumPixels(areaStatistics.getNumPixels() + 1); } } } } pm.worked(1); } } } finally { pm.done(); } return areaStatistics; } @Override public void done() { try { final MaskAreaStatistics areaStatistics = get(); if (areaStatistics.getNumPixels() == 0) { final String message = MessageFormat.format("{0}Mask is empty.", errMsgBase); Dialogs.showError(Bundle.CTL_ComputeMaskAreaAction_DialogTitle(), message); } else { showResults(areaStatistics); } } catch (ExecutionException | InterruptedException e) { final String message = MessageFormat.format("An internal Error occurred:\n{0}", e.getMessage()); Dialogs.showError(Bundle.CTL_ComputeMaskAreaAction_DialogTitle(), message); Debug.trace(e); } } private void showResults(MaskAreaStatistics areaStatistics) { final double roundFactor = 10000.0; final double maskAreaR = MathUtils.round(areaStatistics.getMaskArea(), roundFactor); final double meanPixelAreaR = MathUtils.round(areaStatistics.getMaskArea() / areaStatistics.getNumPixels(), roundFactor); final double pixelAreaMinR = MathUtils.round(areaStatistics.getPixelAreaMin(), roundFactor); final double pixelAreaMaxR = MathUtils.round(areaStatistics.getPixelAreaMax(), roundFactor); final JPanel content = GridBagUtils.createPanel(); final GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.WEST; gbc.insets.right = 4; gbc.gridy = 0; gbc.weightx = 0; gbc.insets.top = 2; addField(content, gbc, "Number of Mask pixels:", String.format("%15d", areaStatistics.getNumPixels()), ""); addField(content, gbc, "Mask area:", String.format("%15.3f", maskAreaR), "km^2"); addField(content, gbc, "Mean pixel area:", String.format("%15.3f", meanPixelAreaR), "km^2"); addField(content, gbc, "Minimum pixel area:", String.format("%15.3f", pixelAreaMinR), "km^2"); addField(content, gbc, "Maximum pixel area:", String.format("%15.3f", pixelAreaMaxR), "km^2"); gbc.insets.top = 8; addField(content, gbc, "Mean earth radius:", String.format("%15.3f", areaStatistics.getEarthRadius()), "km"); final ModalDialog dialog = new ModalDialog(SnapApp.getDefault().getMainFrame(), Bundle.CTL_ComputeMaskAreaAction_DialogTitle() + " - " + mask.getDisplayName(), content, ModalDialog.ID_OK | ModalDialog.ID_HELP, getHelpCtx().getHelpID()); dialog.show(); } private void addField(final JPanel content, final GridBagConstraints gbc, final String text, final String value, final String unit) { content.add(new JLabel(text), gbc); gbc.weightx = 1; content.add(createTextField(value), gbc); gbc.weightx = 0; content.add(new JLabel(unit), gbc); gbc.gridy++; } private JTextField createTextField(final String value) { JTextField field = new JTextField(value); field.setEditable(false); field.setHorizontalAlignment(JTextField.RIGHT); return field; } } }
16,615
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskTableModel.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.mask; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.ProductNodeListenerAdapter; import org.esa.snap.core.datamodel.RasterDataNode; import javax.swing.table.AbstractTableModel; import java.awt.Color; class MaskTableModel extends AbstractTableModel { private static final int IDX_VISIBILITY = 0; private static final int IDX_NAME = 1; private static final int IDX_TYPE = 2; private static final int IDX_COLOR = 3; private static final int IDX_TRANSPARENCY = 4; private static final int IDX_DESCRIPTION = 5; /** * Mask management mode, no visibility control. */ private static final int[] IDXS_MODE_MANAG_NO_BAND = { IDX_NAME, IDX_TYPE, IDX_COLOR, IDX_TRANSPARENCY, IDX_DESCRIPTION, }; /** * Mask management mode, with visibility control. */ private static final int[] IDXS_MODE_MANAG_BAND = { IDX_VISIBILITY, IDX_NAME, IDX_TYPE, IDX_COLOR, IDX_TRANSPARENCY, IDX_DESCRIPTION, }; /** * List only, no mask type management, no visibility control. */ private static final int[] IDXS_MODE_NO_MANAG_NO_BAND = { IDX_NAME, IDX_COLOR, IDX_TRANSPARENCY, IDX_DESCRIPTION, }; /** * List only, no mask type management, with visibility control. */ private static final int[] IDXS_MODE_NO_MANAG_BAND = { IDX_VISIBILITY, IDX_NAME, IDX_COLOR, IDX_TRANSPARENCY, IDX_DESCRIPTION, }; private static final Class[] COLUMN_CLASSES = { Boolean.class, String.class, String.class, Color.class, Double.class, String.class, }; private static final String[] COLUMN_NAMES = { "Visibility", "Name", "Type", "Colour", "Transparency", "Description", }; private static final boolean[] COLUMN_EDITABLE_STATES = { true, true, false, true, true, true, }; static int[] INITIAL_COLUMN_WIDTHS = { 24, 60, 60, 60, 40, 320, }; private final MaskPNL maskPNL; private final boolean inManagmentMode; private int[] modeIdxs; private Product product; private RasterDataNode visibleBand; private int[] columnWidths; MaskTableModel(boolean inManagmentMode) { this.inManagmentMode = inManagmentMode; updateModeIdxs(); maskPNL = new MaskPNL(); columnWidths = INITIAL_COLUMN_WIDTHS.clone(); } Product getProduct() { return product; } void setProduct(Product product, RasterDataNode visibleBand) { if (this.product != product) { if (this.product != null) { this.product.removeProductNodeListener(maskPNL); } this.product = product; if (this.product != null) { this.product.addProductNodeListener(maskPNL); } } this.visibleBand = visibleBand; updateModeIdxs(); fireTableStructureChanged(); } RasterDataNode getVisibleBand() { return visibleBand; } Mask getMask(int selectedRow) { ProductNodeGroup<Mask> maskGroup = getMaskGroup(); return maskGroup.get(selectedRow); } int getMaskIndex(String name) { return getMaskGroup().indexOf(name); } void addMask(Mask mask) { getProduct().getMaskGroup().add(mask); makeMaskVisible(mask); fireTableDataChanged(); } public void addMask(Mask mask, int index) { getProduct().getMaskGroup().add(index, mask); makeMaskVisible(mask); fireTableDataChanged(); } private void makeMaskVisible(Mask mask) { if (visibleBand != null) { visibleBand.getOverlayMaskGroup().add(mask); } } void removeMask(Mask mask) { getProduct().getMaskGroup().remove(mask); fireTableDataChanged(); } private ProductNodeGroup<Mask> getMaskGroup() { if (product == null) { return null; } else if (visibleBand == null) { return product.getMaskGroup(); } else { final ProductNodeGroup<Mask> visibleMasks = new ProductNodeGroup<Mask>("Masks for " + visibleBand.getName()); final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup(); for (int i = 0; i < maskGroup.getNodeCount(); i++) { final Mask mask = maskGroup.get(i); // todo - [multisize_products] fix: ask ImageGeometry whether mask and band have the same scenerastertransform if (mask.getRasterWidth() == visibleBand.getRasterWidth() && mask.getRasterHeight() == visibleBand.getRasterHeight()) { visibleMasks.add(mask); } } return visibleMasks; } } boolean isInManagmentMode() { return product != null && inManagmentMode; } int getVisibilityColumnIndex() { for (int i = 0; i < modeIdxs.length; i++) { if (modeIdxs[i] == IDX_VISIBILITY) { return i; } } return -1; } void setPreferredColumnWidth(int columnIndex, int width) { columnWidths[modeIdxs[columnIndex]] = width; } int getPreferredColumnWidth(int columnIndex) { return columnWidths[modeIdxs[columnIndex]]; } private void updateModeIdxs() { this.modeIdxs = inManagmentMode ? (this.visibleBand != null ? IDXS_MODE_MANAG_BAND : IDXS_MODE_MANAG_NO_BAND) : (this.visibleBand != null ? IDXS_MODE_NO_MANAG_BAND : IDXS_MODE_NO_MANAG_NO_BAND); } void clear() { setProduct(null, null); } ///////////////////////////////////////////////////////////////////////// // TableModel Implementation @Override public Class getColumnClass(int columnIndex) { return COLUMN_CLASSES[modeIdxs[columnIndex]]; } @Override public String getColumnName(int columnIndex) { return COLUMN_NAMES[modeIdxs[columnIndex]]; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return COLUMN_EDITABLE_STATES[modeIdxs[columnIndex]]; } @Override public int getColumnCount() { return modeIdxs.length; } @Override public int getRowCount() { ProductNodeGroup<Mask> maskGroup = getMaskGroup(); return maskGroup != null ? maskGroup.getNodeCount() : 0; } @Override public Object getValueAt(int rowIndex, int columnIndex) { final ProductNodeGroup<Mask> maskGroup = getMaskGroup(); Mask mask = maskGroup.get(rowIndex); int column = modeIdxs[columnIndex]; if (column == IDX_VISIBILITY) { if (visibleBand.getOverlayMaskGroup().contains(mask)) { return Boolean.TRUE; } else { return Boolean.FALSE; } } else if (column == IDX_NAME) { return mask.getName(); } else if (column == IDX_TYPE) { return mask.getImageType().getName(); } else if (column == IDX_COLOR) { return mask.getImageColor(); } else if (column == IDX_TRANSPARENCY) { return mask.getImageTransparency(); } else if (column == IDX_DESCRIPTION) { return mask.getDescription(); } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { final ProductNodeGroup<Mask> maskGroup = getMaskGroup(); Mask mask = maskGroup.get(rowIndex); int column = modeIdxs[columnIndex]; if (column == IDX_VISIBILITY) { boolean visible = (Boolean) aValue; final ProductNodeGroup<Mask> overlayMaskGroup = visibleBand.getOverlayMaskGroup(); if (visible) { if (!overlayMaskGroup.contains(mask)) { overlayMaskGroup.add(mask); } } else { overlayMaskGroup.remove(mask); } visibleBand.fireImageInfoChanged(); fireTableCellUpdated(rowIndex, columnIndex); } else if (column == IDX_NAME) { mask.setName((String) aValue); fireTableCellUpdated(rowIndex, columnIndex); } else if (column == IDX_TYPE) { // type is not editable! } else if (column == IDX_COLOR) { mask.setImageColor((Color) aValue); fireTableCellUpdated(rowIndex, columnIndex); } else if (column == IDX_TRANSPARENCY) { mask.setImageTransparency((Double) aValue); fireTableCellUpdated(rowIndex, columnIndex); } else if (column == IDX_DESCRIPTION) { mask.setDescription((String) aValue); fireTableCellUpdated(rowIndex, columnIndex); } } private class MaskPNL extends ProductNodeListenerAdapter { @Override public void nodeAdded(ProductNodeEvent event) { processEvent(event); } @Override public void nodeRemoved(ProductNodeEvent event) { processEvent(event); } @Override public void nodeChanged(ProductNodeEvent event) { processEvent(event); } private void processEvent(ProductNodeEvent event) { if (event.getSourceNode() instanceof Mask) { fireTableDataChanged(); } else if (event.getSourceNode() instanceof Placemark) { fireTableDataChanged(); } else if (event.getSourceNode() == visibleBand && event.getPropertyName() != null && event.getPropertyName().equals(RasterDataNode.PROPERTY_NAME_IMAGE_INFO)) { fireTableDataChanged(); } } } }
11,190
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskFormActions.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskFormActions.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.mask; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.glevel.MultiLevelImage; import com.bc.ceres.grender.Viewport; import org.esa.snap.core.dataio.dimap.DimapProductConstants; import org.esa.snap.core.dataio.dimap.spi.DimapPersistable; import org.esa.snap.core.dataio.dimap.spi.DimapPersistence; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.datamodel.Mask.ImageType; import org.esa.snap.core.dataop.barithm.BandArithmetic; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.jexp.ParseException; import org.esa.snap.core.jexp.impl.Tokenizer; import org.esa.snap.core.util.DefaultPropertyMap; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.core.util.PropertyMap; 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.actions.vector.CreateVectorDataNodeAction; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.rcp.util.MultiSizeIssue; import org.esa.snap.rcp.util.internal.RasterDataNodeDeleter; import org.esa.snap.rcp.windows.ToolTopComponent; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.SnapFileChooser; import org.esa.snap.ui.product.ProductExpressionPane; import org.esa.snap.ui.product.ProductSceneView; import org.geotools.geometry.jts.ReferencedEnvelope; import org.jdom2.Document; import org.jdom2.Element; import org.jdom2.input.SAXBuilder; import org.jdom2.output.Format; import org.jdom2.output.XMLOutputter; import org.openide.windows.TopComponent; import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.List; import java.util.*; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.VIEW; /** * @author Marco Peters * @since BEAM 4.7 */ class MaskFormActions { private final MaskAction[] maskActions; MaskFormActions(ToolTopComponent maskTopComponent, MaskForm maskForm) { maskActions = new MaskAction[]{ new NewBandMathsAction(maskForm), new NewRangeAction(maskForm), new NewVectorDataNodeAction(maskForm), new NullAction(maskForm), new NewUnionAction(maskForm), new NewIntersectionAction(maskForm), new NewDifferenceAction(maskForm), new NewInvDifferenceAction(maskForm), new NewComplementAction(maskForm), new NullAction(maskForm), new CopyAction(maskForm), new EditAction(maskForm), new RemoveAction(maskForm), new TransferAction(maskForm), new ImportAction(maskTopComponent, maskForm), new ExportAction(maskTopComponent, maskForm), new ZoomToVectorMaskAction(maskTopComponent, maskForm), new NullAction(maskForm), }; } private MaskAction getMaskAction(Class<?> type) { for (MaskAction maskAction : maskActions) { if (type.getName().equals(maskAction.getValue(Action.ACTION_COMMAND_KEY))) { return maskAction; } } return null; } public MaskAction[] getAllActions() { return maskActions.clone(); } public MaskAction getNewBandMathAction() { return getMaskAction(NewBandMathsAction.class); } public MaskAction getNewRangeAction() { return getMaskAction(NewRangeAction.class); } public MaskAction getNewIntersectionAction() { return getMaskAction(NewIntersectionAction.class); } public MaskAction getNewSubtractionAction() { return getMaskAction(NewDifferenceAction.class); } public MaskAction getNewUnionAction() { return getMaskAction(NewUnionAction.class); } public MaskAction getNewInversionAction() { return getMaskAction(NewComplementAction.class); } public MaskAction getCopyAction() { return getMaskAction(CopyAction.class); } public MaskAction getEditAction() { return getMaskAction(EditAction.class); } public MaskAction getExportAction() { return getMaskAction(ExportAction.class); } public MaskAction getImportAction() { return getMaskAction(ImportAction.class); } public MaskAction getRemoveAction() { return getMaskAction(RemoveAction.class); } public MaskAction getNullAction() { return getMaskAction(NullAction.class); } private static class NewBandMathsAction extends BandMathsAction { private NewBandMathsAction(MaskForm maskForm) { super(maskForm, "BandMath24.png", "bandMathButton", "Creates a new mask based on a logical band maths expression"); } @Override String getCode(ActionEvent e) { Product product = getMaskForm().getProduct(); ProductExpressionPane expressionPane = ProductExpressionPane.createBooleanExpressionPane( new Product[]{product}, product, null); expressionPane.setEmptyExpressionAllowed(false); expressionPane.setCode(""); if (expressionPane.showModalDialog(null, "New Logical Band Maths Expression") == AbstractDialog.ID_OK) { final String code = expressionPane.getCode(); if (!code.isEmpty()) { return code; } } return null; } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode()); } } private static class NewVectorDataNodeAction extends MaskAction { private CreateVectorDataNodeAction action; private NewVectorDataNodeAction(MaskForm maskForm) { super(maskForm, "icons/NewVectorDataNode24.gif", "newGeometry", "Creates a new mask based on a new geometry container (lines and polygons))"); action = new CreateVectorDataNodeAction(); } @Override void updateState() { final boolean enabled = SnapApp.getDefault().getSelectedProduct(VIEW) != null; action.setEnabled(enabled); setEnabled(enabled); } @Override public void actionPerformed(ActionEvent e) { action.actionPerformed(e); } } private static class NewIntersectionAction extends BandMathsAction { private NewIntersectionAction(MaskForm maskForm) { super(maskForm, "Intersection24.png", "intersectionButton", "Creates the intersection of the selected masks"); } @Override String getCode(ActionEvent e) { return createCodeFromSelection("&&"); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() > 1); } } private static class NewComplementAction extends BandMathsAction { private NewComplementAction(MaskForm maskForm) { super(maskForm, "Complement24.png", "complementButton", "Creates the complement (of the union) of the selected mask(s)"); } @Override String getCode(ActionEvent e) { Mask[] selectedMasks = getMaskForm().getSelectedMasks(); return "!(" + createCodeFromSelection("||", selectedMasks, 0) + ")"; } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() >= 1); } } private static class NewRangeAction extends MaskAction { private NewRangeAction(MaskForm maskForm) { super(maskForm, "Range24.png", "rangeButton", "Creates a new mask based on a value range"); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode()); } @Override public void actionPerformed(ActionEvent e) { final String[] rasterNames = collectNamesOfRastersOfSameSize(); final RangeEditorDialog.Model model = new RangeEditorDialog.Model(rasterNames); model.setMinValue(0.0); model.setMaxValue(1.0); model.setRasterName(rasterNames[0]); final RangeEditorDialog rangeEditorDialog = new RangeEditorDialog(getWindow(e), model); if (rangeEditorDialog.show() == AbstractDialog.ID_OK) { RasterDataNode referencedRaster = getMaskForm().getProduct().getRasterDataNode(model.getRasterName()); if (referencedRaster == null) { Dialogs.showError(String.format("Raster '%s' not found.", model.getRasterName())); return; } Dimension expectedSize = getMaskForm().getTargetMaskSize(); if (expectedSize != null && !ProductUtils.areRastersEqualInSize(expectedSize.width, expectedSize.height, referencedRaster)) { String message = String.format("'%s' does not have the expected size of %d x %d pixels.", model.getRasterName(), expectedSize.width, expectedSize.height); Dialogs.showError(message); return; } Mask mask = createNewMask(Mask.RangeType.INSTANCE); String externalName = Tokenizer.createExternalName(model.getRasterName()); mask.setDescription(model.getMinValue() + " <= " + externalName + " <= " + model.getMaxValue()); PropertyContainer imageConfig = mask.getImageConfig(); imageConfig.setValue(Mask.RangeType.PROPERTY_NAME_MINIMUM, model.getMinValue()); imageConfig.setValue(Mask.RangeType.PROPERTY_NAME_MAXIMUM, model.getMaxValue()); imageConfig.setValue(Mask.RangeType.PROPERTY_NAME_RASTER, externalName); imageConfig.addPropertyChangeListener(evt -> { String oldText = evt.getOldValue().toString(); String newText = evt.getNewValue().toString(); mask.setDescription(mask.getDescription().replace(oldText, newText)); }); getMaskForm().addMask(mask); } } } private static class NewDifferenceAction extends BandMathsAction { private NewDifferenceAction(MaskForm maskForm) { super(maskForm, "Difference24.png", "differenceButton", "Creates the difference of the selected masks (in top-down order)"); } @Override String getCode(ActionEvent e) { Mask[] selectedMasks = getMaskForm().getSelectedMasks(); StringBuilder code = new StringBuilder(); code.append(BandArithmetic.createExternalName(selectedMasks[0].getName())); if (selectedMasks.length > 1) { code.append(" && !("); code.append(createCodeFromSelection("||", selectedMasks, 1)); code.append(")"); } return code.toString(); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() > 1); } } private static class NewInvDifferenceAction extends BandMathsAction { private NewInvDifferenceAction(MaskForm maskForm) { super(maskForm, "InvDifference24.png", "invDifferenceButton", "Creates the difference of the selected masks (in bottom-up order)"); } @Override String getCode(ActionEvent e) { Mask[] selectedMasks = getMaskForm().getSelectedMasks(); List<Mask> reverseList = new ArrayList<>(Arrays.asList(selectedMasks)); Collections.reverse(reverseList); selectedMasks = reverseList.toArray(new Mask[selectedMasks.length]); StringBuilder code = new StringBuilder(); code.append(BandArithmetic.createExternalName(selectedMasks[0].getName())); if (selectedMasks.length > 1) { code.append(" && !("); code.append(createCodeFromSelection("||", selectedMasks, 1)); code.append(")"); } return code.toString(); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() > 1); } } private static class NewUnionAction extends BandMathsAction { private NewUnionAction(MaskForm maskForm) { super(maskForm, "Union24.png", "unionButton", "Creates the union of the selected masks"); } @Override String getCode(ActionEvent e) { return createCodeFromSelection("||"); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() > 1); } } private static class NullAction extends MaskAction { private NullAction(MaskForm maskForm) { super(maskForm, "", "", ""); } @Override JComponent createComponent() { return new JPanel(); } @Override public void actionPerformed(ActionEvent e) { } } private static class RemoveAction extends MaskAction { private RemoveAction(MaskForm maskForm) { super(maskForm, "icons/Remove24.gif", "removeButton", "Remove the selected mask."); } @Override public void actionPerformed(ActionEvent e) { Mask[] selectedMasks = getMaskForm().getSelectedMasks(); getMaskForm().getMaskTable().clearSelection(); RasterDataNodeDeleter.deleteRasterDataNodes(selectedMasks); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() > 0); } } private static class ImportAction extends MaskIOAction { private final TopComponent maskTopComponent; private ImportAction(TopComponent maskTopComponent, MaskForm maskForm) { super(maskTopComponent, maskForm, "icons/Import24.gif", "importButton", "Import masks from file."); this.maskTopComponent = maskTopComponent; } @Override public void actionPerformed(ActionEvent e) { importMasks(); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode()); } private void importMasks() { final JFileChooser fileChooser = new SnapFileChooser(); fileChooser.setDialogTitle("Import Masks from file"); final FileFilter bmdFilter = new SnapFileFilter("BITMASK_DEFINITION_FILE", ".bmd", "Bitmask definition files (*.bmd)"); fileChooser.addChoosableFileFilter(bmdFilter); final FileFilter bmdxFilter = new SnapFileFilter("BITMASK_DEFINITION_FILE_XML", ".bmdx", "Bitmask definition xml files (*.bmdx)"); fileChooser.addChoosableFileFilter(bmdxFilter); final FileFilter xmlFilter = new SnapFileFilter("XML", ".xml", "XML files (*.xml)"); fileChooser.setFileFilter(xmlFilter); fileChooser.setCurrentDirectory(getDirectory()); fileChooser.setMultiSelectionEnabled(true); if (fileChooser.showOpenDialog(SwingUtilities.getWindowAncestor(maskTopComponent)) == JFileChooser.APPROVE_OPTION) { final File file = fileChooser.getSelectedFile(); if (file != null) { setDirectory(file.getAbsoluteFile().getParentFile()); if (file.canRead()) { if (bmdFilter.accept(file)) { importMaskFromBmd(file); } else if (bmdxFilter.accept(file)) { importMasksFromBmdx(file); } else { importMasksFromXml(file); } } } } } private void importMaskFromBmd(File file) { final PropertyMap propertyMap = new DefaultPropertyMap(); try { propertyMap.load(file.toPath()); // Overwrite existing values final String name = propertyMap.getPropertyString("bitmaskName", "bitmask"); final String description = propertyMap.getPropertyString("bitmaskDesc", null); final String expression = propertyMap.getPropertyString("bitmaskExpr", ""); final Color color = propertyMap.getPropertyColor("bitmaskColor", Color.yellow); final double transparency = propertyMap.getPropertyDouble("bitmaskTransparency", 0.5); final Product product = getMaskForm().getProduct(); product.addMask(name, expression, description, color, transparency); } catch (Exception e) { showErrorDialog(String.format("Failed to import mask(s): %s", e.getMessage())); } } private void importMasksFromBmdx(File file) { try { final SAXBuilder saxBuilder = new SAXBuilder(); final Document document = saxBuilder.build(file); final Element rootElement = document.getRootElement(); @SuppressWarnings({"unchecked"}) final List<Element> children = rootElement.getChildren(DimapProductConstants.TAG_BITMASK_DEFINITION); final Product product = getMaskForm().getProduct(); for (Element element : children) { Mask mask = Mask.BandMathsType.createFromBitmaskDef(element, product.getSceneRasterWidth(), product.getSceneRasterHeight()); product.getMaskGroup().add(mask); } } catch (Exception e) { showErrorDialog(String.format("Failed to import mask(s): %s", e.getMessage())); } } private void importMasksFromXml(File file) { try { final SAXBuilder saxBuilder = new SAXBuilder(); final Document document = saxBuilder.build(file); final Element rootElement = document.getRootElement(); @SuppressWarnings({"unchecked"}) final List<Element> children = rootElement.getChildren(DimapProductConstants.TAG_MASK); final Product product = getMaskForm().getProduct(); for (final Element child : children) { final DimapPersistable persistable = DimapPersistence.getPersistable(child); if (persistable != null) { final Mask mask = (Mask) persistable.createObjectFromXml(child, product); addMaskToProductIfPossible(mask, product); } } } catch (Exception e) { showErrorDialog(String.format("Failed to import mask(s): %s", e.getMessage())); } } private void addMaskToProductIfPossible(Mask mask, Product product) throws Exception { if (mask.getImageType().canTransferMask(mask, product)) { product.getMaskGroup().add(mask); } else { throw new Exception(String.format("Cannot add mask '%s' to selected product.", mask.getName())); } } } private static class ExportAction extends MaskIOAction { private static final String ACTION_NAME = "Export mask definition(s) to XML file."; private final TopComponent maskTopComponent; private ExportAction(TopComponent maskTopComponent, MaskForm maskForm) { super(maskTopComponent, maskForm, "icons/Export24.gif", "exportButton", ACTION_NAME); this.maskTopComponent = maskTopComponent; } @Override public void actionPerformed(ActionEvent e) { exportSelectedMasks(); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() > 0); } private void exportSelectedMasks() { final Mask[] masks = getMaskForm().getSelectedMasks(); if (masks.length == 0) { return; } Document document = new Document(new Element(DimapProductConstants.TAG_MASKS)); boolean[] masksExported = addContent(masks, document); boolean dialogApproved = false; if (hasAtLeastOneMaskExported(masksExported)) { final JFileChooser fileChooser = new SnapFileChooser(); fileChooser.setDialogTitle(ACTION_NAME); final FileFilter fileFilter = new SnapFileFilter("XML", ".xml", "XML files (*.xml)"); fileChooser.setFileFilter(fileFilter); final File targetDirectory = getDirectory(); fileChooser.setCurrentDirectory(targetDirectory); fileChooser.setSelectedFile(new File(targetDirectory, masks[0].getName())); final int result = fileChooser.showSaveDialog(SwingUtilities.getWindowAncestor(maskTopComponent)); dialogApproved = result == JFileChooser.APPROVE_OPTION; if (dialogApproved) { File file = fileChooser.getSelectedFile(); if (file != null) { if (Boolean.TRUE.equals(Dialogs.requestOverwriteDecision(ACTION_NAME, file))) { setDirectory(file.getAbsoluteFile().getParentFile()); file = FileUtils.ensureExtension(file, ".xml"); writeXml(file, document); } } } } boolean allExportsFailed = countFailedMasks(masksExported) == masksExported.length; if (dialogApproved || allExportsFailed) { showUserFeedback(masks, masksExported); } } private void showUserFeedback(Mask[] masks, boolean[] masksExported) { StringBuilder stringBuilder = new StringBuilder(); if (countExportedMasks(masksExported) > 0) { stringBuilder.append("Successfully exported mask"); if (countExportedMasks(masksExported) > 1) { stringBuilder.append("s"); } stringBuilder.append(" "); int maskIndex = 0; for (int i = 0; i < masks.length; i++) { final Mask mask = masks[i]; if (masksExported[i]) { addMaskName(stringBuilder, maskIndex++, mask.getName(), countExportedMasks(masksExported)); } } stringBuilder.append("."); } if (countFailedMasks(masksExported) > 0) { stringBuilder.append("\n"); stringBuilder.append("Unable to export mask"); if (countFailedMasks(masksExported) > 1) { stringBuilder.append("s"); } stringBuilder.append(" "); int maskIndex = 0; for (int i = 0; i < masks.length; i++) { final Mask mask = masks[i]; if (!masksExported[i]) { addMaskName(stringBuilder, maskIndex++, mask.getName(), countFailedMasks(masksExported)); } } stringBuilder.append(" to XML."); } Dialogs.showInformation(ACTION_NAME, stringBuilder.toString(), null); } private static int countExportedMasks(boolean[] masksExported) { int exportedMaskCount = 0; for (boolean maskExported : masksExported) { if (maskExported) { exportedMaskCount++; } } return exportedMaskCount; } private static int countFailedMasks(boolean[] masksExported) { int exportedMaskCount = 0; for (boolean maskExported : masksExported) { if (!maskExported) { exportedMaskCount++; } } return exportedMaskCount; } private static void addMaskName(StringBuilder stringBuilder, int index, String maskName, int maskCount) { if (maskCount < 2) { stringBuilder.append(maskName); } else if (index < maskCount - 2) { stringBuilder.append(maskName); stringBuilder.append(", "); } else if (index < maskCount - 1) { stringBuilder.append(maskName); stringBuilder.append(" "); } else if (index == maskCount - 1) { stringBuilder.append("and "); stringBuilder.append(maskName); } } private static boolean hasAtLeastOneMaskExported(boolean[] masksExported) { for (boolean maskExported : masksExported) { if (maskExported) { return true; } } return false; } private boolean[] addContent(Mask[] masks, Document document) { boolean[] masksExported = new boolean[masks.length]; for (int i = 0; i < masks.length; i++) { final Mask mask = masks[i]; final DimapPersistable persistable = DimapPersistence.getPersistable(mask); if (persistable != null) { final Element element = persistable.createXmlFromObject(mask); document.getRootElement().addContent(element); masksExported[i] = true; } } return masksExported; } private void writeXml(File file, Document document) { FileWriter writer = null; try { writer = new FileWriter(file); final Format format = Format.getPrettyFormat(); final XMLOutputter outputter = new XMLOutputter(format); outputter.output(document, writer); } catch (IOException e) { showErrorDialog("Failed to export mask(s): " + e.getMessage()); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { // ignore } } } } } static Window getWindow(ActionEvent e) { Object source = e.getSource(); Window window = null; if (source instanceof Component) { Component component = (Component) source; window = SwingUtilities.getWindowAncestor(component); } return window; } private static class EditAction extends MaskAction { private EditAction(MaskForm maskForm) { super(maskForm, "icons/Edit24.gif", "editButton", "Edit the selected mask."); } @Override public void actionPerformed(ActionEvent e) { Window window = getWindow(e); Mask selectedMask = getMaskForm().getSelectedMask(); PropertyContainer selectedMaskConfig = selectedMask.getImageConfig(); ImageType type = selectedMask.getImageType(); if (type == Mask.BandMathsType.INSTANCE) { Product product = getMaskForm().getProduct(); ProductExpressionPane expressionPane = ProductExpressionPane.createBooleanExpressionPane( new Product[]{product}, product, null); expressionPane.setEmptyExpressionAllowed(false); expressionPane.setCode(selectedMaskConfig.getValue("expression")); if (expressionPane.showModalDialog(window, "Edit Band Maths Mask") == AbstractDialog.ID_OK) { String code = expressionPane.getCode(); selectedMaskConfig.setValue("expression", code); selectedMask.setDescription(code); } } else if (type == Mask.RangeType.INSTANCE) { final String[] namesOfRastersOfSameSize = collectNamesOfRastersOfSameSize(); final RangeEditorDialog.Model model = new RangeEditorDialog.Model(namesOfRastersOfSameSize); model.setMinValue(selectedMaskConfig.getValue(Mask.RangeType.PROPERTY_NAME_MINIMUM)); model.setMaxValue(selectedMaskConfig.getValue(Mask.RangeType.PROPERTY_NAME_MAXIMUM)); model.setRasterName(selectedMaskConfig.getValue(Mask.RangeType.PROPERTY_NAME_RASTER)); final RangeEditorDialog rangeEditorDialog = new RangeEditorDialog(window, model); if (rangeEditorDialog.show() == AbstractDialog.ID_OK) { final String description = String.format("%s <= %s <= %s", model.getMinValue(), model.getRasterName(), model.getMaxValue()); selectedMask.setDescription(description); selectedMaskConfig.setValue(Mask.RangeType.PROPERTY_NAME_MINIMUM, model.getMinValue()); selectedMaskConfig.setValue(Mask.RangeType.PROPERTY_NAME_MAXIMUM, model.getMaxValue()); selectedMaskConfig.setValue(Mask.RangeType.PROPERTY_NAME_RASTER, model.getRasterName()); } } else if (type == Mask.VectorDataType.INSTANCE) { AbstractDialog.showInformationDialog(window, "Use the geometry tools to add new points, lines or polygons.\n" + "You can then use the select tool to select and modify the shape\n" + "and position of the geometries.", "Edit Geometry Mask" ); } else { // todo - implement for other types too } } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() == 1); } } private static class CopyAction extends MaskAction { private CopyAction(MaskForm maskForm) { super(maskForm, "icons/Copy24.gif", "copyButton", "Copy the selected mask."); } @Override public void actionPerformed(ActionEvent e) { Mask selectedMask = getMaskForm().getSelectedMask(); final Mask mask = createNewMask(selectedMask.getImageType()); mask.setName("Copy_of_" + selectedMask.getName()); mask.setDescription(selectedMask.getDescription()); PropertyContainer selectedConfig = selectedMask.getImageConfig(); Property[] models = selectedConfig.getProperties(); for (Property model : models) { mask.getImageConfig().setValue(model.getDescriptor().getName(), model.getValue()); } getMaskForm().addMask(mask); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() == 1); } } private abstract static class BandMathsAction extends MaskAction { BandMathsAction(MaskForm maskForm, String iconPath, String buttonName, String description) { super(maskForm, iconPath, buttonName, description); } @Override public void actionPerformed(ActionEvent e) { String code = getCode(e); if (code != null) { addBandMathMask(code); } } abstract String getCode(ActionEvent e); String createCodeFromSelection(String op) { return createCodeFromSelection(op, 0); } String createCodeFromSelection(String op, int selectionOffset) { return createCodeFromSelection(op, getMaskForm().getSelectedMasks(), selectionOffset); } String createCodeFromSelection(String op, Mask[] selectedMasks, int selectionOffset) { StringBuilder code = new StringBuilder(); for (int i = selectionOffset; i < selectedMasks.length; i++) { Mask mask = selectedMasks[i]; if (code.length() > 0) { code.append(" "); code.append(op); code.append(" "); } code.append(BandArithmetic.createExternalName(mask.getName())); } return code.toString(); } void addBandMathMask(String code) { Product product = getMaskForm().getProduct(); RasterDataNode[] refRasters; try { refRasters = BandArithmetic.getRefRasters(code, product); } catch (ParseException e) { Dialogs.showError("Invalid expression '" + code + "':\n" + e.getMessage()); return; } Dimension expectedSize = getMaskForm().getTargetMaskSize(); if (expectedSize != null && !ProductUtils.areRastersEqualInSize(expectedSize.width, expectedSize.height, refRasters)) { String message = String.format("Referenced rasters must all be the same size (%d x %d pixels).", expectedSize.width, expectedSize.height); Dialogs.showError(message); return; } final Mask mask = createNewMask(Mask.BandMathsType.INSTANCE); final PropertyContainer imageConfig = mask.getImageConfig(); final String propertyNameExpression = Mask.BandMathsType.PROPERTY_NAME_EXPRESSION; imageConfig.setValue(propertyNameExpression, code); imageConfig.addPropertyChangeListener(propertyNameExpression, evt -> { if (evt.getOldValue().equals(mask.getDescription())) { mask.setDescription((String) evt.getNewValue()); } }); mask.setDescription(code); getMaskForm().addMask(mask); final RasterDataNode refRaster = getMaskForm().getRaster(); if (refRaster != null) { ProductUtils.copyImageGeometry(refRaster, mask, false); } } } private static class TransferAction extends MaskAction { private TransferAction(MaskForm maskForm) { super(maskForm, "icons/MultiAssignProducts24.gif", "transferButton", "Transfer the selected mask(s) to other products."); } @Override void updateState() { setEnabled(getMaskForm().isInManagementMode() && getMaskForm().getSelectedRowCount() > 0 && SnapApp.getDefault().getProductManager().getProductCount() > 1); } @Override public void actionPerformed(ActionEvent e) { Window window = getWindow(e); final Product sourcProduct = getMaskForm().getProduct(); Mask[] selectedMasks = getMaskForm().getSelectedMasks(); Product[] allProducts = SnapApp.getDefault().getProductManager().getProducts(); final TransferMaskDialog dialog = new TransferMaskDialog(window, sourcProduct, allProducts, selectedMasks); if (dialog.show() == AbstractDialog.ID_OK) { Product[] maskPixelTargetProducts = dialog.getMaskPixelTargets(); copyMaskPixel(selectedMasks, sourcProduct, maskPixelTargetProducts); Product[] maskDefinitionTargetProducts = dialog.getMaskDefinitionTargets(); copyMaskDefinition(selectedMasks, maskDefinitionTargetProducts); } } private static void copyMaskDefinition(Mask[] selectedMasks, Product[] maskPixelTargetProducts) { for (Product targetProduct : maskPixelTargetProducts) { for (Mask selectedMask : selectedMasks) { ImageType imageType = selectedMask.getImageType(); if (imageType.canTransferMask(selectedMask, targetProduct)) { imageType.transferMask(selectedMask, targetProduct); } } } } private static void copyMaskPixel(Mask[] selectedMasks, Product sourceProduct, Product[] maskPixelTargetProducts) { if (MultiSizeIssue.isMultiSize(sourceProduct)) { final Product resampledProduct = MultiSizeIssue.maybeResample(sourceProduct); if (resampledProduct != null) { sourceProduct = resampledProduct; for (int i = 0; i < selectedMasks.length; i++) { Mask selectedMask = selectedMasks[i]; selectedMasks[i] = sourceProduct.getMaskGroup().get(selectedMask.getName()); } } else { return; } } for (Product targetProduct : maskPixelTargetProducts) { if (sourceProduct.isCompatibleProduct(targetProduct, 1.0e-3f)) { copyBandData(selectedMasks, targetProduct); } else { reprojectBandData(selectedMasks, sourceProduct, targetProduct); } } } private static void copyBandData(Mask[] selectedMasks, Product targetProduct) { for (Mask mask : selectedMasks) { Band band = createBandCopy(targetProduct, mask); band.setSourceImage(mask.getSourceImage()); } } private static void reprojectBandData(Mask[] selectedMasks, Product sourceProduct, Product targetProduct) { final Map<String, Object> projParameters = Collections.emptyMap(); Map<String, Product> projProducts = new HashMap<>(); projProducts.put("source", sourceProduct); projProducts.put("collocateWith", targetProduct); Product reprojectedProduct = GPF.createProduct("Reproject", projParameters, projProducts); for (Mask mask : selectedMasks) { Band band = createBandCopy(targetProduct, mask); MultiLevelImage image = reprojectedProduct.getMaskGroup().get(mask.getName()).getSourceImage(); band.setSourceImage(image); } } private static Band createBandCopy(Product targetProduct, Mask mask) { String bandName = ProductUtils.getAvailableNodeName("mask_" + mask.getName(), targetProduct.getBandGroup()); String maskName = ProductUtils.getAvailableNodeName(mask.getName(), targetProduct.getMaskGroup()); int dataType = mask.getDataType(); Band band = targetProduct.addBand(bandName, dataType); String description = mask.getDescription() + " (from " + mask.getProduct().getDisplayName() + ")"; String expression = (String) mask.getImageConfig().getValue("expression"); targetProduct.addMask(maskName, expression, description, mask.getImageColor(), mask.getImageTransparency()); return band; } } private static class ZoomToVectorMaskAction extends MaskAction { private final ToolTopComponent topComponent; private ZoomToVectorMaskAction(ToolTopComponent topComponent, MaskForm maskForm) { super(maskForm, "icons/ZoomTo24.gif", "zoomToButton", "Zooms to the selected mask."); this.topComponent = topComponent; } @Override void updateState() { setEnabled(getMaskForm().getSelectedRowCount() == 1 && topComponent.getSelectedProductSceneView() != null); } @Override public void actionPerformed(ActionEvent e) { Mask mask = getMaskForm().getSelectedMask(); ImageType imageType = mask.getImageType(); ProductSceneView productSceneView = topComponent.getSelectedProductSceneView(); if (productSceneView != null) { Rectangle2D modelBounds; if (imageType == Mask.VectorDataType.INSTANCE) { modelBounds = handleVectorMask(mask); } else { modelBounds = handleImageMask(mask, productSceneView.getBaseImageLayer().getImageToModelTransform()); } if (modelBounds != null) { Viewport viewport = productSceneView.getViewport(); final AffineTransform m2vTransform = viewport.getModelToViewTransform(); final AffineTransform v2mTransform = viewport.getViewToModelTransform(); final Rectangle2D viewBounds = m2vTransform.createTransformedShape(modelBounds).getBounds2D(); viewBounds.setFrameFromDiagonal(viewBounds.getMinX() - 10, viewBounds.getMinY() - 10, viewBounds.getMaxX() + 10, viewBounds.getMaxY() + 10); final Shape transformedModelBounds = v2mTransform.createTransformedShape(viewBounds); viewport.zoom(transformedModelBounds.getBounds2D()); } else { Dialogs.showMessage("Zoom to Mask", "The selected mask is empty.", JOptionPane.INFORMATION_MESSAGE, null); } } } private static Rectangle2D handleVectorMask(Mask mask) { VectorDataNode vectorData = Mask.VectorDataType.getVectorData(mask); ReferencedEnvelope envelope = vectorData.getEnvelope(); if (!envelope.isEmpty()) { return new Rectangle2D.Double(envelope.getMinX(), envelope.getMinY(), envelope.getWidth(), envelope.getHeight()); } return null; } private Rectangle2D handleImageMask(Mask mask, AffineTransform i2m) { RenderedImage image = mask.getSourceImage().getImage(0); final int minTileX = image.getMinTileX(); final int minTileY = image.getMinTileY(); final int numXTiles = image.getNumXTiles(); final int numYTiles = image.getNumYTiles(); final int width = image.getWidth(); final int height = image.getHeight(); int minX = width; int maxX = 0; int minY = height; int maxY = 0; for (int tileX = minTileX; tileX < minTileX + numXTiles; ++tileX) { for (int tileY = minTileY; tileY < minTileY + numYTiles; ++tileY) { final Raster data = image.getTile(tileX, tileY); for (int x = data.getMinX(); x < data.getMinX() + data.getWidth(); x++) { for (int y = data.getMinY(); y < data.getMinY() + data.getHeight(); y++) { if (data.getSample(x, y, 0) != 0) { minX = Math.min(x, minX); maxX = Math.max(x, maxX); minY = Math.min(y, minY); maxY = Math.max(y, maxY); } } } } } Rectangle rect = new Rectangle(minX, minY, maxX - minX + 1, maxY - minY + 1); if (rect.isEmpty()) { return null; } else { return i2m.createTransformedShape(rect).getBounds2D(); } } } }
45,165
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TransferMaskDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/TransferMaskDialog.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.datamodel.GeoCoding; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.GeoUtils; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.ui.ModalDialog; import javax.swing.BorderFactory; import javax.swing.ButtonGroup; import javax.swing.ButtonModel; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JEditorPane; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.SwingConstants; import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Window; import java.awt.geom.GeneralPath; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.7 */ class TransferMaskDialog extends ModalDialog { private final Mask[] selectedMasks; private final Product sourceProduct; private final Product[] allProducts; private final Map<Product, ButtonModel> definitionMap; private final Map<Product, ButtonModel> dataMap; TransferMaskDialog(Window window, Product product, Product[] allProducts, Mask[] selectedMasks) { super(window, "Transfer Mask(s) to other product", ModalDialog.ID_OK_CANCEL | ModalDialog.ID_HELP, "transferMaskEditor"); this.sourceProduct = product; this.allProducts = allProducts; this.selectedMasks = selectedMasks; definitionMap = new HashMap<Product, ButtonModel>(); dataMap = new HashMap<Product, ButtonModel>(); getJDialog().setResizable(true); setContent(createUI()); } Product[] getMaskPixelTargets() { return getSelectedProducts(dataMap); } Product[] getMaskDefinitionTargets() { return getSelectedProducts(definitionMap); } private static Product[] getSelectedProducts(Map<Product, ButtonModel> buttonMap) { List<Product> selectedProducts = new ArrayList<Product>(buttonMap.size()); for (Map.Entry<Product, ButtonModel> entry : buttonMap.entrySet()) { Product product = entry.getKey(); ButtonModel buttonModel = entry.getValue(); if (buttonModel.isSelected()) { selectedProducts.add(product); } } return selectedProducts.toArray(new Product[selectedProducts.size()]); } private JComponent createUI() { final TableLayout layout = new TableLayout(3); layout.setTableFill(TableLayout.Fill.BOTH); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableWeightX(1.0); layout.setTableWeightY(0.0); layout.setTablePadding(5, 5); final JPanel panel = new JPanel(layout); panel.add(new JLabel("<html><u>Target product</u></html>")); panel.add(new JLabel("<html><u>Definition</u></html>")); panel.add(new JLabel("<html><u>Pixels</u></html>")); int row = 1; for (Product targetProduct : allProducts) { if (targetProduct != sourceProduct) { panel.add(new JLabel(targetProduct.getDisplayName())); boolean canCopyDef = canCopyDefinition(selectedMasks, targetProduct); JCheckBox defCheckBox = createCeckbox(panel, canCopyDef); if (canCopyDef) { definitionMap.put(targetProduct, defCheckBox.getModel()); } boolean canCopyData = intersectsWith(sourceProduct, targetProduct); JCheckBox dataCheckBox = createCeckbox(panel, canCopyData); if (canCopyData) { dataMap.put(targetProduct, dataCheckBox.getModel()); } if (canCopyData && canCopyDef) { ButtonGroup buttonGroup = new ButtonGroup(); buttonGroup.add(dataCheckBox); buttonGroup.add(defCheckBox); } row++; } } layout.setCellColspan(row, 0, 3); panel.add(createHelpPanel()); return panel; } private JComponent createHelpPanel() { JEditorPane helpPane = new JEditorPane("text/html", null); helpPane.setEditable(false); helpPane.setPreferredSize(new Dimension(400, 120)); helpPane.setText("<html><body>Copying the <b>definition</b> of a mask means the mathematical expression " + "is evaluated in the target product. This is only possible, " + "if the bands which are used in this expression are present in the target product.<br/> " + "Copying the <b>pixel</b> means the data of the mask is transferred to the target product. " + "This is only possible when both product overlap spatially.</body></html>"); JScrollPane helpPanelScrollPane = new JScrollPane(helpPane); helpPanelScrollPane.setBorder(BorderFactory.createTitledBorder("Description")); return helpPanelScrollPane; } private static JCheckBox createCeckbox(final JPanel panel, boolean enabled) { JCheckBox checkBox = new JCheckBox(); checkBox.setHorizontalAlignment(SwingConstants.CENTER); checkBox.setEnabled(enabled); panel.add(checkBox); return checkBox; } private static boolean canCopyDefinition(Mask[] masks, Product targetProduct) { boolean canCopyDef = true; for (Mask mask : masks) { boolean canTransferMask = mask.getImageType().canTransferMask(mask, targetProduct); canCopyDef = canCopyDef && canTransferMask; } return canCopyDef; } private static boolean intersectsWith(Product sourceProduct, Product targetProduct) { final GeoCoding srcGC = sourceProduct.getSceneGeoCoding(); final GeoCoding targetGC = targetProduct.getSceneGeoCoding(); if (srcGC != null && srcGC.canGetGeoPos() && targetGC != null && targetGC.canGetGeoPos()) { final GeneralPath[] sourcePath = GeoUtils.createGeoBoundaryPaths(sourceProduct); final GeneralPath[] targetPath = GeoUtils.createGeoBoundaryPaths(targetProduct); for (GeneralPath spath : sourcePath) { Rectangle bounds = spath.getBounds(); for (GeneralPath tPath : targetPath) { if (tPath.getBounds().intersects(bounds)) { return true; } } } } return false; } }
7,441
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskManagerForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskManagerForm.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.rcp.windows.ToolTopComponent; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import javax.swing.AbstractButton; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.GridBagConstraints; class MaskManagerForm extends MaskForm { private final AbstractButton helpButton; private final MaskFormActions actions; MaskManagerForm(ToolTopComponent maskTopComponent, ListSelectionListener selectionListener) { super(true, selectionListener); helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help22.png"), false); helpButton.setName("helpButton"); actions = new MaskFormActions(maskTopComponent, this); updateState(); } @Override public Action getDoubleClickAction() { return actions.getEditAction(); } @Override public AbstractButton getHelpButton() { return helpButton; } @Override public final void updateState() { for (MaskAction maskAction : actions.getAllActions()) { maskAction.updateState(); } } @Override public JPanel createContentPanel() { JPanel buttonPanel = GridBagUtils.createPanel(); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 0; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.5; gbc.insets.bottom = 0; gbc.gridwidth = 1; final MaskAction[] allActions = actions.getAllActions(); for (int i = 0; i < allActions.length; i += 2) { buttonPanel.add(allActions[i].createComponent(), gbc); buttonPanel.add(allActions[i + 1].createComponent(), gbc); gbc.gridy++; } gbc.fill = GridBagConstraints.VERTICAL; gbc.weighty = 1.0; gbc.gridwidth = 2; buttonPanel.add(new JLabel(" "), gbc); // filler gbc.fill = GridBagConstraints.NONE; gbc.weighty = 0.0; gbc.gridx = 1; gbc.gridy++; gbc.gridwidth = 1; buttonPanel.add(helpButton, gbc); JPanel tablePanel = new JPanel(new BorderLayout(4, 4)); tablePanel.add(new JScrollPane(getMaskTable()), BorderLayout.CENTER); JPanel contentPane1 = new JPanel(new BorderLayout(4, 4)); contentPane1.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); contentPane1.add(BorderLayout.CENTER, tablePanel); contentPane1.add(BorderLayout.EAST, buttonPanel); updateState(); return contentPane1; } }
3,570
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskViewerForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskViewerForm.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; class MaskViewerForm extends MaskForm { public MaskViewerForm(ListSelectionListener selectionListener) { super(false, selectionListener); } @Override public JPanel createContentPanel() { JPanel tablePanel = new JPanel(new BorderLayout(4, 4)); tablePanel.add(new JScrollPane(getMaskTable()), BorderLayout.CENTER); tablePanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); return tablePanel; } }
1,389
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskAction.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.core.util.StringUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JComponent; import java.awt.Dimension; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.prefs.Preferences; /** * @author Marco Peters * @since BEAM 4.7 */ abstract class MaskAction extends AbstractAction { private MaskForm maskForm; private static final String DEFAULT_MASK_NAME_PREFIX = "new_mask_"; MaskAction(MaskForm maskForm, String iconPath, String buttonName, String description) { this.maskForm = maskForm; putValue(ACTION_COMMAND_KEY, getClass().getName()); if (!iconPath.isEmpty()) { putValue(LARGE_ICON_KEY, loadIcon(iconPath)); } putValue(SHORT_DESCRIPTION, description); putValue("componentName", buttonName); } protected MaskForm getMaskForm() { return maskForm; } private ImageIcon loadIcon(String iconPath) { final ImageIcon icon; URL resource = MaskManagerForm.class.getResource(iconPath); if (resource != null) { icon = new ImageIcon(resource); } else { icon = UIUtils.loadImageIcon(iconPath); } return icon; } JComponent createComponent() { AbstractButton button = ToolButtonFactory.createButton(this, false); button.setName((String) getValue("componentName")); return button; } void updateState() { } protected Mask createNewMask(Mask.ImageType type) { String maskName = getNewMaskName(getMaskForm().getProduct().getMaskGroup()); Dimension maskSize = getMaskForm().getTargetMaskSize(); Mask mask = new Mask(maskName, maskSize.width, maskSize.height, type); Preferences preferences = SnapApp.getDefault().getPreferences(); mask.setImageColor( StringUtils.parseColor(preferences.get("mask.color", StringUtils.formatColor(Mask.ImageType.DEFAULT_COLOR)))); mask.setImageTransparency(preferences.getDouble("mask.transparency", Mask.ImageType.DEFAULT_TRANSPARENCY)); return mask; } private String getNewMaskName(ProductNodeGroup<Mask> maskGroup) { String possibleName = DEFAULT_MASK_NAME_PREFIX + maskGroup.getNodeCount(); for (int i = 0; i <= maskGroup.getNodeCount(); i++) { possibleName = DEFAULT_MASK_NAME_PREFIX + (maskGroup.getNodeCount() + i + 1); if (!maskGroup.contains(possibleName)) { break; } } return possibleName; } protected String[] collectNamesOfRastersOfSameSize() { final Product product = getMaskForm().getProduct(); //todo [multisize_products] do not compare raster sizes final RasterDataNode referenceRaster = getMaskForm().getRaster(); final List<String> rangeRasterNames = new ArrayList<>(); final Band[] bands = product.getBands(); for (Band band : bands) { if (band.getRasterHeight() == referenceRaster.getRasterHeight() && band.getRasterWidth() == referenceRaster.getRasterWidth()) { rangeRasterNames.add(band.getName()); } } final TiePointGrid[] tiePointGrids = product.getTiePointGrids(); for (TiePointGrid tiePointGrid : tiePointGrids) { if (tiePointGrid.getRasterHeight() == referenceRaster.getRasterHeight() && tiePointGrid.getRasterWidth() == referenceRaster.getRasterWidth()) { rangeRasterNames.add(tiePointGrid.getName()); } } return rangeRasterNames.toArray(new String[rangeRasterNames.size()]); } }
4,911
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskTable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskTable.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.color.ColorTableCellEditor; import org.esa.snap.ui.color.ColorTableCellRenderer; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.SwingConstants; import javax.swing.UIManager; import javax.swing.event.MouseInputAdapter; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumnModel; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.event.MouseEvent; class MaskTable extends JTable { private final VisibilityHR visibilityHR; public MaskTable(boolean maskManagmentMode) { super(new MaskTableModel(maskManagmentMode)); visibilityHR = new VisibilityHR(); setName("maskTable"); setAutoCreateColumnsFromModel(true); setPreferredScrollableViewportSize(new Dimension(200, 150)); setDefaultRenderer(Color.class, new ColorTableCellRenderer()); setDefaultEditor(Color.class, new ColorTableCellEditor()); setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); getTableHeader().setReorderingAllowed(false); getTableHeader().setResizingAllowed(true); setAutoResizeMode(JTable.AUTO_RESIZE_OFF); ToolTipMIL toolTipSetter = new ToolTipMIL(); addMouseListener(toolTipSetter); addMouseMotionListener(toolTipSetter); setRowHeight(this.getRowHeight() + 4); reconfigureColumnModel(); } @Override public MaskTableModel getModel() { return (MaskTableModel) super.getModel(); } Product getProduct() { return getModel().getProduct(); } void setProduct(Product product, RasterDataNode visibleBand) { saveColumnWidths(); getModel().setProduct(product, visibleBand); reconfigureColumnModel(); } Mask getSelectedMask() { int selectedRow = getSelectedRow(); return selectedRow >= 0 ? getMask(selectedRow) : null; } Mask[] getSelectedMasks() { int[] rows = getSelectedRows(); Mask[] masks = new Mask[rows.length]; for (int i = 0; i < rows.length; i++) { int row = rows[i]; masks[i] = getMask(row); } return masks; } void clear() { getModel().clear(); } boolean isInManagmentMode() { return getModel().isInManagmentMode(); } Mask getMask(int rowIndex) { return getModel().getMask(rowIndex); } void addMask(Mask mask) { getModel().addMask(mask); int rowIndex = getModel().getMaskIndex(mask.getName()); getSelectionModel().addSelectionInterval(rowIndex, rowIndex); scrollRectToVisible(getCellRect(rowIndex, 0, true)); } public void insertMask(Mask mask, int index) { getModel().addMask(mask, index); } void removeMask(Mask mask) { getModel().removeMask(mask); } private void saveColumnWidths() { if (getRowCount() > 0) { MaskTableModel maskTableModel = getModel(); for (int i = 0; i < maskTableModel.getColumnCount(); i++) { maskTableModel.setPreferredColumnWidth(i, columnModel.getColumn(i).getPreferredWidth()); } } } private void reconfigureColumnModel() { createDefaultColumnsFromModel(); TableColumnModel columnModel = getColumnModel(); MaskTableModel maskTableModel = getModel(); int vci = maskTableModel.getVisibilityColumnIndex(); if (vci >= 0) { columnModel.getColumn(vci).setHeaderRenderer(visibilityHR); } for (int i = 0; i < maskTableModel.getColumnCount(); i++) { columnModel.getColumn(i).setPreferredWidth(maskTableModel.getPreferredColumnWidth(i)); } } private class ToolTipMIL extends MouseInputAdapter { private int currentRowIndex; ToolTipMIL() { currentRowIndex = -1; } @Override public void mouseExited(MouseEvent e) { currentRowIndex = -1; } @Override public void mouseMoved(MouseEvent e) { int rowIndex = rowAtPoint(e.getPoint()); if (rowIndex != this.currentRowIndex) { this.currentRowIndex = rowIndex; if (this.currentRowIndex >= 0 && this.currentRowIndex < getRowCount()) { setToolTipText(getToolTipText(rowIndex)); } } } private String getToolTipText(int rowIndex) { Mask mask = getMask(rowIndex); return mask.getDescription(); } } private static class VisibilityHR extends JLabel implements TableCellRenderer { VisibilityHR() { ImageIcon icon = UIUtils.loadImageIcon("icons/EyeIcon10.gif"); this.setBorder(UIManager.getBorder("TableHeader.cellBorder")); this.setText(null); this.setIcon(icon); this.setHorizontalAlignment(SwingConstants.CENTER); this.setPreferredSize(this.getPreferredSize()); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return this; } } }
6,546
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RangeEditorDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/RangeEditorDialog.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.util.StringUtils; import org.esa.snap.ui.ModalDialog; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.awt.Insets; import java.awt.Window; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.ParseException; import java.util.Locale; import static com.bc.ceres.swing.TableLayout.*; /** * @author Marco Peters * @since BEAM 4.7 */ class RangeEditorDialog extends ModalDialog { private String code; private PropertyContainer container; private DefaultComboBoxModel rasterModel; private Model model; public static void main(String[] args) { final String[] rasterNames = new String[]{"raster_1", "raster_2", "raster_3"}; final RangeEditorDialog editorDialog = new RangeEditorDialog(null, new Model(rasterNames)); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { editorDialog.show(); } }); } RangeEditorDialog(Window window, Model model) { super(window, "New Range Mask", ModalDialog.ID_OK_CANCEL | ModalDialog.ID_HELP, "rangeEditor"); this.model = model; container = PropertyContainer.createObjectBacked(this.model); getJDialog().setResizable(false); rasterModel = new DefaultComboBoxModel(this.model.rasterNames); setContent(createUI()); } Model getModel() { return model; } private JComponent createUI() { final TableLayout layout = new TableLayout(5); layout.setTableFill(TableLayout.Fill.BOTH); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableWeightX(1.0); layout.setTableWeightY(0.0); layout.setTablePadding(3, 3); layout.setColumnPadding(1, new Insets(3, 6, 3, 6)); layout.setColumnPadding(3, new Insets(3, 6, 3, 6)); layout.setColumnWeightX(1, 0.0); layout.setColumnWeightX(3, 0.0); final JPanel panel = new JPanel(layout); panel.add(new JLabel("Min value:"), cell(0, 0)); panel.add(new JLabel("Raster:"), cell(0, 2)); panel.add(new JLabel("Max value:"), cell(0, 4)); final DoubleFormatter formatter = new DoubleFormatter("###0.0###"); final JFormattedTextField minValueField = new JFormattedTextField(formatter); final JFormattedTextField maxValueField = new JFormattedTextField(formatter); final JComboBox rasterNameComboBox = new JComboBox(rasterModel); panel.add(minValueField); panel.add(new JLabel("<html><b>&lt;=</b>")); panel.add(rasterNameComboBox); panel.add(new JLabel("<html><b>&lt;=</b>")); panel.add(maxValueField); final BindingContext context = new BindingContext(container); context.bind("rasterName", rasterNameComboBox); context.bind("minValue", minValueField); context.bind("maxValue", maxValueField); return panel; } @Override protected boolean verifyUserInput() { String errorMsg = null; final boolean minGreaterMax = model.getMaxValue() < model.getMinValue(); if (minGreaterMax) { errorMsg = "The specified maximum is less than the minimum."; } final boolean nameEmpty = StringUtils.isNullOrEmpty(model.getRasterName()); if (nameEmpty) { errorMsg = "No raster selected."; } if (errorMsg != null) { showErrorDialog(getJDialog(), errorMsg, "New Range Mask"); return false; } return true; } @SuppressWarnings({"UnusedDeclaration"}) static class Model { private String rasterName; private double minValue; private double maxValue; private final String[] rasterNames; Model(String[] rasterNames) { this.rasterNames = rasterNames; } public void setRasterName(String rasterName) { this.rasterName = rasterName; } public String getRasterName() { return rasterName; } public double getMinValue() { return minValue; } public void setMinValue(double minValue) { this.minValue = minValue; } public double getMaxValue() { return maxValue; } public void setMaxValue(double maxValue) { this.maxValue = maxValue; } public String[] getRasterNames() { return rasterNames; } } private static class DoubleFormatter extends JFormattedTextField.AbstractFormatter { private final DecimalFormat format; DoubleFormatter(String pattern) { final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH); format = new DecimalFormat(pattern, decimalFormatSymbols); format.setParseIntegerOnly(false); format.setParseBigDecimal(false); format.setDecimalSeparatorAlwaysShown(true); } @Override public Object stringToValue(String text) throws ParseException { return format.parse(text).doubleValue(); } @Override public String valueToString(Object value) throws ParseException { if (value == null) { return ""; } return format.format(value); } } }
6,523
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskManagerToolTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/mask/MaskManagerToolTopComponent.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.mask; import org.esa.snap.rcp.windows.ToolTopComponent; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.event.ListSelectionListener; @TopComponent.Description( preferredID = "MaskManagerTopComponent", iconBase = "org/esa/snap/rcp/icons/MaskManager.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "rightSlidingSide", openAtStartup = true, position = 20 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.mask.MaskManagerTopComponent") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 2), @ActionReference(path = "Toolbars/Tool Windows", position = 2) }) @TopComponent.OpenActionRegistration( displayName = "#CTL_MaskManagerTopComponent_Name", preferredID = "MaskManagerTopComponent" ) @NbBundle.Messages({ "CTL_MaskManagerTopComponent_Name=Mask Manager", "CTL_MaskManagerTopComponent_HelpId=showMaskManagerWnd" }) public class MaskManagerToolTopComponent extends MaskToolTopComponent { public static final String ID = MaskManagerToolTopComponent.class.getName(); public MaskManagerToolTopComponent() { initUI(); } @Override protected MaskForm createMaskForm(ToolTopComponent maskTopComponent, ListSelectionListener selectionListener) { return new MaskManagerForm(this, selectionListener); } @Override protected String getTitle() { return Bundle.CTL_MaskManagerTopComponent_Name(); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_MaskManagerTopComponent_HelpId()); } }
2,608
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SnapArgsProcessor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/cli/SnapArgsProcessor.java
package org.esa.snap.rcp.cli; import org.esa.snap.rcp.session.SessionManager; import org.netbeans.api.sendopts.CommandException; import org.netbeans.spi.sendopts.Arg; import org.netbeans.spi.sendopts.ArgsProcessor; import org.netbeans.spi.sendopts.Description; import org.netbeans.spi.sendopts.Env; import org.openide.util.NbBundle; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; /** * Extra SNAP Desktop command-line arguments: * <ul> * <li>{@code --open [<session-file>] [<file-1> <file-2> ...]} </li> * <li>{@code --python <python-interpreter> [<snappy-python-module-dir>]}</li> * </ul> * * @author Norman Fomferra */ @NbBundle.Messages({ "TXT_OpenOption_Description=Open SNAP session file (*.snap) or any number of EO data product files", "TXT_PythonOption_Description=Configure the SNAP Java-Python adapter 'snappy': python <python-interpreter> [<snappy-python-module-dir>]", }) public class SnapArgsProcessor implements ArgsProcessor { @Arg(longName = "open") @Description(shortDescription = "#TXT_OpenOption_Description") public String[] openArgs; @Arg(longName = "python") @Description(shortDescription = "#TXT_PythonOption_Description") public String[] pythonArgs; public void process(Env env) throws CommandException { if (openArgs != null) { processOpen(openArgs); } } private static void processOpen(String[] args) throws CommandException { int errorExitCode = 100; Path sessionFile = null; List<Path> fileList = new ArrayList<>(); for (String arg : args) { Path file = Paths.get(arg); if (Files.exists(file)) { if (file.toFile() != null && SessionManager.getDefault().getSessionFileFilter().accept(file.toFile())) { if (sessionFile != null) { throw new CommandException(errorExitCode, "Only a single SNAP session file can be given."); } sessionFile = file; } else { fileList.add(file); } } else { System.err.println("File not found: " + file); } } SnapArgs.getDefault().setSessionFile(sessionFile); SnapArgs.getDefault().setFileList(fileList); } }
2,426
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SnapArgs.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/cli/SnapArgs.java
package org.esa.snap.rcp.cli; import java.io.File; import java.nio.file.Path; import java.util.Collections; import java.util.List; /** * SNAP's command-line arguments. * * @author Norman Fomferra */ public class SnapArgs { public static final SnapArgs INSTANCE = new SnapArgs(); private Path sessionFile; private List<Path> fileList; public static SnapArgs getDefault() { return INSTANCE; } public Path getSessionFile() { return sessionFile; } void setSessionFile(Path sessionFile) { this.sessionFile = sessionFile; } public List<Path> getFileList() { return fileList != null ? fileList : Collections.<Path>emptyList(); } void setFileList(List<Path> fileList) { this.fileList = fileList; } }
797
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StatisticsPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/StatisticsPanel.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.statistics; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValueRange; import com.bc.ceres.binding.validators.IntervalValidator; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.Stx; import org.esa.snap.core.datamodel.StxFactory; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.core.util.StringUtils; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.statistics.output.Util; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.StandardXYBarPainter; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.ui.RectangleInsets; import org.jfree.data.xy.XIntervalSeries; import org.jfree.data.xy.XIntervalSeriesCollection; import org.openide.windows.TopComponent; import javax.media.jai.Histogram; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JLayeredPane; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.SpinnerNumberModel; import javax.swing.SwingWorker; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DecimalFormat; import java.util.List; /** * A general pane within the statistics window. * * @author Norman Fomferra * @author Marco Peters */ class StatisticsPanel extends PagePanel implements MultipleRoiComputePanel.ComputeMasks, StatisticsDataProvider { private static final String DEFAULT_STATISTICS_TEXT = "No statistics computed yet."; /*I18N*/ private static final String TITLE_PREFIX = "Statistics"; private MultipleRoiComputePanel computePanel; private JPanel backgroundPanel; private AbstractButton hideAndShowButton; private AbstractButton exportButton; private JPanel contentPanel; private final StatisticsPanel.PopupHandler popupHandler; private final StringBuilder resultText; private boolean init; private Histogram[] histograms; private ExportStatisticsAsCsvAction exportAsCsvAction; private PutStatisticsIntoVectorDataAction putStatisticsIntoVectorDataAction; private AccuracyModel accuracyModel; public StatisticsPanel(final TopComponent parentDialog, String helpID) { super(parentDialog, helpID, TITLE_PREFIX); setMinimumSize(new Dimension(1000, 390)); resultText = new StringBuilder(); popupHandler = new PopupHandler(); } @Override protected void initComponents() { init = true; computePanel = new MultipleRoiComputePanel(this, getRaster()); exportButton = getExportButton(); final JPanel exportAndHelpPanel = GridBagUtils.createPanel(); GridBagConstraints helpPanelConstraints = GridBagUtils.createConstraints("anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2,weightx=1,ipadx=0"); GridBagUtils.addToPanel(exportAndHelpPanel, new JSeparator(), helpPanelConstraints, "fill=HORIZONTAL,gridwidth=2,insets.left=5,insets.right=5"); GridBagUtils.addToPanel(exportAndHelpPanel, exportButton, helpPanelConstraints, "gridy=1,anchor=WEST,fill=NONE"); GridBagUtils.addToPanel(exportAndHelpPanel, getHelpButton(), helpPanelConstraints, "gridx=1,gridy=1,anchor=EAST,fill=NONE"); final JPanel rightPanel = GridBagUtils.createPanel(); GridBagConstraints extendedOptionsPanelConstraints = GridBagUtils.createConstraints("anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2,weightx=1,insets.right=-2"); GridBagUtils.addToPanel(rightPanel, computePanel, extendedOptionsPanelConstraints, "gridy=0,fill=BOTH,weighty=1"); GridBagUtils.addToPanel(rightPanel, createAccuracyPanel(), extendedOptionsPanelConstraints, "gridy=1,fill=BOTH,weighty=1"); GridBagUtils.addToPanel(rightPanel, exportAndHelpPanel, extendedOptionsPanelConstraints, "gridy=2,anchor=SOUTHWEST,fill=HORIZONTAL,weighty=0"); final ImageIcon collapseIcon = UIUtils.loadImageIcon("icons/PanelRight12.png"); final ImageIcon collapseRolloverIcon = ToolButtonFactory.createRolloverIcon(collapseIcon); final ImageIcon expandIcon = UIUtils.loadImageIcon("icons/PanelLeft12.png"); final ImageIcon expandRolloverIcon = ToolButtonFactory.createRolloverIcon(expandIcon); hideAndShowButton = ToolButtonFactory.createButton(collapseIcon, false); hideAndShowButton.setToolTipText("Collapse Options Panel"); hideAndShowButton.setName("switchToChartButton"); hideAndShowButton.addActionListener(new ActionListener() { private boolean rightPanelShown; @Override public void actionPerformed(ActionEvent e) { rightPanel.setVisible(rightPanelShown); if (rightPanelShown) { hideAndShowButton.setIcon(collapseIcon); hideAndShowButton.setRolloverIcon(collapseRolloverIcon); hideAndShowButton.setToolTipText("Collapse Options Panel"); } else { hideAndShowButton.setIcon(expandIcon); hideAndShowButton.setRolloverIcon(expandRolloverIcon); hideAndShowButton.setToolTipText("Expand Options Panel"); } rightPanelShown = !rightPanelShown; } }); contentPanel = new JPanel(new GridLayout(-1, 1)); contentPanel.setBackground(Color.WHITE); contentPanel.addMouseListener(popupHandler); final JScrollPane contentScrollPane = new JScrollPane(contentPanel); contentScrollPane.setBorder(null); contentScrollPane.setBackground(Color.WHITE); backgroundPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); GridBagUtils.addToPanel(backgroundPanel, contentScrollPane, gbc, "fill=BOTH, weightx=1.0, weighty=1.0, anchor=NORTH"); GridBagUtils.addToPanel(backgroundPanel, rightPanel, gbc, "gridx=1, fill=VERTICAL, weightx=0.0"); JLayeredPane layeredPane = new JLayeredPane(); layeredPane.add(backgroundPanel); layeredPane.add(hideAndShowButton); add(layeredPane); } private JPanel createAccuracyPanel() { final JPanel accuracyPanel = new JPanel(new GridBagLayout()); final GridBagConstraints gbc = new GridBagConstraints(); final JLabel label = new JLabel("Histogram accuracy:"); accuracyModel = new AccuracyModel(); final BindingContext bindingContext = new BindingContext(PropertyContainer.createObjectBacked(accuracyModel)); final SpinnerNumberModel accuracyNumberModel = new SpinnerNumberModel(accuracyModel.accuracy, 0, Util.MAX_ACCURACY, 1); final JSpinner accuracySpinner = new JSpinner(accuracyNumberModel); ((JSpinner.DefaultEditor) accuracySpinner.getEditor()).getTextField().setEditable(false); bindingContext.bind("accuracy", accuracySpinner); final JCheckBox checkBox = new JCheckBox("Auto accuracy"); bindingContext.bind("useAutoAccuracy", checkBox); final IntervalValidator rangeValidator = new IntervalValidator(new ValueRange(0, Util.MAX_ACCURACY)); final PropertyDescriptor accuracyDescriptor = bindingContext.getPropertySet().getDescriptor("accuracy"); accuracyDescriptor.setValidator(rangeValidator); checkBox.setSelected(accuracyModel.useAutoAccuracy); bindingContext.getPropertySet().getProperty("useAutoAccuracy").addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { label.setEnabled(!checkBox.isSelected()); accuracySpinner.setEnabled(!checkBox.isSelected()); if (checkBox.isSelected()) { bindingContext.getBinding("accuracy").setPropertyValue(3); } computePanel.updateEnablement(); } }); label.setEnabled(false); accuracySpinner.setEnabled(false); accuracySpinner.setToolTipText("Specify the number of histogram bins (#bins: 10^accuracy)."); accuracySpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { computePanel.updateEnablement(); } }); GridBagUtils.addToPanel(accuracyPanel, new TitledSeparator("Histogram accuracy"), gbc, "fill=HORIZONTAL, weightx=1.0,anchor=NORTH,gridwidth=2"); GridBagUtils.addToPanel(accuracyPanel, checkBox, gbc, "gridy=1,insets.left=5,insets.top=2"); GridBagUtils.addToPanel(accuracyPanel, label, gbc, "gridy=2, insets.left=26,weightx=0.0,fill=NONE,anchor=WEST,gridwidth=1"); GridBagUtils.addToPanel(accuracyPanel, accuracySpinner, gbc, "gridx=1,weightx=1.0,fill=HORIZONTAL,insets.right=5,insets.left=5"); return accuracyPanel; } @Override protected void updateComponents() { if (!init) { initComponents(); } final RasterDataNode raster = getRaster(); computePanel.setRaster(raster); contentPanel.removeAll(); resultText.setLength(0); if (raster != null && raster.isStxSet() && raster.getStx().getResolutionLevel() == 0) { resultText.append(createText(raster.getStx(), null)); contentPanel.add(createStatPanel(raster.getStx(), null)); histograms = new Histogram[]{raster.getStx().getHistogram()}; exportAsCsvAction = new ExportStatisticsAsCsvAction(this); putStatisticsIntoVectorDataAction = new PutStatisticsIntoVectorDataAction(this); exportButton.setEnabled(true); } else { contentPanel.add(new JLabel(DEFAULT_STATISTICS_TEXT)); exportButton.setEnabled(false); } contentPanel.revalidate(); contentPanel.repaint(); } @Override public Histogram[] getHistograms() { return histograms; } private static class ComputeResult { final Stx stx; final Mask mask; ComputeResult(Stx stx, Mask mask) { this.stx = stx; this.mask = mask; } } @Override public void compute(final Mask[] selectedMasks) { this.histograms = new Histogram[selectedMasks.length]; final String title = "Computing Statistics"; SwingWorker<Object, ComputeResult> swingWorker = new ProgressMonitorSwingWorker<Object, ComputeResult>(this, title) { @Override protected Object doInBackground(ProgressMonitor pm) { pm.beginTask(title, selectedMasks.length); try { final int binCount = Util.computeBinCount(accuracyModel.accuracy); for (int i = 0; i < selectedMasks.length; i++) { final Mask mask = selectedMasks[i]; final Stx stx; ProgressMonitor subPm = SubProgressMonitor.create(pm, 1); if (mask == null) { stx = new StxFactory() .withHistogramBinCount(binCount) .create(getRaster(), subPm); getRaster().setStx(stx); } else { stx = new StxFactory() .withHistogramBinCount(binCount) .withRoiMask(mask) .create(getRaster(), subPm); } histograms[i] = stx.getHistogram(); publish(new ComputeResult(stx, mask)); } } finally { pm.done(); } return null; } @Override protected void process(List<ComputeResult> chunks) { for (ComputeResult result : chunks) { final Stx stx = result.stx; final Mask mask = result.mask; if (resultText.length() > 0) { resultText.append("\n"); } resultText.append(createText(stx, mask)); JPanel statPanel = createStatPanel(stx, mask); contentPanel.add(statPanel); contentPanel.revalidate(); contentPanel.repaint(); } } @Override protected void done() { try { get(); if (exportAsCsvAction == null) { exportAsCsvAction = new ExportStatisticsAsCsvAction(StatisticsPanel.this); } exportAsCsvAction.setSelectedMasks(selectedMasks); if (putStatisticsIntoVectorDataAction == null) { putStatisticsIntoVectorDataAction = new PutStatisticsIntoVectorDataAction(StatisticsPanel.this); } putStatisticsIntoVectorDataAction.setSelectedMasks(selectedMasks); exportButton.setEnabled(true); } catch (Exception e) { e.printStackTrace(); Dialogs.showMessage("<html>Statistics", "Failed to compute statistics.<br/>An error occurred:" + e.getMessage() + "</html>", JOptionPane.ERROR_MESSAGE, null); } } }; resultText.setLength(0); contentPanel.removeAll(); swingWorker.execute(); } private JPanel createStatPanel(Stx stx, final Mask mask) { final Histogram histogram = stx.getHistogram(); XIntervalSeries histogramSeries = new XIntervalSeries("Histogram"); int[] bins = histogram.getBins(0); for (int j = 0; j < bins.length; j++) { histogramSeries.add(histogram.getBinLowValue(0, j), histogram.getBinLowValue(0, j), j < bins.length - 1 ? histogram.getBinLowValue(0, j + 1) : histogram.getHighValue(0), bins[j]); } ChartPanel histogramPanel = createChartPanel(histogramSeries, "Value", "#Pixels", new Color(0, 0, 127)); XIntervalSeries percentileSeries = new XIntervalSeries("Percentile"); percentileSeries.add(0, 0, 1, histogram.getLowValue(0)); for (int j = 1; j < 99; j++) { percentileSeries.add(j, j, j + 1, histogram.getPTileThreshold(j / 100.0)[0]); } percentileSeries.add(99, 99, 100, histogram.getHighValue(0)); ChartPanel percentilePanel = createChartPanel(percentileSeries, "Percentile (%)", "Value Threshold", new Color(127, 0, 0)); Object[][] tableData = new Object[][]{ new Object[]{"#Pixels total:", histogram.getTotals()[0]}, new Object[]{"Minimum:", stx.getMinimum()}, new Object[]{"Maximum:", stx.getMaximum()}, new Object[]{"Mean:", stx.getMean()}, new Object[]{"Sigma:", stx.getStandardDeviation()}, new Object[]{"Median:", stx.getMedian()}, new Object[]{"Coef Variation:", stx.getCoefficientOfVariation()}, new Object[]{"ENL:", stx.getEquivalentNumberOfLooks()}, new Object[]{"P75 threshold:", histogram.getPTileThreshold(0.75)[0]}, new Object[]{"P80 threshold:", histogram.getPTileThreshold(0.80)[0]}, new Object[]{"P85 threshold:", histogram.getPTileThreshold(0.85)[0]}, new Object[]{"P90 threshold:", histogram.getPTileThreshold(0.90)[0]}, new Object[]{"Max error:", getBinSize(histogram)}, }; JPanel plotContainerPanel = new JPanel(new GridLayout(1, 2)); plotContainerPanel.add(histogramPanel); plotContainerPanel.add(percentilePanel); TableModel tableModel = new DefaultTableModel(tableData, new String[]{"Name", "Value"}) { @Override public Class<?> getColumnClass(int columnIndex) { return columnIndex == 0 ? String.class : Number.class; } @Override public boolean isCellEditable(int row, int column) { return false; } }; final JTable table = new JTable(tableModel); table.setDefaultRenderer(Number.class, new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final Component label = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); if (value instanceof Float || value instanceof Double) { setHorizontalTextPosition(RIGHT); setText(getFormattedValue((Number) value)); } return label; } private String getFormattedValue(Number value) { if (value.doubleValue() < 0.001 && value.doubleValue() > -0.001 && value.doubleValue() != 0.0) { return new DecimalFormat("0.####E0").format(value.doubleValue()); } return String.format("%.4f", value.doubleValue()); } }); table.addMouseListener(popupHandler); JPanel textContainerPanel = new JPanel(new BorderLayout(2, 2)); textContainerPanel.setBackground(Color.WHITE); textContainerPanel.add(table, BorderLayout.CENTER); JPanel statPanel = new JPanel(new BorderLayout(4, 4)); statPanel.setBorder(new EmptyBorder(10, 2, 10, 2)); statPanel.setBackground(Color.WHITE); statPanel.add(new JLabel(getSubPanelTitle(mask)), BorderLayout.NORTH); statPanel.add(textContainerPanel, BorderLayout.WEST); statPanel.add(plotContainerPanel, BorderLayout.CENTER); return statPanel; } static double getBinSize(Histogram histogram) { return (histogram.getHighValue(0) - histogram.getLowValue(0)) / histogram.getNumBins(0); } private String getSubPanelTitle(Mask mask) { final String title; if (mask != null) { title = String.format("<html><b>%s</b> with ROI-mask <b>%s</b></html>", getRaster().getName(), mask.getName()); } else { title = String.format("<html><b>%s</b></html>", getRaster().getName()); } return title; } @Override protected String getDataAsText() { return resultText.toString(); } private String createText(final Stx stx, final Mask mask) { if (stx.getSampleCount() == 0) { if (mask != null) { return "The ROI-Mask '" + mask.getName() + "' is empty."; } else { return "The scene contains no valid pixels."; } } RasterDataNode raster = getRaster(); boolean maskUsed = mask != null; final String unit = (StringUtils.isNotNullAndNotEmpty(raster.getUnit()) ? raster.getUnit() : "1"); final long numPixelTotal = (long) raster.getRasterWidth() * (long) raster.getRasterHeight(); final StringBuilder sb = new StringBuilder(1024); sb.append("Only ROI-mask pixels considered:\t"); sb.append(maskUsed ? "Yes" : "No"); sb.append("\n"); if (maskUsed) { sb.append("ROI-mask name:\t"); sb.append(mask.getName()); sb.append("\n"); } sb.append("Number of pixels total:\t"); sb.append(numPixelTotal); sb.append("\n"); sb.append("Number of considered pixels:\t"); sb.append(stx.getSampleCount()); sb.append("\n"); sb.append("Ratio of considered pixels:\t"); sb.append(100.0 * stx.getSampleCount() / numPixelTotal); sb.append("\t"); sb.append("%"); sb.append("\n"); sb.append("Minimum:\t"); sb.append(stx.getMinimum()); sb.append("\t"); sb.append(unit); sb.append("\n"); sb.append("Maximum:\t"); sb.append(stx.getMaximum()); sb.append("\t"); sb.append(unit); sb.append("\n"); sb.append("Mean:\t"); sb.append(stx.getMean()); sb.append("\t"); sb.append(unit); sb.append("\n"); sb.append("Standard deviation:\t"); sb.append(stx.getStandardDeviation()); sb.append("\t"); sb.append(unit); sb.append("\n"); sb.append("Coefficient of variation:\t"); sb.append(getCoefficientOfVariation(stx)); sb.append("\t"); sb.append(""); sb.append("\n"); sb.append("Median:\t"); sb.append(stx.getMedian()); sb.append("\t "); sb.append(unit); sb.append("\n"); for (int percentile = 5; percentile <= 95; percentile += 5) { sb.append("P").append(percentile).append(" threshold:\t"); sb.append(stx.getHistogram().getPTileThreshold(percentile / 100.0)[0]); sb.append("\t"); sb.append(unit); sb.append("\n"); } sb.append("Threshold max error:\t"); sb.append(getBinSize(stx.getHistogram())); sb.append("\t"); sb.append(unit); sb.append("\n"); return sb.toString(); } private double getCoefficientOfVariation(Stx stx) { return stx.getStandardDeviation() / stx.getMean(); } @Override public void doLayout() { super.doLayout(); backgroundPanel.setBounds(0, 0, getWidth() - 8, getHeight() - 8); hideAndShowButton.setBounds(getWidth() - hideAndShowButton.getWidth() - 12, 6, 24, 24); } private static ChartPanel createChartPanel(XIntervalSeries percentileSeries, String xAxisLabel, String yAxisLabel, Color color) { XIntervalSeriesCollection percentileDataset = new XIntervalSeriesCollection(); percentileDataset.addSeries(percentileSeries); return getHistogramPlotPanel(percentileDataset, xAxisLabel, yAxisLabel, color); } private static ChartPanel getHistogramPlotPanel(XIntervalSeriesCollection dataset, String xAxisLabel, String yAxisLabel, Color color) { JFreeChart chart = ChartFactory.createHistogram( null, xAxisLabel, yAxisLabel, dataset, PlotOrientation.VERTICAL, false, // Legend? true, // tooltips false // url ); final XYPlot xyPlot = chart.getXYPlot(); //xyPlot.setForegroundAlpha(0.85f); xyPlot.setNoDataMessage("No data"); xyPlot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); final XYBarRenderer renderer = (XYBarRenderer) xyPlot.getRenderer(); renderer.setDrawBarOutline(false); renderer.setShadowVisible(false); renderer.setSeriesPaint(0, color); StandardXYBarPainter painter = new StandardXYBarPainter(); renderer.setBarPainter(painter); ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new Dimension(300, 200)); // chartPanel.getPopupMenu().add(createCopyDataToClipboardMenuItem()); return chartPanel; } private AbstractButton getExportButton() { final AbstractButton export = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Export24.gif"), false); export.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { JPopupMenu viewPopup = new JPopupMenu("Export"); viewPopup.add(exportAsCsvAction); viewPopup.add(putStatisticsIntoVectorDataAction); final Rectangle buttonBounds = export.getBounds(); viewPopup.show(export, 1, buttonBounds.height + 1); } }); export.setEnabled(false); return export; } @Override public RasterDataNode getRasterDataNode() { return getRaster(); } @Override public ProductNodeGroup<VectorDataNode> getVectorDataNodeGroup() { return getRasterDataNode().getProduct().getVectorDataGroup(); } private class PopupHandler extends MouseAdapter { @Override public void mouseReleased(MouseEvent e) { if (e.getButton() == 2 || e.isPopupTrigger()) { final JPopupMenu menu = new JPopupMenu(); menu.add(createCopyDataToClipboardMenuItem()); menu.show(e.getComponent(), e.getX(), e.getY()); } } } // The fields of this class are used by the binding framework @SuppressWarnings("UnusedDeclaration") static class AccuracyModel { private int accuracy = 3; private boolean useAutoAccuracy = true; } }
27,739
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TablePagePanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/TablePagePanel.java
/* * Copyright (C) 2011 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.util.StringUtils; import org.openide.windows.TopComponent; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableModel; import java.awt.Color; import java.awt.Component; import java.awt.FontMetrics; import java.util.ArrayList; import java.util.List; /** * @author Thomas Storm */ abstract class TablePagePanel extends PagePanel { private final TableModel emptyTableModel; private JTable table; TablePagePanel(TopComponent parentDialog, String helpId, String titlePrefix, String defaultInformationText) { super(parentDialog, helpId, titlePrefix); emptyTableModel = new DefaultTableModel(1, 1); emptyTableModel.setValueAt(defaultInformationText, 0, 0); table = new JTable(emptyTableModel); } /** * Notified when a node changed. * * @param event the product node which the listener to be notified */ @Override public void nodeChanged(final ProductNodeEvent event) { if (event.getSourceNode() == getRaster() || event.getSourceNode() == getProduct()) { updateComponents(); } } protected JTable getTable() { return table; } protected void showNoInformationAvailableMessage() { table.setModel(emptyTableModel); } protected void setColumnRenderer(int column, TableCellRenderer renderer) { getTable().getColumnModel().getColumn(column).setCellRenderer(renderer); } static class RendererFactory { final static int ALTERNATING_ROWS = 1; final static int TOOLTIP_AWARE = 2; final static int WRAP_TEXT = 4; static TableCellRenderer createRenderer(int spec) { return createRenderer(spec, null); } static TableCellRenderer createRenderer(int spec, Object configurator) { final List<RendererStrategy> strategies = new ArrayList<>(); if ((spec & WRAP_TEXT) == WRAP_TEXT) { strategies.add(new WrapTextRenderer((ArrayList<Integer>) configurator)); } if ((spec & ALTERNATING_ROWS) == ALTERNATING_ROWS) { strategies.add(new AlternatingRowsRenderer()); } if ((spec & TOOLTIP_AWARE) == TOOLTIP_AWARE) { strategies.add(new TooltipAwareRenderer()); } return new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { JTextArea textArea = new JTextArea(value.toString()); for (RendererStrategy strategy : strategies) { strategy.customise(table, textArea, value.toString(), row, column); } careForEmptyLines(value, textArea); return textArea; } public void careForEmptyLines(Object value, JTextArea textArea) { if (StringUtils.isNullOrEmpty(value.toString())) { // imbecile code, but necessary in order to show empty lines textArea.setText("____"); textArea.setForeground(textArea.getBackground()); } } }; } } private static interface RendererStrategy { void customise(JTable table, JTextArea component, String value, int rowIndex, int colIndex); } private static class AlternatingRowsRenderer implements RendererStrategy { private Color brightBackground; private Color mediumBackground; public AlternatingRowsRenderer() { brightBackground = Color.white; mediumBackground = new Color((14 * brightBackground.getRed()) / 15, (14 * brightBackground.getGreen()) / 15, (14 * brightBackground.getBlue()) / 15); } protected Color getBackground(int row) { if (row % 2 == 0) { return mediumBackground; } else { return brightBackground; } } @Override public void customise(JTable table, JTextArea component, String value, int rowIndex, int colIndex) { component.setBorder(new EmptyBorder(0, 0, 0, 0)); component.setBackground(getBackground(rowIndex)); } } private static class TooltipAwareRenderer implements RendererStrategy { @Override public void customise(JTable table, JTextArea component, String value, int rowIndex, int colIndex) { component.setToolTipText(value); } } private static class WrapTextRenderer implements RendererStrategy { List<Integer> wrappingRows; private WrapTextRenderer(ArrayList<Integer> wrappingRows) { this.wrappingRows = wrappingRows; } @Override public void customise(JTable table, JTextArea component, String value, int rowIndex, int colIndex) { if (!wrappingRows.contains(rowIndex)) { return; } component.setLineWrap(true); component.setWrapStyleWord(true); int max = 230; // if ((table).getCellSpanAt(rowIndex, colIndex).getColumnSpan() == table.getColumnCount()) { // max *= 2; // } int numRows = countLines(component, value, max); if (numRows > 1) { int rowHeight = table.getRowHeight() * numRows; table.setRowHeight(rowIndex, Math.max(table.getRowHeight(rowIndex), rowHeight)); } } private static int countLines(JTextArea component, String value, int max) { int lineCount = 0; FontMetrics fontMetrics = component.getFontMetrics(component.getFont()); for (String s : value.split("\n")) { lineCount += 1 + fontMetrics.stringWidth(s) / max; } return lineCount; } } static interface TableRow {} protected static abstract class TablePagePanelModel implements TableModel { private List<TableModelListener> listeners = new ArrayList<>(); protected List<TableRow> rows = new ArrayList<>(); public void addRow(TableRow row) { rows.add(row); notifyListeners(); } public void clear() { rows.clear(); notifyListeners(); } private void notifyListeners() { for (TableModelListener listener : listeners) { listener.tableChanged(new TableModelEvent(this)); } } @Override public void addTableModelListener(TableModelListener listener) { listeners.add(listener); } @Override public void removeTableModelListener(TableModelListener listener) { listeners.remove(listener); } @Override public void setValueAt(Object invalid1, int invalid2, int invalid3) { throw new IllegalStateException("Table must be non-editable!"); } @Override public Class<?> getColumnClass(int columnIndex) { return String.class; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } @Override public int getRowCount() { return rows.size(); } } }
8,708
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DensityPlotTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/DensityPlotTopComponent.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.statistics; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; @TopComponent.Description( preferredID = "DensityPlotTopComponent", iconBase = "org/esa/snap/rcp/icons/DensityPlot.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "ScatterPlot", openAtStartup = false, position = 10 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.DensityPlotTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 20), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_DensityPlotTopComponent_Name", preferredID = "DensityPlotTopComponent" ) @NbBundle.Messages({ "CTL_DensityPlotTopComponent_Name=Scatter Plot", "CTL_DensityPlotTopComponent_HelpId=densityPlotDialog" }) /** * The tool view containing a density plot * * @author Marco Zuehlke */ public class DensityPlotTopComponent extends AbstractStatisticsTopComponent { @Override protected PagePanel createPagePanel() { return new DensityPlotPanel(this, Bundle.CTL_DensityPlotTopComponent_HelpId()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_DensityPlotTopComponent_HelpId()); } @Override protected void componentOpened() { super.componentOpened(); } }
2,362
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PutStatisticsIntoVectorDataAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/PutStatisticsIntoVectorDataAction.java
/* * Copyright (C) 2011 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.statistics.output.BandNameCreator; import org.esa.snap.statistics.output.FeatureStatisticsWriter; import org.esa.snap.statistics.output.StatisticsOutputContext; import org.esa.snap.statistics.output.Util; 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.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import javax.media.jai.Histogram; import javax.swing.AbstractAction; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Thomas Storm */ class PutStatisticsIntoVectorDataAction extends AbstractAction { private Mask[] selectedMasks; private final Map<SimpleFeatureType, VectorDataNode> featureType2VDN = new HashMap<>(); private final Map<SimpleFeatureType, Set<Mask>> featureType2Mask = new HashMap<>(); private final Map<Mask, Histogram> mask2Histogram = new HashMap<>(); private final Map<Mask, String> mask2RegionName = new HashMap<>(); private final StatisticsDataProvider provider; PutStatisticsIntoVectorDataAction(StatisticsDataProvider provider) { super("Put statistics into vector data"); this.provider = provider; } @Override public boolean isEnabled() { boolean hasSelectedMasks = hasSelectedMasks(); final boolean hasTarget = getFeatureTypes().length != 0; return super.isEnabled() && hasSelectedMasks && hasTarget; } private boolean hasSelectedMasks() { boolean hasSelectedMasks = selectedMasks != null && selectedMasks.length != 0; if (hasSelectedMasks) { for (Mask selectedMask : selectedMasks) { if (selectedMask != null) { break; } hasSelectedMasks = false; } } return hasSelectedMasks; } @Override public void actionPerformed(ActionEvent e) { if (selectedMasks[0] == null) { return; } for (final SimpleFeatureType featureType : getFeatureTypes()) { final VectorDataNode originalVDN = featureType2VDN.get(featureType); if (originalVDN.isPermanent()) { SystemUtils.LOG.warning("Unable to put statistics into permanent vector data."); Dialogs.showError("Unable to put statistics into permanent vector data (such as pins/GCPs)."); continue; } FeatureStatisticsWriter featureStatisticsWriter = FeatureStatisticsWriter.createFeatureStatisticsWriter(getFeatureCollection(featureType), null, new BandNameCreator()); featureStatisticsWriter.initialiseOutput( StatisticsOutputContext.create( new String[]{provider.getRasterDataNode().getName()}, new String[]{ "minimum", "maximum", "median", "average", "sigma", "p90", "p95", "pxx_max_error", "total" })); for (final Mask mask : getMasks(featureType)) { HashMap<String, Object> statistics = new HashMap<>(); Histogram histogram = getHistogram(mask); statistics.put("minimum", histogram.getLowValue(0)); statistics.put("maximum", histogram.getHighValue(0)); statistics.put("median", histogram.getPTileThreshold(0.5)[0]); statistics.put("average", histogram.getMean()[0]); statistics.put("sigma", histogram.getStandardDeviation()[0]); statistics.put("p90", histogram.getPTileThreshold(0.9)[0]); statistics.put("p95", histogram.getPTileThreshold(0.95)[0]); statistics.put("pxx_max_error", StatisticsPanel.getBinSize(histogram)); statistics.put("total", histogram.getTotals()[0]); featureStatisticsWriter.addToOutput(provider.getRasterDataNode().getName(), mask2RegionName.get(mask), statistics); } exchangeVDN(featureType, featureStatisticsWriter); Dialogs.showMessage("Extending vector data with statistics", "The vector data have successfully been extended with the computed statistics.", JOptionPane.INFORMATION_MESSAGE, null); } } private void exchangeVDN(SimpleFeatureType featureType, FeatureStatisticsWriter featureStatisticsWriter) { final VectorDataNode originalVDN = featureType2VDN.get(featureType); final VectorDataNode vectorDataNode = createVectorDataNode(featureStatisticsWriter, originalVDN); final ProductNodeGroup<VectorDataNode> vectorDataNodeGroup = provider.getVectorDataNodeGroup(); vectorDataNodeGroup.remove(originalVDN); originalVDN.dispose(); vectorDataNodeGroup.add(vectorDataNode); //todo solve this one // final JInternalFrame internalFrame = VisatApp.getApp().findInternalFrame(originalVDN); // if (internalFrame != null) { // try { // internalFrame.setClosed(true); // } catch (PropertyVetoException ignored) { // ok // } // } final ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); if (sceneView != null) { sceneView.setLayersVisible(vectorDataNode); } } private static VectorDataNode createVectorDataNode(FeatureStatisticsWriter featureStatisticsWriter, VectorDataNode originalVDN) { final SimpleFeatureType updatedFeatureType = featureStatisticsWriter.getUpdatedFeatureType(); final List<SimpleFeature> features = featureStatisticsWriter.getFeatures(); final ListFeatureCollection featureCollection = new ListFeatureCollection(updatedFeatureType, features); final PlacemarkDescriptor placemarkDescriptor = originalVDN.getPlacemarkDescriptor(); final VectorDataNode vectorDataNode = new VectorDataNode(originalVDN.getName(), featureCollection, placemarkDescriptor); vectorDataNode.setPermanent(originalVDN.isPermanent()); vectorDataNode.setModified(true); vectorDataNode.setDescription(originalVDN.getDescription()); return vectorDataNode; } private Histogram getHistogram(Mask mask) { return mask2Histogram.get(mask); } private Mask[] getMasks(SimpleFeatureType featureType) { final Set<Mask> masks = featureType2Mask.get(featureType); return masks.toArray(new Mask[masks.size()]); } private FeatureCollection<SimpleFeatureType, SimpleFeature> getFeatureCollection(SimpleFeatureType featureType) { return featureType2VDN.get(featureType).getFeatureCollection(); } private SimpleFeatureType[] getFeatureTypes() { if (!hasSelectedMasks()) { return new SimpleFeatureType[0]; } List<SimpleFeatureType> result = new ArrayList<>(); final Histogram[] histograms = provider.getHistograms(); for (int i = 0; i < selectedMasks.length; i++) { final Mask selectedMask = selectedMasks[i]; mask2Histogram.put(selectedMask, histograms[i]); if (selectedMask.getImageType().getName().equals(Mask.VectorDataType.TYPE_NAME)) { VectorDataNode vectorDataNode = Mask.VectorDataType.getVectorData(selectedMask); SimpleFeatureType featureType = vectorDataNode.getFeatureType(); if (!result.contains(featureType)) { result.add(featureType); } if (!featureType2Mask.containsKey(featureType)) { featureType2Mask.put(featureType, new HashSet<Mask>()); } featureType2Mask.get(featureType).add(selectedMask); featureType2VDN.put(featureType, vectorDataNode); setMaskRegionName(selectedMask, vectorDataNode); } } return result.toArray(new SimpleFeatureType[result.size()]); } private void setMaskRegionName(Mask selectedMask, VectorDataNode vectorDataNode) { FeatureIterator<SimpleFeature> features = vectorDataNode.getFeatureCollection().features(); mask2RegionName.put(selectedMask, Util.getFeatureName(features.next())); features.close(); } public void setSelectedMasks(Mask[] selectedMasks) { this.selectedMasks = selectedMasks; } }
10,391
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TableViewPagePanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/TableViewPagePanel.java
package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.ui.io.TableModelCsvEncoder; import org.esa.snap.ui.tool.ToolButtonFactory; import org.openide.windows.TopComponent; import javax.swing.AbstractButton; import javax.swing.Icon; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.JTableHeader; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableColumn; import javax.swing.table.TableModel; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.StringWriter; import java.util.Enumeration; public class TableViewPagePanel extends PagePanel { private JTable table; private final Icon iconForSwitchToChartButton; public TableViewPagePanel(TopComponent topComponent, String helpId, String titlePrefix, Icon iconForSwitchToChartButton) { super(topComponent, helpId, titlePrefix); this.iconForSwitchToChartButton = iconForSwitchToChartButton; } @Override protected void initComponents() { final AbstractButton switchToChartButton = ToolButtonFactory.createButton(iconForSwitchToChartButton, false); switchToChartButton.setToolTipText("Switch to Chart View"); switchToChartButton.setName("switchToChartButton"); switchToChartButton.setEnabled(hasAlternativeView()); switchToChartButton.addActionListener(e -> showAlternativeView()); final JPanel buttonPanel = new JPanel(new BorderLayout()); buttonPanel.add(switchToChartButton, BorderLayout.NORTH); buttonPanel.add(getHelpButton(), BorderLayout.SOUTH); add(buttonPanel, BorderLayout.EAST); table = new JTable(); table.removeEditor(); table.setGridColor(Color.LIGHT_GRAY.brighter()); table.addMouseListener(new PagePanel.PopupHandler()); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JScrollPane scrollPane = new JScrollPane(table); add(scrollPane, BorderLayout.CENTER); } @Override protected void updateComponents() { } @Override protected String getDataAsText() { final StringWriter writer = new StringWriter(); try { new TableModelCsvEncoder(table.getModel()).encodeCsv(writer); writer.close(); } catch (IOException ignore) { } return writer.toString(); } @Override protected void showAlternativeView() { super.showAlternativeView(); final PagePanel alternativeView = getAlternativeView(); alternativeView.handleLayerContentChanged(); final RasterDataNode raster = alternativeView.getRaster(); alternativeView.setRaster(null); alternativeView.setRaster(raster); alternativeView.handleNodeSelectionChanged(); } void setModel(TableModel tableModel) { table.setModel(tableModel); if (table.getColumnCount() > 0) { final JTableHeader tableHeader = table.getTableHeader(); final int margin = tableHeader.getColumnModel().getColumnMargin(); final TableCellRenderer renderer = tableHeader.getDefaultRenderer(); final Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); while (columns.hasMoreElements()) { TableColumn tableColumn = columns.nextElement(); final int width = getColumnMinWith(tableColumn, renderer, margin); tableColumn.setMinWidth(width); } } } private int getColumnMinWith(TableColumn column, TableCellRenderer renderer, int margin) { final Object headerValue = column.getHeaderValue(); final JLabel label = (JLabel) renderer.getTableCellRendererComponent(table, headerValue, false, false, 0, 0); return label.getPreferredSize().width + margin; } }
4,042
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProfilePlotPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ProfilePlotPanel.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.statistics; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.Validator; import com.bc.ceres.binding.ValueRange; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.Enablement; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.TransectProfileData; import org.esa.snap.core.datamodel.TransectProfileDataBuilder; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.core.dataop.barithm.BandArithmetic; import org.esa.snap.rcp.sync.DefaultCursorSynchronizer; import org.esa.snap.rcp.util.RoiMaskSelector; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.GridBagUtils; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.event.AxisChangeEvent; import org.jfree.chart.event.AxisChangeListener; import org.jfree.chart.plot.IntervalMarker; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DeviationRenderer; import org.jfree.chart.renderer.xy.XYErrorRenderer; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.ui.Layer; import org.jfree.chart.ui.RectangleInsets; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.type.AttributeDescriptor; import org.openide.windows.TopComponent; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSpinner; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.awt.BasicStroke; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.Shape; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.util.HashSet; import java.util.Set; /** * The profile plot pane within the statistics window. * * @author Norman Fomferra * @author Thomas Storm */ class ProfilePlotPanel extends ChartPagePanel { static final String CHART_TITLE = "Profile Plot"; private static final String NO_DATA_MESSAGE = "No profile plot computed yet.\n" + "It will be computed if vector data (a polygon, an ellipse, or a line)\n" + "is selected within the image view.\n" + HELP_TIP_MESSAGE + "\n" + ZOOM_TIP_MESSAGE; private static final String PROPERTY_NAME_MARK_SEGMENTS = "markSegments"; private static final String PROPERTY_NAME_LOG_SCALED = "logScaled"; private static final String DEFAULT_SAMPLE_DATASET_NAME = "Sample"; private AxisRangeControl xAxisRangeControl; private AxisRangeControl yAxisRangeControl; private boolean isInitialized; private ChartPanel profilePlotDisplay; private JFreeChart chart; private XYIntervalSeriesCollection dataset; private TransectProfileData profileData; private boolean axisAdjusting = false; private Set<IntervalMarker> intervalMarkers; private CorrelativeFieldSelector correlativeFieldSelector; private DataSourceConfig dataSourceConfig; private DeviationRenderer deviationRenderer; private XYErrorRenderer pointRenderer; private Enablement pointDataSourceEnablement; private Enablement dataFieldEnablement; private DefaultCursorSynchronizer cursorSynchronizer; ProfilePlotPanel(TopComponent parentComponent, String helpId) { super(parentComponent, helpId, CHART_TITLE, false); } private ChartPanel createChartPanel(JFreeChart chart) { profilePlotDisplay = new ChartPanel(chart); MaskSelectionToolSupport maskSelectionToolSupport = new MaskSelectionToolSupport(this, profilePlotDisplay, "profile_plot_area", "Mask generated from selected profile plot area", Color.RED, PlotAreaSelectionTool.AreaType.Y_RANGE) { @Override protected String createMaskExpression(PlotAreaSelectionTool.AreaType areaType, Shape shape) { Rectangle2D bounds = shape.getBounds2D(); return createMaskExpression(bounds.getMinY(), bounds.getMaxY()); } protected String createMaskExpression(double x1, double x2) { String bandName = BandArithmetic.createExternalName(getRaster().getName()); return String.format("%s >= %s && %s <= %s", bandName, x1, bandName, x2); } }; profilePlotDisplay.addChartMouseListener(new XYPlotMarker(profilePlotDisplay, new XYPlotMarker.Listener() { @Override public void pointSelected(XYDataset xyDataset, int seriesIndex, Point2D dataPoint) { if (profileData != null) { GeoPos[] geoPositions = profileData.getGeoPositions(); int index = (int) dataPoint.getX(); if (index >= 0 && index < geoPositions.length) { if (cursorSynchronizer == null) { cursorSynchronizer = new DefaultCursorSynchronizer(); } if (!cursorSynchronizer.isEnabled()) { cursorSynchronizer.setEnabled(true); } cursorSynchronizer.updateCursorOverlays(geoPositions[index]); } } } @Override public void pointDeselected() { cursorSynchronizer.setEnabled(false); } })); profilePlotDisplay.setInitialDelay(200); profilePlotDisplay.setDismissDelay(1500); profilePlotDisplay.setReshowDelay(200); profilePlotDisplay.setZoomTriggerDistance(5); profilePlotDisplay.getPopupMenu().addSeparator(); profilePlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createMaskSelectionModeMenuItem()); profilePlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createDeleteMaskMenuItem()); profilePlotDisplay.getPopupMenu().addSeparator(); profilePlotDisplay.getPopupMenu().add(createCopyDataToClipboardMenuItem()); return profilePlotDisplay; } @Override protected void showAlternativeView() { final TableModel model; if (profileData != null) { model = createProfileDataTableModel(); } else { model = new DefaultTableModel(); } final TableViewPagePanel alternativePanel = (TableViewPagePanel) getAlternativeView(); alternativePanel.setModel(model); super.showAlternativeView(); } @Override protected void initComponents() { if (hasAlternativeView()) { getAlternativeView().initComponents(); } dataset = new XYIntervalSeriesCollection(); this.chart = ChartFactory.createXYLineChart( CHART_TITLE, "Path in pixels", DEFAULT_SAMPLE_DATASET_NAME, dataset, PlotOrientation.VERTICAL, true, true, false ); final XYPlot plot = chart.getXYPlot(); deviationRenderer = new DeviationRenderer(); deviationRenderer.setUseFillPaint(true); deviationRenderer.setDefaultToolTipGenerator(new XYPlotToolTipGenerator()); deviationRenderer.setSeriesLinesVisible(0, true); deviationRenderer.setSeriesShapesVisible(0, false); deviationRenderer.setSeriesStroke(0, new BasicStroke(1.0f)); deviationRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); deviationRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); pointRenderer = new XYErrorRenderer(); pointRenderer.setUseFillPaint(true); pointRenderer.setDefaultToolTipGenerator(new XYPlotToolTipGenerator()); pointRenderer.setSeriesLinesVisible(0, false); pointRenderer.setSeriesShapesVisible(0, true); pointRenderer.setSeriesStroke(0, new BasicStroke(1.0f)); pointRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); pointRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); pointRenderer.setSeriesShape(0, StatisticChartStyling.SAMPLE_DATA_POINT_SHAPE); configureRendererForCorrelativeData(deviationRenderer); configureRendererForCorrelativeData(pointRenderer); plot.setNoDataMessage(NO_DATA_MESSAGE); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); plot.setRenderer(deviationRenderer); final AxisChangeListener axisListener = new AxisChangeListener() { @Override public void axisChanged(AxisChangeEvent event) { adjustAxisControlComponents(); } }; final ValueAxis domainAxis = plot.getDomainAxis(); final ValueAxis rangeAxis = plot.getRangeAxis(); // allow transfer from bounds into min/max fields, if auto min/maxis enabled domainAxis.setAutoRange(true); rangeAxis.setAutoRange(true); domainAxis.addChangeListener(axisListener); rangeAxis.addChangeListener(axisListener); intervalMarkers = new HashSet<>(); xAxisRangeControl = new AxisRangeControl("X-Axis"); yAxisRangeControl = new AxisRangeControl("Y-Axis"); final PropertyChangeListener changeListener = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName().equals(PROPERTY_NAME_MARK_SEGMENTS)) { updateDataSet(); } if (evt.getPropertyName().equals(PROPERTY_NAME_LOG_SCALED)) { updateScalingOfYAxis(); } updateUIState(); } }; xAxisRangeControl.getBindingContext().addPropertyChangeListener(changeListener); xAxisRangeControl.getBindingContext().getPropertySet().addProperty(Property.create(PROPERTY_NAME_MARK_SEGMENTS, false)); xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor(PROPERTY_NAME_MARK_SEGMENTS).setDescription("Toggle whether to mark segments"); yAxisRangeControl.getBindingContext().addPropertyChangeListener(changeListener); yAxisRangeControl.getBindingContext().getPropertySet().addProperty(Property.create(PROPERTY_NAME_LOG_SCALED, false)); yAxisRangeControl.getBindingContext().getPropertySet().getDescriptor(PROPERTY_NAME_LOG_SCALED).setDescription("Toggle whether to use a logarithmic axis"); dataSourceConfig = new DataSourceConfig(); final BindingContext bindingContext = new BindingContext(PropertyContainer.createObjectBacked(dataSourceConfig)); JPanel middlePanel = createMiddlePanel(bindingContext); createUI(createChartPanel(chart), middlePanel, new RoiMaskSelector(bindingContext)); isInitialized = true; updateComponents(); } protected JPanel createMiddlePanel(BindingContext bindingContext) { final JLabel boxSizeLabel = new JLabel("Box size: "); final JSpinner boxSizeSpinner = new JSpinner(); final JCheckBox computeInBetweenPoints = new JCheckBox("Compute in-between points"); final JCheckBox useCorrelativeData = new JCheckBox("Use correlative data"); correlativeFieldSelector = new CorrelativeFieldSelector(bindingContext); final PropertyDescriptor boxSizeDescriptor = bindingContext.getPropertySet().getProperty("boxSize").getDescriptor(); boxSizeDescriptor.setValueRange(new ValueRange(1, 101)); boxSizeDescriptor.setAttribute("stepSize", 2); boxSizeDescriptor.setValidator(new Validator() { @Override public void validateValue(Property property, Object value) throws ValidationException { if (((Number) value).intValue() % 2 == 0) { throw new ValidationException("Only odd values allowed as box size."); } } }); bindingContext.bind("boxSize", boxSizeSpinner); bindingContext.bind("computeInBetweenPoints", computeInBetweenPoints); bindingContext.bind("useCorrelativeData", useCorrelativeData); EnablePointDataCondition condition = new EnablePointDataCondition(); pointDataSourceEnablement = bindingContext.bindEnabledState("pointDataSource", true, condition); dataFieldEnablement = bindingContext.bindEnabledState("dataField", true, condition); bindingContext.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateDataSource(); updateDataSet(); updateUIState(); } }); JPanel dataSourceOptionsPanel = GridBagUtils.createPanel(); GridBagConstraints dataSourceOptionsConstraints = GridBagUtils.createConstraints("anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2"); GridBagUtils.addToPanel(dataSourceOptionsPanel, boxSizeLabel, dataSourceOptionsConstraints, "gridwidth=1,gridy=0,gridx=0,weightx=0,insets.left=4"); GridBagUtils.addToPanel(dataSourceOptionsPanel, boxSizeSpinner, dataSourceOptionsConstraints, "gridwidth=1,gridy=0,gridx=1,weightx=1,insets.left=0"); GridBagUtils.addToPanel(dataSourceOptionsPanel, computeInBetweenPoints, dataSourceOptionsConstraints, "gridwidth=2,gridy=1,gridx=0,weightx=2"); GridBagUtils.addToPanel(dataSourceOptionsPanel, useCorrelativeData, dataSourceOptionsConstraints, "gridy=2,insets.top=16"); GridBagUtils.addToPanel(dataSourceOptionsPanel, correlativeFieldSelector.pointDataSourceLabel, dataSourceOptionsConstraints, "gridy=3,insets.top=0,insets.left=4"); GridBagUtils.addToPanel(dataSourceOptionsPanel, correlativeFieldSelector.pointDataSourceList, dataSourceOptionsConstraints, "gridy=4,insets.left=4"); GridBagUtils.addToPanel(dataSourceOptionsPanel, correlativeFieldSelector.dataFieldLabel, dataSourceOptionsConstraints, "gridy=5,insets.left=4"); GridBagUtils.addToPanel(dataSourceOptionsPanel, correlativeFieldSelector.dataFieldList, dataSourceOptionsConstraints, "gridy=6,insets.left=4"); xAxisRangeControl.getBindingContext().bind(PROPERTY_NAME_MARK_SEGMENTS, new JCheckBox("Mark segments")); yAxisRangeControl.getBindingContext().bind(PROPERTY_NAME_LOG_SCALED, new JCheckBox("Log10 scaled")); JPanel displayOptionsPanel = GridBagUtils.createPanel(); GridBagConstraints displayOptionsConstraints = GridBagUtils.createConstraints("anchor=SOUTH,fill=HORIZONTAL,weightx=1"); GridBagUtils.addToPanel(displayOptionsPanel, xAxisRangeControl.getPanel(), displayOptionsConstraints, "gridy=0"); GridBagUtils.addToPanel(displayOptionsPanel, xAxisRangeControl.getBindingContext().getBinding(PROPERTY_NAME_MARK_SEGMENTS).getComponents()[0], displayOptionsConstraints, "gridy=1"); GridBagUtils.addToPanel(displayOptionsPanel, yAxisRangeControl.getPanel(), displayOptionsConstraints, "gridy=2"); GridBagUtils.addToPanel(displayOptionsPanel, yAxisRangeControl.getBindingContext().getBinding(PROPERTY_NAME_LOG_SCALED).getComponents()[0], displayOptionsConstraints, "gridy=3"); JPanel middlePanel = GridBagUtils.createPanel(); GridBagConstraints middlePanelConstraints = GridBagUtils.createConstraints("anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2,weightx=1"); GridBagUtils.addToPanel(middlePanel, dataSourceOptionsPanel, middlePanelConstraints, "gridy=0"); GridBagUtils.addToPanel(middlePanel, new JPanel(), middlePanelConstraints, "gridy=1,fill=VERTICAL,weighty=1"); GridBagUtils.addToPanel(middlePanel, displayOptionsPanel, middlePanelConstraints, "gridy=2,fill=HORIZONTAL,weighty=0"); return middlePanel; } @Override protected void updateChartData() { //Left empty for Profile Plot Panel } private void configureRendererForCorrelativeData(XYLineAndShapeRenderer renderer) { renderer.setSeriesLinesVisible(1, false); renderer.setSeriesShapesVisible(1, true); renderer.setSeriesStroke(1, new BasicStroke(1.0f)); renderer.setSeriesPaint(1, StatisticChartStyling.CORRELATIVE_POINT_PAINT); renderer.setSeriesFillPaint(1, StatisticChartStyling.CORRELATIVE_POINT_FILL_PAINT); renderer.setSeriesShape(1, StatisticChartStyling.CORRELATIVE_POINT_SHAPE); } @Override protected boolean mustHandleSelectionChange() { return super.mustHandleSelectionChange() || isVectorDataNodeChanged(); } @Override protected void updateComponents() { if (!isInitialized || !isVisible()) { return; } final RasterDataNode raster = getRaster(); if (raster != null) { chart.setTitle(CHART_TITLE + " for " + raster.getName()); } else { chart.setTitle(CHART_TITLE); } correlativeFieldSelector.updatePointDataSource(getProduct()); updateDataSource(); updateDataSet(); updateUIState(); super.updateComponents(); } private void updateDataSource() { if (!isInitialized) { return; } profileData = null; if (getRaster() != null) { try { if (dataSourceConfig.useCorrelativeData && dataSourceConfig.pointDataSource != null) { profileData = new TransectProfileDataBuilder() .raster(getRaster()) .pointData(dataSourceConfig.pointDataSource) .boxSize(dataSourceConfig.boxSize) .connectVertices(dataSourceConfig.computeInBetweenPoints) .useRoiMask(dataSourceConfig.useRoiMask) .roiMask(dataSourceConfig.roiMask) .build(); } else { Shape shape = StatisticsUtils.TransectProfile.getTransectShape(getRaster().getProduct()); if (shape != null) { profileData = new TransectProfileDataBuilder() .raster(getRaster()) .path(shape) .boxSize(dataSourceConfig.boxSize) .connectVertices(dataSourceConfig.computeInBetweenPoints) .useRoiMask(dataSourceConfig.useRoiMask) .roiMask(dataSourceConfig.roiMask) .build(); } } } catch (IOException e) { AbstractDialog.showErrorDialog(getParent(), "Failed to compute profile plot.\n" + "An I/O error occurred:" + e.getMessage(), "I/O error"); } } } private void updateDataSet() { if (!isInitialized) { return; } dataset.removeAllSeries(); double dx = 0.5 * dataSourceConfig.boxSize; if (profileData != null) { final float[] sampleValues = profileData.getSampleValues(); final float[] sampleSigmas = profileData.getSampleSigmas(); XYIntervalSeries series = new XYIntervalSeries(getRaster() != null ? getRaster().getName() : DEFAULT_SAMPLE_DATASET_NAME); for (int x = 0; x < sampleValues.length; x++) { final float y = sampleValues[x]; final float dy = sampleSigmas[x]; series.add(x, x - dx, x + dx, y, y - dy, y + dy); } dataset.addSeries(series); if (dataSourceConfig.useCorrelativeData && dataSourceConfig.pointDataSource != null && dataSourceConfig.dataField != null) { XYIntervalSeries corrSeries = new XYIntervalSeries( StatisticChartStyling.getCorrelativeDataLabel(dataSourceConfig.pointDataSource, dataSourceConfig.dataField)); int[] shapeVertexIndexes = profileData.getShapeVertexIndexes(); SimpleFeature[] simpleFeatures = dataSourceConfig.pointDataSource.getFeatureCollection().toArray(new SimpleFeature[0]); if (shapeVertexIndexes.length == simpleFeatures.length) { int fieldIndex = getAttributeIndex(dataSourceConfig.pointDataSource, dataSourceConfig.dataField); if (fieldIndex != -1) { for (int i = 0; i < simpleFeatures.length; i++) { Number attribute = (Number) simpleFeatures[i].getAttribute(fieldIndex); if (attribute != null) { final double x = shapeVertexIndexes[i]; final double y = attribute.doubleValue(); corrSeries.add(x, x, x, y, y, y); } } dataset.addSeries(corrSeries); } } else { System.out.println("Weird things happened:"); System.out.println(" shapeVertexIndexes.length = " + shapeVertexIndexes.length); System.out.println(" simpleFeatures.length = " + simpleFeatures.length); } } profilePlotDisplay.restoreAutoBounds(); xAxisRangeControl.getBindingContext().setComponentsEnabled(PROPERTY_NAME_MARK_SEGMENTS, profileData.getShapeVertices().length > 2); } } private int getAttributeIndex(VectorDataNode pointDataSource, AttributeDescriptor dataField) { final String fieldName = dataField.getLocalName(); if (fieldName.equals(CorrelativeFieldSelector.NULL_NAME)) { return -1; } return pointDataSource.getFeatureType().indexOf(fieldName); } private void updateUIState() { if (!isInitialized) { return; } xAxisRangeControl.getBindingContext().setComponentsEnabled(PROPERTY_NAME_MARK_SEGMENTS, profileData != null && profileData.getShapeVertices().length > 2); xAxisRangeControl.setComponentsEnabled(profileData != null); yAxisRangeControl.setComponentsEnabled(profileData != null); adjustPlotAxes(); if (dataSourceConfig.computeInBetweenPoints) { chart.getXYPlot().setRenderer(deviationRenderer); } else { chart.getXYPlot().setRenderer(pointRenderer); } chart.getXYPlot().getRangeAxis().setLabel(StatisticChartStyling.getAxisLabel(getRaster(), DEFAULT_SAMPLE_DATASET_NAME, false)); boolean markSegments = xAxisRangeControl.getBindingContext().getPropertySet().getValue(PROPERTY_NAME_MARK_SEGMENTS); if (markSegments && profileData != null && profileData.getNumShapeVertices() > 1) { final int[] shapeVertexIndexes = profileData.getShapeVertexIndexes(); removeIntervalMarkers(); for (int i = 0; i < shapeVertexIndexes.length - 1; i++) { if (i % 2 != 0) { final IntervalMarker marker = new IntervalMarker(shapeVertexIndexes[i], shapeVertexIndexes[i + 1]); marker.setPaint(new Color(120, 122, 125)); marker.setAlpha(0.3F); chart.getXYPlot().addDomainMarker(marker, Layer.BACKGROUND); intervalMarkers.add(marker); } } } else { removeIntervalMarkers(); } pointDataSourceEnablement.apply(); dataFieldEnablement.apply(); } private void removeIntervalMarkers() { for (IntervalMarker intervalMarker : intervalMarkers) { chart.getXYPlot().removeDomainMarker(intervalMarker, Layer.BACKGROUND); } intervalMarkers.clear(); } private void adjustAxisControlComponents() { if (!axisAdjusting) { axisAdjusting = true; try { if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.adjustComponents(chart.getXYPlot().getDomainAxis(), 0); } if (yAxisRangeControl.isAutoMinMax()) { yAxisRangeControl.adjustComponents(chart.getXYPlot().getRangeAxis(), 2); } } finally { axisAdjusting = false; } } } private void adjustPlotAxes() { if (!axisAdjusting) { axisAdjusting = true; try { xAxisRangeControl.adjustAxis(chart.getXYPlot().getDomainAxis(), 0); yAxisRangeControl.adjustAxis(chart.getXYPlot().getRangeAxis(), 2); } finally { axisAdjusting = false; } } } private void updateScalingOfYAxis() { final boolean logScaled = (Boolean) yAxisRangeControl.getBindingContext().getBinding(PROPERTY_NAME_LOG_SCALED).getPropertyValue(); final XYPlot plot = chart.getXYPlot(); plot.setRangeAxis(StatisticChartStyling.updateScalingOfAxis(logScaled, plot.getRangeAxis(), true)); } @Override public void nodeAdded(ProductNodeEvent event) { if (event.getSourceNode() instanceof VectorDataNode) { updateComponents(); } } @Override public void nodeRemoved(ProductNodeEvent event) { if (event.getSourceNode() instanceof VectorDataNode) { updateComponents(); } } @Override public void setVisible(boolean aFlag) { super.setVisible(aFlag); updateComponents(); } @Override protected String getDataAsText() { if (profileData != null) { ProfileDataTableModel model = createProfileDataTableModel(); return model.toCsv(); } else { return ""; } } private ProfileDataTableModel createProfileDataTableModel() { return new ProfileDataTableModel(getRaster().getName(), profileData, dataSourceConfig); } @Override public void handleLayerContentChanged() { updateComponents(); } @SuppressWarnings("UnusedDeclaration") static class DataSourceConfig { int boxSize = 3; boolean useRoiMask; Mask roiMask; boolean computeInBetweenPoints = true; boolean useCorrelativeData; VectorDataNode pointDataSource; AttributeDescriptor dataField; } private class EnablePointDataCondition extends Enablement.Condition { @Override public boolean evaluate(BindingContext bindingContext) { return dataSourceConfig.useCorrelativeData && getProduct() != null; } } }
28,866
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ExportStatisticsAsCsvAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ExportStatisticsAsCsvAction.java
/* * Copyright (C) 2011 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Product; 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.statistics.output.CsvStatisticsWriter; import org.esa.snap.statistics.output.MetadataWriter; import org.esa.snap.statistics.output.StatisticsOutputContext; import org.esa.snap.ui.SnapFileChooser; import javax.media.jai.Histogram; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; /** * @author Thomas Storm */ class ExportStatisticsAsCsvAction extends AbstractAction { private static final String PROPERTY_KEY_EXPORT_DIR = "user.statistics.export.dir"; private Mask[] selectedMasks; private final StatisticsDataProvider dataProvider; public ExportStatisticsAsCsvAction(StatisticsDataProvider dataProvider) { super("Export as CSV"); this.dataProvider = dataProvider; } @Override public void actionPerformed(ActionEvent e) { PrintStream metadataOutputStream = null; PrintStream csvOutputStream = null; String exportDir = SnapApp.getDefault().getPreferences().get(PROPERTY_KEY_EXPORT_DIR, null); File baseDir = null; if (exportDir != null) { baseDir = new File(exportDir); } SnapFileChooser fileChooser = new SnapFileChooser(baseDir); final SnapFileFilter snapFileFilter = new SnapFileFilter("CSV", new String[]{".csv", ".txt"}, "CSV files"); fileChooser.setFileFilter(snapFileFilter); File outputAsciiFile; int result = fileChooser.showSaveDialog(SnapApp.getDefault().getMainFrame()); if (result == JFileChooser.APPROVE_OPTION) { outputAsciiFile = fileChooser.getSelectedFile(); SnapApp.getDefault().getPreferences().put(PROPERTY_KEY_EXPORT_DIR, outputAsciiFile.getParent()); } else { return; } try { final File metadataFile = new File(outputAsciiFile.getParent(), FileUtils.getFilenameWithoutExtension(outputAsciiFile) + "_metadata.txt"); metadataOutputStream = new PrintStream(new FileOutputStream(metadataFile)); csvOutputStream = new PrintStream(new FileOutputStream(outputAsciiFile)); CsvStatisticsWriter csvStatisticsWriter = new CsvStatisticsWriter(csvOutputStream); final MetadataWriter metadataWriter = new MetadataWriter(metadataOutputStream); String[] regionIds; if (selectedMasks != null) { regionIds = new String[selectedMasks.length]; for (int i = 0; i < selectedMasks.length; i++) { if (selectedMasks[i] != null) { regionIds[i] = selectedMasks[i].getName(); } else { regionIds[i] = "\t"; } } } else { regionIds = new String[]{"full_scene"}; } final String[] algorithmNames = { "minimum", "maximum", "median", "average", "sigma", "p90_threshold", "p95_threshold", "total" }; final StatisticsOutputContext outputContext = StatisticsOutputContext.create( new Product[]{dataProvider.getRasterDataNode().getProduct()}, algorithmNames, regionIds); metadataWriter.initialiseOutput(outputContext); csvStatisticsWriter.initialiseOutput(outputContext); final Map<String, Object> statistics = new HashMap<>(); final Histogram[] histograms = dataProvider.getHistograms(); for (int i = 0; i < histograms.length; i++) { final Histogram histogram = histograms[i]; statistics.put("minimum", histogram.getLowValue(0)); statistics.put("maximum", histogram.getHighValue(0)); statistics.put("median", histogram.getPTileThreshold(0.5)[0]); statistics.put("average", histogram.getMean()[0]); statistics.put("sigma", histogram.getStandardDeviation()[0]); statistics.put("p90_threshold", histogram.getPTileThreshold(0.9)[0]); statistics.put("p95_threshold", histogram.getPTileThreshold(0.95)[0]); statistics.put("total", histogram.getTotals()[0]); csvStatisticsWriter.addToOutput(dataProvider.getRasterDataNode().getName(), regionIds[i], statistics); metadataWriter.addToOutput(dataProvider.getRasterDataNode().getName(), regionIds[i], statistics); statistics.clear(); } csvStatisticsWriter.finaliseOutput(); metadataWriter.finaliseOutput(); } catch (IOException exception) { Dialogs.showMessage("Statistics export", "Failed to export statistics.\nAn error occurred:" + exception.getMessage(), JOptionPane.ERROR_MESSAGE, null); } finally { if (metadataOutputStream != null) { metadataOutputStream.close(); } if (csvOutputStream != null) { csvOutputStream.close(); } } // JOptionPane.showMessageDialog(VisatApp.getApp().getApplicationWindow(), // "The statistics have successfully been exported to '" + outputAsciiFile + // "'.", // "Statistics export", // JOptionPane.INFORMATION_MESSAGE); Dialogs.showMessage("Statistics export", "The statistics have successfully been exported to '" + outputAsciiFile + "'.", JOptionPane.INFORMATION_MESSAGE, null); } public void setSelectedMasks(Mask[] selectedMasks) { this.selectedMasks = selectedMasks; } }
7,170
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
XYImagePlot.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/XYImagePlot.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import com.bc.ceres.core.Assert; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.CrosshairState; import org.jfree.chart.plot.PlotRenderingInfo; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.data.xy.DefaultXYDataset; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; /** * An X/Y plot that uses a buffered image to display its data. * * @author Norman Fomferra */ public class XYImagePlot extends XYPlot { private BufferedImage image; private Rectangle2D imageDataBounds; private final Object imageLock = new Object(); public XYImagePlot() { super(null, new NumberAxis("X"), new NumberAxis("Y"), new XYLineAndShapeRenderer(false, false)); } public BufferedImage getImage() { synchronized (imageLock) { return image; } } public void setImage(BufferedImage image) { synchronized (imageLock) { this.image = image; if (image != null && imageDataBounds == null) { setImageDataBounds(new Rectangle(0, 0, image.getWidth(), image.getHeight())); } } } public Rectangle2D getImageDataBounds() { synchronized (imageLock) { return imageDataBounds != null ? (Rectangle2D) imageDataBounds.clone() : null; } } public void setImageDataBounds(Rectangle2D imageDataBounds) { synchronized (imageLock) { this.imageDataBounds = (Rectangle2D) imageDataBounds.clone(); DefaultXYDataset xyDataset = new DefaultXYDataset(); xyDataset.addSeries("Image Data Bounds", new double[][]{ {imageDataBounds.getMinX(), imageDataBounds.getMaxX()}, {imageDataBounds.getMinY(), imageDataBounds.getMaxY()} }); setDataset(xyDataset); getDomainAxis().setRange(imageDataBounds.getMinX(), imageDataBounds.getMaxX()); getRangeAxis().setRange(imageDataBounds.getMinY(), imageDataBounds.getMaxY()); } } @Override public boolean render(Graphics2D g2, Rectangle2D dataArea, int index, PlotRenderingInfo info, CrosshairState crosshairState) { final boolean foundData = super.render(g2, dataArea, index, info, crosshairState); if (image != null) { final int dx1 = (int) dataArea.getMinX(); final int dy1 = (int) dataArea.getMinY(); final int dx2 = (int) dataArea.getMaxX(); final int dy2 = (int) dataArea.getMaxY(); synchronized (imageLock) { final Rectangle rectangle = getImageSourceArea(); final int sx1 = rectangle.x; final int sy1 = rectangle.y; final int sx2 = sx1 + rectangle.width - 1; final int sy2 = sy1 + rectangle.height - 1; g2.drawImage(image, dx1, dy1, dx2, dy2, sx1, sy1, sx2, sy2, null); } } return foundData; } final Rectangle getImageSourceArea() { Assert.notNull(image); Assert.notNull(imageDataBounds); final ValueAxis xAxis = getDomainAxis(); final ValueAxis yAxis = getRangeAxis(); final double scaleX = image.getWidth() / imageDataBounds.getWidth(); final double scaleY = image.getHeight() / imageDataBounds.getHeight(); final int x = crop(scaleX * (xAxis.getLowerBound() - imageDataBounds.getMinX()), 0, image.getWidth() - 1); final int y = crop(scaleY * (imageDataBounds.getMaxY() - yAxis.getUpperBound()), 0, image.getHeight() - 1); final int w = crop(scaleX * (xAxis.getUpperBound() - xAxis.getLowerBound()), 1, image.getWidth()); final int h = crop(scaleY * (yAxis.getUpperBound() - yAxis.getLowerBound()), 1, image.getHeight()); return new Rectangle(x, y, w, h); } private static int crop(double v, int i1, int i2) { int i = (int) Math.round(v); if (i < i1) { return i1; } if (i > i2) { return i2; } return i; } }
4,982
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
XYPlotToolTipGenerator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/XYPlotToolTipGenerator.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import org.jfree.chart.labels.CustomXYToolTipGenerator; import org.jfree.data.xy.XYDataset; public class XYPlotToolTipGenerator extends CustomXYToolTipGenerator { @Override public String generateToolTip(XYDataset data, int series, int item) { final Comparable key = data.getSeriesKey(series); final double valueX = data.getXValue(series, item); final double valueY = data.getYValue(series, item); return String.format("%s: X = %6.2f, Y = %6.2f", key, valueX, valueY); } }
1,280
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GeoCodingPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/GeoCodingPanel.java
/* * Copyright (C) 2011 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.dataio.geocoding.ComponentGeoCoding; import org.esa.snap.core.dataio.geocoding.GeoRaster; import org.esa.snap.core.datamodel.BasicPixelGeoCoding; import org.esa.snap.core.datamodel.CombinedFXYGeoCoding; import org.esa.snap.core.datamodel.CrsGeoCoding; import org.esa.snap.core.datamodel.FXYGeoCoding; import org.esa.snap.core.datamodel.GcpGeoCoding; import org.esa.snap.core.datamodel.GeoCoding; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.MapGeoCoding; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.TiePointGeoCoding; import org.esa.snap.core.dataop.maptransf.MapInfo; import org.esa.snap.core.param.Parameter; import org.esa.snap.core.util.math.FXYSum; import org.openide.windows.TopComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Rectangle; import java.util.List; /** * @author Thomas Storm * @author Tonio Fincke */ class GeoCodingPanel extends PagePanel { private static final String DEFAULT_INFORMATION_TEXT = "No geo-coding information available."; /*I18N*/ private static final String TITLE_PREFIX = "Geo-Coding"; /*I18N*/ private GeoCoding geoCoding; private JPanel contentPanel; private TableLayout contentLayout; private int currentRow; private StringBuilder dataAsTextBuilder; public GeoCodingPanel(TopComponent topComponent, String helpId) { super(topComponent, helpId, TITLE_PREFIX); } @Override protected boolean mustHandleSelectionChange() { final RasterDataNode raster = getRaster(); return super.mustHandleSelectionChange() || (raster != null && geoCoding != raster.getGeoCoding()); } @Override public void nodeChanged(final ProductNodeEvent event) { if (Product.PROPERTY_NAME_SCENE_GEO_CODING.equals(event.getPropertyName())) { if (event.getSourceNode() instanceof Product) { geoCoding = getProduct().getSceneGeoCoding(); } else { geoCoding = getRaster().getGeoCoding(); } updateComponents(); } } @Override protected void initComponents() { contentPanel = new JPanel(); resetContentPanel(); final JScrollPane scrollPane = new JScrollPane(contentPanel); scrollPane.getHorizontalScrollBar().setUnitIncrement(20); scrollPane.getVerticalScrollBar().setUnitIncrement(20); add(scrollPane, BorderLayout.CENTER); } @Override protected void updateComponents() { if (isVisible()) { currentRow = 0; updateContent(); if (geoCoding == null) { contentLayout.setColumnWeightX(0, 1.0); showNoInformationAvailableMessage(); } updateUI(); } } private void resetContentPanel() { contentPanel.removeAll(); contentLayout = new TableLayout(6); contentLayout.setTablePadding(2, 2); contentLayout.setTableFill(TableLayout.Fill.BOTH); contentLayout.setColumnWeightX(0, 0.0); contentLayout.setTableWeightX(1.0); contentLayout.setTableWeightY(0.0); contentLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); contentPanel.setLayout(contentLayout); } private void showNoInformationAvailableMessage() { contentPanel.add(new JLabel(DEFAULT_INFORMATION_TEXT)); contentPanel.add(contentLayout.createVerticalSpacer()); dataAsTextBuilder.append(DEFAULT_INFORMATION_TEXT); } @Override protected String getDataAsText() { return dataAsTextBuilder.toString(); } private void updateContent() { resetContentPanel(); dataAsTextBuilder = new StringBuilder(); final RasterDataNode raster = getRaster(); final Product product = getProduct(); boolean usingMultiGeoCodings = false; GeoCoding sceneGeoCoding = null; if (product != null) { usingMultiGeoCodings = isUsingMultiGeoCoding(product); sceneGeoCoding = product.getSceneGeoCoding(); } PixelPos sceneCenter = new PixelPos(); PixelPos sceneUL = new PixelPos(); PixelPos sceneUR = new PixelPos(); PixelPos sceneLL = new PixelPos(); PixelPos sceneLR = new PixelPos(); String nodeType = ""; if (product != null) { if (usingMultiGeoCodings) { addEmptyRow(); addRow("Some bands come with an individual geo-coding that differs from the geo-coding of the product. Select a band to see the bands individual geo-coding."); addEmptyRow(); } nodeType = "product"; geoCoding = sceneGeoCoding; sceneCenter = new PixelPos(Math.floor(product.getSceneRasterWidth() / 2.0) + 0.5, Math.floor(product.getSceneRasterHeight() / 2.0) + 0.5); sceneUL = new PixelPos(0 + 0.5f, 0 + 0.5f); sceneUR = new PixelPos(product.getSceneRasterWidth() - 1 + 0.5f, 0 + 0.5f); sceneLL = new PixelPos(0 + 0.5f, product.getSceneRasterHeight() - 1 + 0.5f); sceneLR = new PixelPos(product.getSceneRasterWidth() - 1 + 0.5f, product.getSceneRasterHeight() - 1 + 0.5f); } if (raster != null && usingMultiGeoCodings) { nodeType = "band"; geoCoding = raster.getGeoCoding(); if (sceneGeoCoding != null && geoCoding == sceneGeoCoding) { addEmptyRow(); addRow("This band uses the same geo-coding as the product."); addEmptyRow(); } sceneCenter = new PixelPos(Math.floor(raster.getRasterWidth() / 2.0) + 0.5, Math.floor(raster.getRasterHeight() / 2.0) + 0.5); sceneUL = new PixelPos(0 + 0.5, 0 + 0.5); sceneUR = new PixelPos(raster.getRasterWidth() - 1 + 0.5, 0 + 0.5); sceneLL = new PixelPos(0 + 0.5, raster.getRasterHeight() - 1 + 0.5); sceneLR = new PixelPos(raster.getRasterWidth() - 1 + 0.5, raster.getRasterHeight() - 1 + 0.5); } writeGeoCoding(geoCoding, sceneCenter, sceneUL, sceneUR, sceneLL, sceneLR, nodeType); } public boolean isUsingMultiGeoCoding(Product product) { final GeoCoding geoCoding = product.getSceneGeoCoding(); if (geoCoding == null) { return false; } final List<RasterDataNode> rasterDataNodes = product.getRasterDataNodes(); for (RasterDataNode rasterDataNode : rasterDataNodes) { if (geoCoding != rasterDataNode.getGeoCoding()) { return true; } } return false; } private void writeGeoCoding(final GeoCoding geoCoding, final PixelPos sceneCenter, final PixelPos sceneUpperLeft, final PixelPos sceneUpperRight, final PixelPos sceneLowerLeft, final PixelPos sceneLowerRight, final String nodeType) { if (geoCoding != null) { GeoPos gp = new GeoPos(); gp = geoCoding.getGeoPos(sceneCenter, gp); addRow("Center latitude", gp.getLatString()); addRow("Center longitude", gp.getLonString()); gp = geoCoding.getGeoPos(sceneUpperLeft, gp); addRow("Upper left latitude", gp.getLatString()); addRow("Upper left longitude", gp.getLonString()); gp = geoCoding.getGeoPos(sceneUpperRight, gp); addRow("Upper right latitude", gp.getLatString()); addRow("Upper right longitude", gp.getLonString()); gp = geoCoding.getGeoPos(sceneLowerLeft, gp); addRow("Lower left latitude", gp.getLatString()); addRow("Lower left longitude", gp.getLonString()); gp = geoCoding.getGeoPos(sceneLowerRight, gp); addRow("Lower right latitude", gp.getLatString()); addRow("Lower right longitude", gp.getLonString()); addEmptyRow(); addRowWithTextField("WKT of the image CRS", geoCoding.getImageCRS().toString()); addRowWithTextField("WKT of the geographical CRS", geoCoding.getGeoCRS().toString()); addEmptyRow(); } if (geoCoding instanceof TiePointGeoCoding) { writeTiePointGeoCoding((TiePointGeoCoding) geoCoding, nodeType); } else if (geoCoding instanceof ComponentGeoCoding) { writeComponentGeoCoding((ComponentGeoCoding) geoCoding, nodeType); } else if (geoCoding instanceof BasicPixelGeoCoding) { writePixelGeoCoding((BasicPixelGeoCoding) geoCoding, nodeType); } else if (geoCoding instanceof MapGeoCoding) { writeMapGeoCoding((MapGeoCoding) geoCoding, nodeType); } else if (geoCoding instanceof FXYGeoCoding) { writeFXYGeoCoding((FXYGeoCoding) geoCoding, nodeType); } else if (geoCoding instanceof CombinedFXYGeoCoding) { writeCombinedFXYGeoCoding((CombinedFXYGeoCoding) geoCoding, nodeType); } else if (geoCoding instanceof GcpGeoCoding) { writeGcpGeoCoding((GcpGeoCoding) geoCoding, nodeType); } else if (geoCoding instanceof CrsGeoCoding) { writeCrsGeoCoding((CrsGeoCoding) geoCoding, nodeType); } else if (geoCoding != null) { writeUnknownGeoCoding(geoCoding, nodeType); } else { addRow("The " + nodeType + " has no geo-coding information."); } } private void addHeaderRow(String content) { StringBuilder b = new StringBuilder(); for (int i = 0; i < content.length(); i++) { b.append('='); } contentLayout.setCellColspan(currentRow++, 0, 6); contentPanel.add(getCorrectlyColouredLabel(b.toString())); contentLayout.setCellColspan(currentRow++, 0, 6); contentPanel.add(getCorrectlyColouredLabel(content)); contentLayout.setCellColspan(currentRow++, 0, 6); contentPanel.add(getCorrectlyColouredLabel(b.toString())); dataAsTextBuilder.append(b.toString()).append("/n").append(content).append("/n").append(b.toString()).append("/n"); } private void addRow(String content) { contentLayout.setCellColspan(currentRow++, 0, 6); contentPanel.add(getCorrectlyColouredLabel(content)); dataAsTextBuilder.append(content).append("/n"); } private void addRow(String name, String value) { contentLayout.setCellColspan(currentRow++, 1, 5); contentPanel.add(getCorrectlyColouredLabel(name)); contentPanel.add(getCorrectlyColouredLabel(value)); dataAsTextBuilder.append(name).append("/t").append(value).append("/n"); } private void addRowWithTextField(String name, String value) { contentLayout.setCellColspan(currentRow++, 1, 5); contentPanel.add(getCorrectlyColouredLabel(name)); final JTextArea textArea = new JTextArea(value); textArea.setBackground(getBackgroundColor()); textArea.setEditable(false); contentPanel.add(textArea); dataAsTextBuilder.append(name).append("/t").append(value).append("/n"); } private void addEmptyRow() { contentPanel.add(contentLayout.createVerticalSpacer()); currentRow++; dataAsTextBuilder.append("/n"); } private void addRow(String... values) { for (String value : values) { contentPanel.add(getCorrectlyColouredLabel(value)); dataAsTextBuilder.append(value).append("/t"); } currentRow++; dataAsTextBuilder.append("/n"); } private JLabel getCorrectlyColouredLabel(String value) { final JLabel label = new JLabel(value); label.setBackground(getBackgroundColor()); label.setOpaque(true); return label; } private Color getBackgroundColor() { final Color white = Color.WHITE; if (currentRow % 2 == 0) { return new Color((14 * white.getRed()) / 15, (14 * white.getGreen()) / 15, (14 * white.getBlue()) / 15); } return white; } private void writeGcpGeoCoding(GcpGeoCoding gcpGeoCoding, String nodeType) { addEmptyRow(); addRow("The " + nodeType + " uses a geo-coding which is based on ground control points (GCPs)."); addEmptyRow(); ProductNodeGroup<Placemark> gcpGroup = getProduct().getGcpGroup(); addRow("Number Of GCPs", String.valueOf(gcpGroup.getNodeCount())); addRow("Function", String.valueOf(gcpGeoCoding.getMethod())); addRow("Datum", String.valueOf(gcpGeoCoding.getDatum().getName())); addRow("Latitude RMSE", String.valueOf(gcpGeoCoding.getRmseLat())); addRow("Longitude RMSE", String.valueOf(gcpGeoCoding.getRmseLon())); addEmptyRow(); addRow("Table of used GCPs"); Placemark[] gcps = gcpGroup.toArray(new Placemark[0]); addRow("Number", "Label", "X", "Y", "Latitude", "Longitude"); for (int i = 0; i < gcps.length; i++) { Placemark gcp = gcps[i]; PixelPos pixelPos = gcp.getPixelPos(); GeoPos geoPos = gcp.getGeoPos(); addRow(String.valueOf(i), gcp.getLabel(), String.valueOf(pixelPos.getX()), String.valueOf(pixelPos.getY()), geoPos.getLatString(), geoPos.getLonString()); } // setFirstColumnWidth(40); } private void writeCrsGeoCoding(CrsGeoCoding geoCoding, String nodeType) { addRow("The " + nodeType + " uses a geo-coding based on a cartographic map CRS."); addEmptyRow(); addRow("WKT of the map CRS", geoCoding.getMapCRS().toString()); addEmptyRow(); addRow("Image-to-map transformation", geoCoding.getImageToMapTransform().toString()); } private void writeUnknownGeoCoding(GeoCoding geoCoding, String nodeType) { addRow("The " + nodeType + " uses an unknown geo-coding implementation."); addRow("Class", geoCoding.getClass().getName()); addRow("Instance", geoCoding.toString()); } private void writeCombinedFXYGeoCoding(CombinedFXYGeoCoding combinedGeoCoding, String nodeType) { final CombinedFXYGeoCoding.CodingWrapper[] codingWrappers = combinedGeoCoding.getCodingWrappers(); addEmptyRow(); addRow("The " + nodeType + " uses a geo-coding which consists of multiple polynomial based geo-coding."); addEmptyRow(); addRow("The geo-coding uses " + codingWrappers.length + " polynomial based geo-codings"); for (int i = 0; i < codingWrappers.length; i++) { final CombinedFXYGeoCoding.CodingWrapper codingWrapper = codingWrappers[i]; final Rectangle region = codingWrapper.getRegion(); addHeaderRow("Geo-coding[" + (i + 1) + "]"); addRow("The region in the scene which is covered by this geo-coding is defined by:"); addRow("Location: X = " + region.x + ", Y = " + region.y + "\n"); addRow("Dimension: W = " + region.width + ", H = " + region.height); addEmptyRow(); final FXYGeoCoding fxyGeoCoding = codingWrapper.getGeoGoding(); addRow("<html>Geographic coordinates (lat,lon) are computed from pixel coordinates (x,y)<br/>" + "by using following polynomial equations</html>"); addRow(fxyGeoCoding.getLatFunction().createCFunctionCode("latitude", "x", "y")); addRow(fxyGeoCoding.getLonFunction().createCFunctionCode("longitude", "x", "y")); addEmptyRow(); addRow("<html>Pixels (x,y) are computed from geographic coordinates (lat,lon)<br/>" + "by using the following polynomial equations</html>"); addRow(fxyGeoCoding.getPixelXFunction().createCFunctionCode("x", "lat", "lon")); addRow(fxyGeoCoding.getPixelYFunction().createCFunctionCode("y", "lat", "lon")); } } private void writeFXYGeoCoding(FXYGeoCoding fxyGeoCoding, String nodeType) { addEmptyRow(); addRow("The " + nodeType + " uses a polynomial based geo-coding."); addEmptyRow(); addRow("<html>Geographic coordinates (lat,lon) are computed from pixel coordinates (x,y)<br/>" + "by using following polynomial equations</html>"); addRow(fxyGeoCoding.getLatFunction().createCFunctionCode("latitude", "x", "y")); addRow(fxyGeoCoding.getLonFunction().createCFunctionCode("longitude", "x", "y")); addEmptyRow(); addRow("<html>Pixels (x,y) are computed from geographic coordinates (lat,lon)<br/>" + "by using the following polynomial equations</html>"); addRow(fxyGeoCoding.getPixelXFunction().createCFunctionCode("x", "lat", "lon")); addRow(fxyGeoCoding.getPixelYFunction().createCFunctionCode("y", "lat", "lon")); } private void writeMapGeoCoding(MapGeoCoding mgc, String nodeType) { final MapInfo mi = mgc.getMapInfo(); addEmptyRow(); addRow("The " + nodeType + " uses a map-projection based geo-coding."); addEmptyRow(); addRow("Projection", mi.getMapProjection().getName()); addRow("Projection parameters"); final Parameter[] parameters = mi.getMapProjection().getMapTransform().getDescriptor().getParameters(); final double[] parameterValues = mi.getMapProjection().getMapTransform().getParameterValues(); for (int i = 0; i < parameters.length; i++) { addRow(parameters[i].getName(), String.valueOf(parameterValues[i]) + " " + parameters[i].getProperties().getPhysicalUnit()); } addEmptyRow(); addRow("Map CRS Name", mgc.getMapCRS().getName().toString()); addRow("Map CRS WKT"); addRow(mgc.getMapCRS().toWKT()); addEmptyRow(); addRow("Output parameters"); addRow("Datum", mi.getDatum().getName()); addRow("Reference pixel X", String.valueOf(mi.getPixelX())); addRow("Reference pixel Y", String.valueOf(mi.getPixelY())); addRow("Orientation", String.valueOf(mi.getOrientation()) + " degree"); String mapUnit = mi.getMapProjection().getMapUnit(); addRow("Northing", String.valueOf(mi.getNorthing()) + " " + mapUnit); addRow("Easting", String.valueOf(mi.getEasting()) + " " + mapUnit); addRow("Pixel size X", String.valueOf(mi.getPixelSizeX()) + " " + mapUnit); addRow("Pixel size Y", String.valueOf(mi.getPixelSizeY()) + " " + mapUnit); } private void writePixelGeoCoding(BasicPixelGeoCoding gc, String nodeType) { addEmptyRow(); addRow("The " + nodeType + " uses a pixel based geo-coding."); addEmptyRow(); addRow("Name of latitude band", gc.getLatBand().getName()); addRow("Name of longitude band", gc.getLonBand().getName()); addRow("Search radius", gc.getSearchRadius() + " pixels"); final String validMask = gc.getValidMask(); addRow("Valid pixel mask", validMask != null ? validMask : ""); addRow("Crossing 180 degree meridian", String.valueOf(gc.isCrossingMeridianAt180())); addEmptyRow(); addRow("<html>Geographic coordinates (lat,lon) are computed from pixel coordinates (x,y)<br/>" + "by linear interpolation between pixels.</html>"); addEmptyRow(); addRow("<html>Pixel coordinates (x,y) are computed from geographic coordinates (lat,lon)<br/>" + "by a search algorithm.</html>"); addEmptyRow(); } private void writeComponentGeoCoding(ComponentGeoCoding gc, String nodeType) { addHeaderRow("The " + nodeType + " uses a component composed geo-coding."); addRow("Type:", gc.getClass().getSimpleName()); addEmptyRow(); addHeaderRow("The component geo-coding consists of:"); addRow("Forward coding:", gc.getForwardCoding().getKey()); addRow("Inverse coding:", gc.getInverseCoding().getKey()); addRow("A configured geo raster component"); final GeoRaster geoRaster = gc.getGeoRaster(); addEmptyRow(); addHeaderRow("The GeoRaster consists of:"); addRow("Name of latitude raster:", geoRaster.getLatVariableName()); addRow("Name of longitude raster:", geoRaster.getLonVariableName()); addRow("Raster resolution:", geoRaster.getRasterResolutionInKm() + " in km"); addRow("Number of longitude values:", "" + geoRaster.getLongitudes().length); addRow("Number of latitude values:", "" + geoRaster.getLatitudes().length); addRow("Raster width:", "" + geoRaster.getRasterWidth()); addRow("Raster height:", "" + geoRaster.getRasterHeight()); addRow("Scene width:", "" + geoRaster.getSceneWidth()); addRow("Scene height:", "" + geoRaster.getSceneHeight()); addRow("Offset X:", "" + geoRaster.getOffsetX()); addRow("Offset Y:", "" + geoRaster.getOffsetY()); addRow("Subsampling X:", "" + geoRaster.getSubsamplingX()); addRow("Subsampling Y:", "" + geoRaster.getSubsamplingY()); addEmptyRow(); addHeaderRow("Additional information:"); addRow("Can get geo position:", "" + gc.canGetGeoPos()); addRow("Can get pixel position:", "" + gc.canGetPixelPos()); addRow("Crossing 180 degree meridian", String.valueOf(gc.isCrossingMeridianAt180())); addEmptyRow(); } private void writeTiePointGeoCoding(TiePointGeoCoding tgc, String nodeType) { addRow("The " + nodeType + " uses a tie-point based geo-coding."); addEmptyRow(); addRow("Name of latitude tie-point grid", tgc.getLatGrid().getName()); addRow("Name of longitude tie-point grid", tgc.getLonGrid().getName()); addRow("Crossing 180 degree meridian", String.valueOf(tgc.isCrossingMeridianAt180())); addEmptyRow(); addRow("<html>Geographic coordinates (lat,lon) are computed from pixel coordinates (x,y)<br/>" + "by linear interpolation between tie points.</html>"); final int numApproximations = tgc.getNumApproximations(); if (numApproximations > 0) { addRow("<html>Pixel coordinates (x,y) are computed from geographic coordinates (lat,lon)<br/>" + "by polynomial approximations for " + numApproximations + " tile(s).</html>"); addEmptyRow(); for (int i = 0; i < numApproximations; i++) { final TiePointGeoCoding.Approximation approximation = tgc.getApproximation(i); final FXYSum fX = approximation.getFX(); final FXYSum fY = approximation.getFY(); addHeaderRow("Approximation for tile " + (i + 1)); addRow("Center latitude", String.valueOf(approximation.getCenterLat()) + " degree"); addRow("Center longitude", String.valueOf(approximation.getCenterLon()) + " degree"); addRow("RMSE for X", String.valueOf(fX.getRootMeanSquareError()) + " pixels"); addRow("RMSE for Y", String.valueOf(fY.getRootMeanSquareError()) + " pixels"); addRow("Max. error for X", String.valueOf(fX.getMaxError()) + " pixels"); addRow("Max. error for Y", String.valueOf(fY.getMaxError()) + " pixels"); } } else { addEmptyRow(); addRow( "<html>WARNING: Pixel coordinates (x,y) cannot be computed from geographic coordinates (lat,lon)<br/>" + "because appropriate polynomial approximations could not be found.</html>"); } } }
25,103
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProfileDataTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ProfileDataTableModel.java
package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.TransectProfileData; import org.esa.snap.ui.io.CsvEncoder; import org.esa.snap.ui.io.TableModelCsvEncoder; import org.opengis.feature.Property; import org.opengis.feature.simple.SimpleFeature; import javax.swing.table.AbstractTableModel; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Norman Fomferra */ class ProfileDataTableModel extends AbstractTableModel implements CsvEncoder { private final static String REF_SUFFIX = "_ref"; private final TransectProfileData profileData; private final List<String> columnNames; private final Map<Integer, Integer> propertyIndices; private final int[] pointDataIndexes; private final int dataFieldIndex; private final SimpleFeature[] features; private final boolean computeInBetweenPoints; public ProfileDataTableModel(String sampleName, TransectProfileData profileData, ProfilePlotPanel.DataSourceConfig dataSourceConfig) { this.profileData = profileData; pointDataIndexes = new int[profileData.getNumPixels()]; Arrays.fill(pointDataIndexes, -1); int[] shapeVertexIndexes = profileData.getShapeVertexIndexes(); for (int i = 0; i < shapeVertexIndexes.length; i++) { int shapeVertexIndex = shapeVertexIndexes[i]; pointDataIndexes[shapeVertexIndex] = i; } computeInBetweenPoints = dataSourceConfig.computeInBetweenPoints; final String corrDataName; if (dataSourceConfig.pointDataSource != null && dataSourceConfig.dataField != null) { corrDataName = dataSourceConfig.dataField.getLocalName(); features = dataSourceConfig.pointDataSource.getFeatureCollection().toArray(new SimpleFeature[0]); dataFieldIndex = dataSourceConfig.pointDataSource.getFeatureType().indexOf(corrDataName); } else { corrDataName = ""; features = null; dataFieldIndex = -1; } columnNames = new ArrayList<String>(); columnNames.add("pixel_no"); columnNames.add("pixel_x"); columnNames.add("pixel_y"); columnNames.add("latitude"); columnNames.add("longitude"); columnNames.add(sampleName + "_mean"); columnNames.add(sampleName + "_sigma"); columnNames.add(corrDataName.trim().length() == 0 ? "" : corrDataName + REF_SUFFIX); propertyIndices = new HashMap<Integer, Integer>(); if (features != null && features.length > 0) { final int colStart = 8; int validPropertyCount = 0; final Collection<Property> props = features[0].getProperties(); final Property[] properties = props.toArray(new Property[props.size()]); for (int i = 0; i < properties.length; i++) { Property property = properties[i]; final String name = property.getName().toString(); if (!corrDataName.equals(name)) { columnNames.add(name + REF_SUFFIX); propertyIndices.put(colStart + validPropertyCount, i); validPropertyCount++; } } } } @Override public int getColumnCount() { return columnNames.size(); } @Override public String getColumnName(int column) { return columnNames.get(column); } @Override public int getRowCount() { return computeInBetweenPoints ? profileData.getNumPixels() : profileData.getNumShapeVertices(); } @Override public Object getValueAt(int row, int column) { int pixelIndex = computeInBetweenPoints ? row : profileData.getShapeVertexIndexes()[row]; if (column == 0) { return pixelIndex + 1; } else if (column == 1) { return profileData.getPixelPositions()[pixelIndex].getX(); } else if (column == 2) { return profileData.getPixelPositions()[pixelIndex].getY(); } else if (column == 3) { GeoPos[] geoPositions = profileData.getGeoPositions(); return geoPositions.length > 0 ? geoPositions[pixelIndex].getLat() : null; } else if (column == 4) { GeoPos[] geoPositions = profileData.getGeoPositions(); return geoPositions.length > 0 ? geoPositions[pixelIndex].getLon() : null; } else if (column == 5) { return profileData.getSampleValues()[pixelIndex]; } else if (column == 6) { return profileData.getSampleSigmas()[pixelIndex]; } else if (column == 7) { if (dataFieldIndex == -1) { return null; } int pointDataIndex = pointDataIndexes[pixelIndex]; if (pointDataIndex == -1) { return null; } return features[pointDataIndex].getAttribute(dataFieldIndex); } else if (column < getColumnCount()) { int pointDataIndex = pointDataIndexes[pixelIndex]; if (pointDataIndex == -1) { return null; } final Collection<Property> propColl = features[pointDataIndex].getProperties(); final Property[] properties = propColl.toArray(new Property[propColl.size()]); final Integer propertyIndex = propertyIndices.get(column); return properties[propertyIndex].getValue(); } return null; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return false; } public String toCsv() { StringWriter sw = new StringWriter(); try { encodeCsv(sw); sw.close(); } catch (IOException e) { throw new IllegalStateException(e); } return sw.toString(); } @Override public void encodeCsv(Writer writer) throws IOException { new TableModelCsvEncoder(this).encodeCsv(writer); } }
6,279
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskSelectionToolSupport.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/MaskSelectionToolSupport.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.statistics; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.util.ProductUtils; import org.jfree.chart.ChartPanel; import javax.swing.JCheckBoxMenuItem; import javax.swing.JMenuItem; import java.awt.Color; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * @author Norman Fomferra */ public abstract class MaskSelectionToolSupport implements PlotAreaSelectionTool.Action { private final PagePanel pagePanel; private final ChartPanel chartPanel; private final String maskName; private final String maskDescription; private final Color maskColor; private final PlotAreaSelectionTool.AreaType areaType; private PlotAreaSelectionTool plotAreaSelectionTool; protected MaskSelectionToolSupport(PagePanel pagePanel, ChartPanel chartPanel, String maskName, String maskDescription, Color maskColor, PlotAreaSelectionTool.AreaType areaType) { this.pagePanel = pagePanel; this.chartPanel = chartPanel; this.maskName = maskName; this.maskDescription = maskDescription; this.maskColor = maskColor; this.areaType = areaType; } public JCheckBoxMenuItem createMaskSelectionModeMenuItem() { final JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(String.format("Select Mask '%s'", maskName)); menuItem.setName("maskSelectionMode"); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (menuItem.isSelected()) { if (plotAreaSelectionTool == null) { plotAreaSelectionTool = new PlotAreaSelectionTool(chartPanel, MaskSelectionToolSupport.this); plotAreaSelectionTool.setAreaType(areaType); plotAreaSelectionTool.setFillPaint(createAlphaColor(maskColor, 50)); } plotAreaSelectionTool.install(); } else { if (plotAreaSelectionTool != null) { plotAreaSelectionTool.uninstall(); } } } }); return menuItem; } public JMenuItem createDeleteMaskMenuItem() { final JMenuItem menuItem = new JMenuItem(String.format("Delete Mask '%s' ", maskName)); menuItem.setName("deleteMask"); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (plotAreaSelectionTool != null) { plotAreaSelectionTool.removeAnnotation(); } Product product = pagePanel.getProduct(); if (product != null) { Mask mask = product.getMaskGroup().get(maskName); if (mask != null) { product.getMaskGroup().remove(mask); } } } }); return menuItem; } @Override public void areaSelected(PlotAreaSelectionTool.AreaType areaType, Shape shape) { Product product = pagePanel.getProduct(); final RasterDataNode raster = pagePanel.getRaster(); if (product == null || raster == null) { return; } String expression = createMaskExpression(areaType, shape); Mask mask = product.getMaskGroup().get(maskName); if (mask != null) { if (!mask.getRasterSize().equals(raster.getRasterSize())) { // if sizes are different we need to remove the mask first and add it as new one product.getMaskGroup().remove(mask); mask = addMask(product, raster, expression); } else { mask.getImageConfig().setValue("expression", expression); } } else { mask = addMask(product, raster, expression); } ProductNodeGroup<Mask> overlayMaskGroup = raster.getOverlayMaskGroup(); if (!overlayMaskGroup.contains(mask)) { overlayMaskGroup.add(mask); } } private Mask addMask(Product product, RasterDataNode raster, String expression) { Mask mask = Mask.BandMathsType.create(maskName, maskDescription, raster.getRasterWidth(), raster.getRasterHeight(), expression, maskColor, 0.5); product.addMask(mask); ProductUtils.copyImageGeometry(raster, mask, false); return mask; } protected abstract String createMaskExpression(PlotAreaSelectionTool.AreaType areaType, Shape shape); private static Color createAlphaColor(Color color, int alpha) { return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); } }
5,817
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AbstractStatisticsTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/AbstractStatisticsTopComponent.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.statistics; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.support.AbstractLayerListener; import com.bc.ceres.glayer.support.LayerUtils; import com.bc.ceres.swing.selection.SelectionChangeEvent; import com.bc.ceres.swing.selection.SelectionChangeListener; 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.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.SelectionSupport; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.ui.product.VectorDataLayer; import org.esa.snap.ui.product.VectorDataLayerFilterFactory; import org.openide.util.HelpCtx; import org.openide.windows.TopComponent; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.geom.Rectangle2D; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.EXPLORER; /** * The window containing all statistics. * * @author Marco Peters * @author Tonio Fincke */ public abstract class AbstractStatisticsTopComponent extends TopComponent implements HelpCtx.Provider { private PagePanel pagePanel; private Product product; private final PagePanelLL pagePanelLL; private final SelectionChangeListener pagePanelSCL; private final PagePanelProductHandler pagePanelProductListener; private final PagePanelProductSceneViewHandler pagePanelProductSceneViewListener; private final PagePanelProductRemovedListener pagePanelProductRemovedListener; protected AbstractStatisticsTopComponent() { pagePanelProductListener = new PagePanelProductHandler(); pagePanelProductSceneViewListener = new PagePanelProductSceneViewHandler(); pagePanelProductRemovedListener = new PagePanelProductRemovedListener(); pagePanelLL = new PagePanelLL(); pagePanelSCL = new PagePanelSCL(); initComponent(); } public void initComponent() { setLayout(new BorderLayout()); pagePanel = createPagePanel(); pagePanel.initComponents(); setCurrentSelection(); add(pagePanel, BorderLayout.CENTER); } protected abstract PagePanel createPagePanel(); public abstract HelpCtx getHelpCtx(); @Override public void componentShowing() { final SnapApp snapApp = SnapApp.getDefault(); snapApp.getProductManager().addListener(pagePanelProductRemovedListener); snapApp.getSelectionSupport(ProductNode.class).addHandler(pagePanelProductListener); snapApp.getSelectionSupport(ProductSceneView.class).addHandler(pagePanelProductSceneViewListener); final ProductSceneView productSceneView = snapApp.getSelectedProductSceneView(); addViewListener(productSceneView); setCurrentSelection(); transferProductNodeListener(null, product); } @Override public void componentHidden() { transferProductNodeListener(product, null); final SnapApp snapApp = SnapApp.getDefault(); snapApp.getProductManager().removeListener(pagePanelProductRemovedListener); snapApp.getSelectionSupport(ProductNode.class).removeHandler(pagePanelProductListener); snapApp.getSelectionSupport(ProductSceneView.class).removeHandler(pagePanelProductSceneViewListener); removeViewListener(snapApp.getSelectedProductSceneView()); } private void addViewListener(ProductSceneView view) { if (view != null) { view.getRootLayer().addListener(pagePanelLL); view.getFigureEditor().addSelectionChangeListener(pagePanelSCL); } } private void removeViewListener(ProductSceneView view) { if (view != null) { view.getRootLayer().removeListener(pagePanelLL); view.getFigureEditor().removeSelectionChangeListener(pagePanelSCL); } } private void transferProductNodeListener(Product oldProduct, Product newProduct) { if (oldProduct != newProduct) { if (oldProduct != null) { oldProduct.removeProductNodeListener(pagePanel); } if (newProduct != null) { newProduct.addProductNodeListener(pagePanel); } } } private void updateTitle() { setDisplayName(pagePanel.getTitle()); } void setCurrentSelection() { Product product = null; RasterDataNode raster = null; VectorDataNode vectorDataNode = null; final ProductNode selectedNode = SnapApp.getDefault().getSelectedProductNode(EXPLORER); if (selectedNode != null && selectedNode.getProduct() != null) { product = selectedNode.getProduct(); } if (selectedNode instanceof RasterDataNode) { raster = (RasterDataNode) selectedNode; } else if (selectedNode instanceof VectorDataNode) { vectorDataNode = (VectorDataNode) selectedNode; } selectionChanged(product, raster, vectorDataNode); } private void selectionChanged(final Product product, final RasterDataNode raster, final VectorDataNode vectorDataNode) { this.product = product; runInEDT(new Runnable() { @Override public void run() { pagePanel.selectionChanged(product, raster, vectorDataNode); updateTitle(); } }); } private void runInEDT(Runnable runnable) { if (SwingUtilities.isEventDispatchThread()) { runnable.run(); } else { SwingUtilities.invokeLater(runnable); } } private class PagePanelProductHandler implements SelectionSupport.Handler<ProductNode> { @Override public void selectionChange(ProductNode oldValue, ProductNode newValue) { if (newValue != null) { RasterDataNode raster = null; if (newValue instanceof RasterDataNode) { raster = (RasterDataNode) newValue; } VectorDataNode vector = null; if (newValue instanceof VectorDataNode) { vector = (VectorDataNode) newValue; final ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); if (sceneView != null) { raster = sceneView.getRaster(); } } Product product = newValue.getProduct(); if (product != null) { selectionChanged(product, raster, vector); } } } } private class PagePanelProductRemovedListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { //do nothing } @Override public void productRemoved(ProductManager.Event event) { selectionChanged(null, null, null); } } private class PagePanelProductSceneViewHandler implements SelectionSupport.Handler<ProductSceneView> { @Override public void selectionChange(ProductSceneView oldValue, ProductSceneView newValue) { if (oldValue != null) { removeViewListener(oldValue); } if (newValue != null) { addViewListener(newValue); VectorDataNode vectorDataNode = getVectorDataNode(newValue); selectionChanged(newValue.getRaster().getProduct(), newValue.getRaster(), vectorDataNode); } } private VectorDataNode getVectorDataNode(ProductSceneView view) { final Layer rootLayer = view.getRootLayer(); final Layer layer = LayerUtils.getChildLayer(rootLayer, LayerUtils.SearchMode.DEEP, VectorDataLayerFilterFactory.createGeometryFilter()); VectorDataNode vectorDataNode = null; if (layer instanceof VectorDataLayer) { VectorDataLayer vdl = (VectorDataLayer) layer; vectorDataNode = vdl.getVectorDataNode(); } return vectorDataNode; } } private class PagePanelLL extends AbstractLayerListener { @Override public void handleLayerDataChanged(Layer layer, Rectangle2D modelRegion) { pagePanel.handleLayerContentChanged(); } } private class PagePanelSCL implements SelectionChangeListener { @Override public void selectionChanged(SelectionChangeEvent event) { pagePanel.handleLayerContentChanged(); } @Override public void selectionContextChanged(SelectionChangeEvent event) { pagePanel.handleLayerContentChanged(); } } }
9,651
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PagePanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/PagePanel.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.statistics; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeListener; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.help.HelpDisplayer; import org.esa.snap.ui.tool.ToolButtonFactory; import org.openide.windows.TopComponent; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; /** * A general page within the statistics window. * * @author Marco Peters */ public abstract class PagePanel extends JPanel implements ProductNodeListener { private final TopComponent parentComponent; private final String helpId; private final String title; private Product product; private boolean productChanged; private RasterDataNode raster; private boolean rasterChanged; private VectorDataNode vectorData; private boolean vectorDataChanged; private PagePanel alternativeView; protected PagePanel(TopComponent parentComponent, String helpId, String title) { super(new BorderLayout(4, 4)); this.parentComponent = parentComponent; this.helpId = helpId; this.title = title; setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); setPreferredSize(new Dimension(600, 320)); } public String getTitle() { return title; } public VectorDataNode getVectorDataNode() { return vectorData; } public TopComponent getParentDialog() { return parentComponent; } /** * Notified when a node was added. * * @param event the product node which the listener to be notified */ @Override public void nodeAdded(ProductNodeEvent event) { } /** * Notified when a node changed. * * @param event the product node which the listener to be notified */ @Override public void nodeChanged(ProductNodeEvent event) { } /** * Notified when a node's data changed. * * @param event the product node which the listener to be notified */ @Override public void nodeDataChanged(ProductNodeEvent event) { } /** * Notified when a node was removed. * * @param event the product node which the listener to be notified */ @Override public void nodeRemoved(ProductNodeEvent event) { } protected Product getProduct() { return product; } protected RasterDataNode getRaster() { return raster; } protected boolean isRasterChanged() { return rasterChanged; } protected boolean isProductChanged() { return productChanged; } protected boolean isVectorDataNodeChanged() { return vectorDataChanged; } protected void setRaster(RasterDataNode raster) { if (this.raster != raster) { this.raster = raster; rasterChanged = true; } } protected void setVectorDataNode(VectorDataNode vectorDataNode) { if (this.vectorData != vectorDataNode) { this.vectorData = vectorDataNode; vectorDataChanged = true; } } /** * @return {@code true} if {@link #handleNodeSelectionChanged} shall be called in a reaction to a node selection change. */ protected boolean mustHandleSelectionChange() { return isRasterChanged() || isProductChanged(); } /** * Called in reaction to a node selection change and if {@link #mustHandleSelectionChange()} returns {@code true}. * The default implementation calls {@link #updateComponents}. */ protected void handleNodeSelectionChanged() { updateComponents(); } /** * Called in reaction to a layer content change. * The default implementation does nothing. */ protected void handleLayerContentChanged() { } /** * Initialises the panel's sub-components. */ protected abstract void initComponents(); /** * Updates the panel's sub-components as a reaction to a product node selection change. */ protected abstract void updateComponents(); protected abstract String getDataAsText(); protected void handlePopupCreated(JPopupMenu popupMenu) { } protected boolean checkDataToClipboardCopy() { return true; } protected AbstractButton getHelpButton() { if (helpId != null) { final AbstractButton helpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Help22.png"), false); helpButton.setToolTipText("Help."); helpButton.setName("helpButton"); helpButton.addActionListener(e -> HelpDisplayer.show(parentComponent.getHelpCtx())); return helpButton; } return null; } protected JMenuItem createCopyDataToClipboardMenuItem() { final JMenuItem menuItem = new JMenuItem("Copy Data to Clipboard"); /*I18N*/ menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { if (checkDataToClipboardCopy()) { copyTextDataToClipboard(); } } }); return menuItem; } protected void copyTextDataToClipboard() { final Cursor oldCursor = getCursor(); try { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); final String dataAsText = getDataAsText(); if (dataAsText != null) { SystemUtils.copyToClipboard(dataAsText); } } finally { setCursor(oldCursor); } } protected boolean hasAlternativeView(){ return alternativeView != null; } protected void showAlternativeView() { final TopComponent parent = (TopComponent) this.getParent(); parent.remove(this); this.setVisible(false); parent.add(alternativeView, BorderLayout.CENTER); alternativeView.setVisible(true); parent.revalidate(); } protected void setAlternativeView(PagePanel alternativeView) { this.alternativeView = alternativeView; } protected PagePanel getAlternativeView() { return alternativeView; } void selectionChanged(Product product, RasterDataNode raster, VectorDataNode vectorDataNode) { if (raster != getRaster() || product != getProduct() || vectorDataNode != getVectorDataNode()) { setRaster(raster); setProduct(product); setVectorDataNode(vectorDataNode); if (mustHandleSelectionChange()) { handleNodeSelectionChanged(); rasterChanged = false; productChanged = false; vectorDataChanged = false; } } } private void maybeOpenPopup(MouseEvent mouseEvent) { if (mouseEvent.isPopupTrigger()) { final JPopupMenu popupMenu = new JPopupMenu(); popupMenu.add(createCopyDataToClipboardMenuItem()); handlePopupCreated(popupMenu); final Point point = SwingUtilities.convertPoint(mouseEvent.getComponent(), mouseEvent.getPoint(), this); popupMenu.show(this, point.x, point.y); } } private String getProductNodeDisplayName() { if (raster != null) { return raster.getDisplayName(); } else { if (product != null) { return product.getDisplayName(); } else { return ""; } } } private void transferProductNodeListener(Product oldProduct, Product newProduct) { if (oldProduct != newProduct) { if (oldProduct != null) { oldProduct.removeProductNodeListener(this); } if (newProduct != null) { newProduct.addProductNodeListener(this); } } } private void setProduct(Product product) { if (this.product != product) { transferProductNodeListener(this.product, product); this.product = product; productChanged = true; } } class PopupHandler extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { maybeOpenPopup(e); } @Override public void mouseReleased(MouseEvent e) { maybeOpenPopup(e); } @Override public void mouseClicked(MouseEvent e) { maybeOpenPopup(e); } } }
9,913
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DensityPlotPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/DensityPlotPanel.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.statistics; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; 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.ProductNodeEvent; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.Stx; import org.esa.snap.core.datamodel.StxFactory; import org.esa.snap.core.dataop.barithm.BandArithmetic; 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.math.MathUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.GridBagUtils; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.ui.RectangleInsets; import org.openide.windows.TopComponent; import javax.swing.DefaultListCellRenderer; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.ListCellRenderer; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Shape; import java.awt.event.ItemEvent; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.awt.image.IndexColorModel; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.logging.Level; /** * The density plot pane within the statistics window. */ class DensityPlotPanel extends ChartPagePanel { private static final String NO_DATA_MESSAGE = "No scatter plot computed yet.\n" + "To create a scatter plot, select bands in both combo boxes.\n" + "The plot will be computed when you click the 'Refresh View' button.\n" + HELP_TIP_MESSAGE + "\n" + ZOOM_TIP_MESSAGE; private static final String CHART_TITLE = "Scatter Plot"; private final static String PROPERTY_NAME_AUTO_MIN_MAX = "autoMinMax"; private final static String PROPERTY_NAME_MIN = "min"; private final static String PROPERTY_NAME_MAX = "max"; private final static String PROPERTY_NAME_USE_ROI_MASK = "useRoiMask"; private final static String PROPERTY_NAME_ROI_MASK = "roiMask"; private final static String PROPERTY_NAME_X_PRODUCT = "xProduct"; private final static String PROPERTY_NAME_Y_PRODUCT = "yProduct"; private final static String PROPERTY_NAME_X_BAND = "xBand"; private final static String PROPERTY_NAME_Y_BAND = "yBand"; private static final int X_VAR = 0; private static final int Y_VAR = 1; private static final int NUM_DECIMALS = 2; private BindingContext bindingContext; private DataSourceConfig dataSourceConfig; private Property xProductProperty; private Property yProductProperty; private Property xBandProperty; private Property yBandProperty; private JComboBox<ListCellRenderer> xProductList; private JComboBox<ListCellRenderer> yProductList; private JComboBox<ListCellRenderer> xBandList; private JComboBox<ListCellRenderer> yBandList; //todo instead using referenceSize, use referenceSceneRasterTransform private Dimension referenceSize; private static AxisRangeControl[] axisRangeControls = new AxisRangeControl[2]; private IndexColorModel toggledColorModel; private IndexColorModel untoggledColorModel; private ChartPanel densityPlotDisplay; private XYImagePlot plot; private static final Color backgroundColor = new Color(255, 255, 255, 0); private boolean plotColorsInverted; private JCheckBox toggleColorCheckBox; DensityPlotPanel(TopComponent parentComponent, String helpId) { super(parentComponent, helpId, CHART_TITLE, true); } @Override protected void initComponents() { initParameters(); createUI(); initActionEnablers(); } private void initActionEnablers() { RefreshActionEnabler roiMaskActionEnabler = new RefreshActionEnabler(refreshButton, PROPERTY_NAME_USE_ROI_MASK, PROPERTY_NAME_ROI_MASK); roiMaskActionEnabler.addProductBandEnablement(PROPERTY_NAME_X_PRODUCT, PROPERTY_NAME_X_BAND); roiMaskActionEnabler.addProductBandEnablement(PROPERTY_NAME_Y_PRODUCT, PROPERTY_NAME_Y_BAND); bindingContext.addPropertyChangeListener(roiMaskActionEnabler); RefreshActionEnabler rangeControlActionEnabler = new RefreshActionEnabler(refreshButton, PROPERTY_NAME_MIN, PROPERTY_NAME_AUTO_MIN_MAX, PROPERTY_NAME_MAX); axisRangeControls[X_VAR].getBindingContext().addPropertyChangeListener(rangeControlActionEnabler); axisRangeControls[Y_VAR].getBindingContext().addPropertyChangeListener(rangeControlActionEnabler); } @Override public void nodeDataChanged(ProductNodeEvent event) { super.nodeDataChanged(event); if (!dataSourceConfig.useRoiMask) { return; } final Mask roiMask = dataSourceConfig.roiMask; if (roiMask == null) { return; } final ProductNode sourceNode = event.getSourceNode(); if (!(sourceNode instanceof Mask)) { return; } final String maskName = sourceNode.getName(); if (roiMask.getName().equals(maskName)) { updateComponents(); } } @Override protected void updateComponents() { super.updateComponents(); if (isRasterChanged() || isProductChanged()) { plot.setImage(null); plot.setDataset(null); if (isProductChanged()) { plot.getDomainAxis().setLabel("X"); plot.getRangeAxis().setLabel("Y"); } final ValueSet productValueSet = new ValueSet(createAvailableProductList()); xProductProperty.getDescriptor().setValueSet(productValueSet); yProductProperty.getDescriptor().setValueSet(productValueSet); if (productValueSet.getItems().length > 0) { Product currentProduct = getProduct(); try { xProductProperty.setValue(currentProduct); yProductProperty.setValue(currentProduct); } catch (ValidationException ignored) { Debug.trace(ignored); } } updateBandList(getProduct(), xBandProperty, false); updateBandList(getProduct(), yBandProperty, true); toggleColorCheckBox.setEnabled(false); } refreshButton.setEnabled(xBandProperty.getValue() != null && yBandProperty.getValue() != null); } private void updateBandList(final Product product, final Property bandProperty, boolean considerReferenceSize) { if (product == null) { return; } final ValueSet bandValueSet = new ValueSet(createAvailableBandList(product, considerReferenceSize)); bandProperty.getDescriptor().setValueSet(bandValueSet); if (bandValueSet.getItems().length > 0) { RasterDataNode currentRaster = getRaster(); if (bandValueSet.contains(getRaster())) { currentRaster = getRaster(); } try { bandProperty.setValue(currentRaster); } catch (ValidationException ignored) { Debug.trace(ignored); } } } private void initParameters() { axisRangeControls[X_VAR] = new AxisRangeControl("X-Axis"); axisRangeControls[Y_VAR] = new AxisRangeControl("Y-Axis"); initColorModels(); plotColorsInverted = false; dataSourceConfig = new DataSourceConfig(); bindingContext = new BindingContext(PropertyContainer.createObjectBacked(dataSourceConfig)); xProductList = new JComboBox<>(); xProductList.addItemListener(event -> { if (event.getStateChange() == ItemEvent.SELECTED) { final Product selectedXProduct = (Product) event.getItem(); updateBandList(selectedXProduct, xBandProperty, false); } }); xProductList.setRenderer(new ProductListCellRenderer()); bindingContext.bind(PROPERTY_NAME_X_PRODUCT, xProductList); xProductProperty = bindingContext.getPropertySet().getProperty(PROPERTY_NAME_X_PRODUCT); yProductList = new JComboBox<>(); yProductList.addItemListener(event -> { if (event.getStateChange() == ItemEvent.SELECTED) { final Product selectedYProduct = (Product) event.getItem(); updateBandList(selectedYProduct, yBandProperty, true); } }); yProductList.setRenderer(new ProductListCellRenderer()); bindingContext.bind(PROPERTY_NAME_Y_PRODUCT, yProductList); yProductProperty = bindingContext.getPropertySet().getProperty(PROPERTY_NAME_Y_PRODUCT); xBandList = new JComboBox<>(); xBandList.setRenderer(new BandListCellRenderer()); bindingContext.bind(PROPERTY_NAME_X_BAND, xBandList); xBandList.addActionListener(e -> { final Object value = xBandList.getSelectedItem(); if (value != null) { final Dimension rasterSize = ((RasterDataNode) value).getRasterSize(); if (rasterSize != referenceSize) { referenceSize = rasterSize; updateBandList(getProduct(), yBandProperty, true); } } }); xBandProperty = bindingContext.getPropertySet().getProperty(PROPERTY_NAME_X_BAND); yBandList = new JComboBox<>(); yBandList.setRenderer(new BandListCellRenderer()); bindingContext.bind(PROPERTY_NAME_Y_BAND, yBandList); yBandProperty = bindingContext.getPropertySet().getProperty(PROPERTY_NAME_Y_BAND); } private static String formatProductName(final Product product) { String name = product.getName().substring(0, Math.min(10, product.getName().length())); if (product.getName().length() > 10) { name += "..."; } return product.getProductRefString() + name; } private void initColorModels() { for (int j = 0; j <= 1; j++) { final int palSize = 256; final byte[] r = new byte[palSize]; final byte[] g = new byte[palSize]; final byte[] b = new byte[palSize]; final byte[] a = new byte[palSize]; r[0] = (byte) backgroundColor.getRed(); g[0] = (byte) backgroundColor.getGreen(); b[0] = (byte) backgroundColor.getBlue(); a[0] = (byte) backgroundColor.getAlpha(); for (int i = 1; i < 128; i++) { if (j == 0) { r[i] = (byte) (2 * i); g[i] = (byte) 0; } else { r[i] = (byte) 255; g[i] = (byte) (255 - (2 * (i - 128))); } b[i] = (byte) 0; a[i] = (byte) 255; } for (int i = 128; i < 256; i++) { if (j == 0) { r[i] = (byte) 255; g[i] = (byte) (2 * (i - 128)); } else { r[i] = (byte) (255 - (2 * i)); g[i] = (byte) 0; } b[i] = (byte) 0; a[i] = (byte) 255; } if (j == 0) { toggledColorModel = new IndexColorModel(8, palSize, r, g, b, a); } else { untoggledColorModel = new IndexColorModel(8, palSize, r, g, b, a); } } } private void createUI() { plot = new XYImagePlot(); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); NumberAxis domainAxis = (NumberAxis) plot.getDomainAxis(); NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis(); domainAxis.setAutoRangeIncludesZero(false); rangeAxis.setAutoRangeIncludesZero(false); domainAxis.setUpperMargin(0); domainAxis.setLowerMargin(0); rangeAxis.setUpperMargin(0); rangeAxis.setLowerMargin(0); plot.setNoDataMessage(NO_DATA_MESSAGE); plot.getRenderer().setDefaultToolTipGenerator(new XYPlotToolTipGenerator()); JFreeChart chart = new JFreeChart(CHART_TITLE, plot); ChartFactory.getChartTheme().apply(chart); chart.removeLegend(); createUI(createChartPanel(chart), createOptionsPanel(), bindingContext); updateUIState(); } private void toggleColor() { BufferedImage image = plot.getImage(); if (image != null) { if (!plotColorsInverted) { image = new BufferedImage(untoggledColorModel, image.getRaster(), image.isAlphaPremultiplied(), null); } else { image = new BufferedImage(toggledColorModel, image.getRaster(), image.isAlphaPremultiplied(), null); } plot.setImage(image); densityPlotDisplay.getChart().setNotify(true); plotColorsInverted = !plotColorsInverted; } } private JPanel createOptionsPanel() { toggleColorCheckBox = new JCheckBox("Invert plot colors"); toggleColorCheckBox.addActionListener(e -> toggleColor()); toggleColorCheckBox.setEnabled(false); final JPanel optionsPanel = GridBagUtils.createPanel(); final GridBagConstraints gbc = GridBagUtils.createConstraints("anchor=NORTHWEST,fill=HORIZONTAL,insets.top=0,weightx=1,gridx=0"); GridBagUtils.addToPanel(optionsPanel, axisRangeControls[X_VAR].getPanel(), gbc, "gridy=0, insets.top=2"); GridBagUtils.addToPanel(optionsPanel, xProductList, gbc, "gridy=1,insets.left=4,insets.right=2"); GridBagUtils.addToPanel(optionsPanel, xBandList, gbc, "gridy=2,insets.left=4,insets.right=2"); GridBagUtils.addToPanel(optionsPanel, axisRangeControls[Y_VAR].getPanel(), gbc, "gridy=3,insets.left=0,insets.right=0"); GridBagUtils.addToPanel(optionsPanel, yProductList, gbc, "gridy=4,insets.left=4,insets.right=2"); GridBagUtils.addToPanel(optionsPanel, yBandList, gbc, "gridy=5,insets.left=4,insets.right=2"); GridBagUtils.addToPanel(optionsPanel, new JPanel(), gbc, "gridy=6"); GridBagUtils.addToPanel(optionsPanel, new JSeparator(), gbc, "gridy=7,insets.left=4,insets.right=2"); GridBagUtils.addToPanel(optionsPanel, toggleColorCheckBox, gbc, "gridy=8,insets.left=0,insets.right=0"); return optionsPanel; } private ChartPanel createChartPanel(JFreeChart chart) { densityPlotDisplay = new ChartPanel(chart); MaskSelectionToolSupport maskSelectionToolSupport = new MaskSelectionToolSupport(this, densityPlotDisplay, "scatter_plot_area", "Mask generated from selected scatter plot area", Color.RED, PlotAreaSelectionTool.AreaType.ELLIPSE) { @Override protected String createMaskExpression(PlotAreaSelectionTool.AreaType areaType, Shape shape) { Rectangle2D bounds = shape.getBounds2D(); return createMaskExpression(bounds.getCenterX(), bounds.getCenterY(), 0.5 * bounds.getWidth(), 0.5 * bounds.getHeight()); } protected String createMaskExpression(double x0, double y0, double dx, double dy) { return String.format("sqrt(sq((%s - %s)/%s) + sq((%s - %s)/%s)) < 1.0", BandArithmetic.createExternalName(dataSourceConfig.xBand.getName()), x0, dx, BandArithmetic.createExternalName(dataSourceConfig.yBand.getName()), y0, dy); } }; densityPlotDisplay.getPopupMenu().addSeparator(); densityPlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createMaskSelectionModeMenuItem()); densityPlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createDeleteMaskMenuItem()); densityPlotDisplay.getPopupMenu().addSeparator(); densityPlotDisplay.getPopupMenu().add(createCopyDataToClipboardMenuItem()); return densityPlotDisplay; } private RasterDataNode getRaster(int varIndex) { final Product product = getProduct(); if (product == null) { return null; } final RasterDataNode raster; if (varIndex == X_VAR) { raster = dataSourceConfig.xBand; } else { raster = dataSourceConfig.yBand; } Debug.assertTrue(raster != null); return raster; } private void updateUIState() { super.updateComponents(); } private static void checkBandsForRange() throws IllegalArgumentException { if (axisRangeControls[X_VAR].getMin().equals(axisRangeControls[X_VAR].getMax()) && axisRangeControls[Y_VAR].getMin().equals(axisRangeControls[Y_VAR].getMax())) { throw new IllegalArgumentException("Value range of at least one band must be larger than one"); } } @Override protected void updateChartData() { final RasterDataNode rasterX = getRaster(X_VAR); final RasterDataNode rasterY = getRaster(Y_VAR); if (rasterX == null || rasterY == null) { return; } ProgressMonitorSwingWorker<BufferedImage, Object> swingWorker = new ProgressMonitorSwingWorker<BufferedImage, Object>( this, "Computing scatter plot") { @Override protected BufferedImage doInBackground(ProgressMonitor pm) throws Exception { pm.beginTask("Computing scatter plot...", 100); try { checkBandsForRange(); setRange(X_VAR, rasterX, dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null, SubProgressMonitor.create(pm, 15)); setRange(Y_VAR, rasterY, dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null, SubProgressMonitor.create(pm, 15)); final BufferedImage densityPlotImage = ProductUtils.createDensityPlotImage(rasterX, axisRangeControls[X_VAR].getMin().floatValue(), axisRangeControls[X_VAR].getMax().floatValue(), rasterY, axisRangeControls[Y_VAR].getMin().floatValue(), axisRangeControls[Y_VAR].getMax().floatValue(), dataSourceConfig.useRoiMask ? dataSourceConfig.roiMask : null, 512, 512, backgroundColor, null, SubProgressMonitor.create(pm, 70)); toggleColorCheckBox.setSelected(false); plotColorsInverted = false; return densityPlotImage; } finally { pm.done(); } } @Override public void done() { try { checkBandsForRange(); final BufferedImage densityPlotImage = get(); double minX = axisRangeControls[X_VAR].getMin(); double maxX = axisRangeControls[X_VAR].getMax(); double minY = axisRangeControls[Y_VAR].getMin(); double maxY = axisRangeControls[Y_VAR].getMax(); if (minX > maxX || minY > maxY) { Dialogs.showMessage(/*I18N*/ CHART_TITLE, /*I18N*/ "Failed to compute scatter plot.\n" + "No Pixels considered..", JOptionPane.ERROR_MESSAGE, null ); plot.setDataset(null); return; } if (MathUtils.equalValues(minX, maxX, 1.0e-4)) { minX = Math.floor(minX); maxX = Math.ceil(maxX); } if (MathUtils.equalValues(minY, maxY, 1.0e-4)) { minY = Math.floor(minY); maxY = Math.ceil(maxY); } plot.setImage(densityPlotImage); plot.setImageDataBounds(new Rectangle2D.Double(minX, minY, maxX - minX, maxY - minY)); axisRangeControls[X_VAR].adjustComponents(minX, maxX, NUM_DECIMALS); axisRangeControls[Y_VAR].adjustComponents(minY, maxY, NUM_DECIMALS); plot.getDomainAxis().setLabel(StatisticChartStyling.getAxisLabel(getRaster(X_VAR), "X", false)); plot.getRangeAxis().setLabel(StatisticChartStyling.getAxisLabel(getRaster(Y_VAR), "Y", false)); toggleColorCheckBox.setEnabled(true); } catch (InterruptedException | CancellationException | ExecutionException | IllegalArgumentException e) { String msg = "Failed to compute scatter plot"; String reason; int messageType = JOptionPane.ERROR_MESSAGE; Level logLevel = Level.SEVERE; if (e instanceof CancellationException) { messageType = JOptionPane.INFORMATION_MESSAGE; logLevel = Level.INFO; reason = "Calculation canceled by user"; } else if (e instanceof InterruptedException) { reason = "Calculation unexpectedly interrupted"; } else { reason = "An unexpected error occurred: " + e.getCause().getMessage(); } SystemUtils.LOG.log(logLevel, String.format("%s: %s", msg, reason), e); Dialogs.showMessage(CHART_TITLE, String.format("%s:\n%s", msg, reason), messageType, null); } } }; swingWorker.execute(); } private static void setRange(int varIndex, RasterDataNode raster, Mask mask, ProgressMonitor pm) throws IOException { final AxisRangeControl axisRangeControl = axisRangeControls[varIndex]; if (axisRangeControl.isAutoMinMax()) { Stx stx; if (mask == null) { stx = raster.getStx(false, pm); } else { stx = new StxFactory().withRoiMask(mask).create(raster, pm); } axisRangeControl.adjustComponents(stx.getMinimum(), stx.getMaximum(), NUM_DECIMALS); } } private static Product[] createAvailableProductList() { return SnapApp.getDefault().getProductManager().getProducts(); } private RasterDataNode[] createAvailableBandList(final Product product, boolean considerReferenceSize) { final List<RasterDataNode> availableBandList = new ArrayList<>(17); if (product != null) { for (int i = 0; i < product.getNumBands(); i++) { final Band band = product.getBandAt(i); if (!considerReferenceSize || band.getRasterSize().equals(referenceSize)) { availableBandList.add(band); } } if (!considerReferenceSize || product.getSceneRasterSize().equals(referenceSize)) { for (int i = 0; i < product.getNumTiePointGrids(); i++) { availableBandList.add(product.getTiePointGridAt(i)); } } } // if raster is only bound to the product and does not belong to it final RasterDataNode raster = getRaster(); if (raster != null && raster.getProduct() == product && (!considerReferenceSize || raster.getRasterSize().equals(raster.getProduct().getSceneRasterSize()))) { if (!availableBandList.contains(raster)) { availableBandList.add(raster); } } return availableBandList.toArray(new RasterDataNode[availableBandList.size()]); } @Override protected boolean checkDataToClipboardCopy() { final int warnLimit = 2000; final int excelLimit = 65536; final int numNonEmptyBins = getNumNonEmptyBins(); if (numNonEmptyBins > warnLimit) { String excelNote = ""; if (numNonEmptyBins > excelLimit - 100) { excelNote = "Note that e.g., Microsoft® Excel 2002 only supports a total of " + excelLimit + " rows in a sheet.\n"; /*I18N*/ } final String message = MessageFormat.format( "This scatter plot contains {0} non-empty bins.\n" + "For each bin, a text data row containing an x, y and z value will be created.\n" + "{1}\nPress ''Yes'' if you really want to copy this amount of data to the system clipboard.\n", numNonEmptyBins, excelNote); final int status = JOptionPane.showConfirmDialog(this, message, /*I18N*/ "Copy Data to Clipboard", /*I18N*/ JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE); if (status != JOptionPane.YES_OPTION) { return false; } } return true; } private static byte[] getValidData(BufferedImage image) { if (image != null && image.getColorModel() instanceof IndexColorModel && image.getData().getDataBuffer() instanceof DataBufferByte) { return ((DataBufferByte) image.getData().getDataBuffer()).getData(); } return null; } protected int getNumNonEmptyBins() { final byte[] data = getValidData(plot.getImage()); int n = 0; if (data != null) { int b; for (byte aData : data) { b = aData & 0xff; if (b != 0) { n++; } } } return n; } @Override protected String getDataAsText() { final BufferedImage image = plot.getImage(); final Rectangle2D bounds = plot.getImageDataBounds(); final byte[] data = getValidData(image); if (data == null) { return null; } final StringBuilder sb = new StringBuilder(64000); final int w = image.getWidth(); final int h = image.getHeight(); final RasterDataNode rasterX = getRaster(X_VAR); assert rasterX != null; final String nameX = rasterX.getName(); final double sampleMinX = bounds.getMinX(); final double sampleMaxX = bounds.getMaxX(); final RasterDataNode rasterY = getRaster(Y_VAR); assert rasterY != null; final String nameY = rasterY.getName(); final double sampleMinY = bounds.getMinY(); final double sampleMaxY = bounds.getMaxY(); sb.append("Product name:\t").append(rasterX.getProduct().getName()).append("\n"); sb.append("Dataset X name:\t").append(nameX).append("\n"); sb.append("Dataset Y name:\t").append(nameY).append("\n"); sb.append('\n'); sb.append(nameX).append(" minimum:\t").append(sampleMinX).append("\t").append(rasterX.getUnit()).append( "\n"); sb.append(nameX).append(" maximum:\t").append(sampleMaxX).append("\t").append(rasterX.getUnit()).append( "\n"); sb.append(nameX).append(" bin size:\t").append((sampleMaxX - sampleMinX) / w).append("\t").append( rasterX.getUnit()).append("\n"); sb.append(nameX).append(" #bins:\t").append(w).append("\n"); sb.append('\n'); sb.append(nameY).append(" minimum:\t").append(sampleMinY).append("\t").append(rasterY.getUnit()).append( "\n"); sb.append(nameY).append(" maximum:\t").append(sampleMaxY).append("\t").append(rasterY.getUnit()).append( "\n"); sb.append(nameY).append(" bin size:\t").append((sampleMaxY - sampleMinY) / h).append("\t").append( rasterY.getUnit()).append("\n"); sb.append(nameY).append(" #bins:\t").append(h).append("\n"); sb.append('\n'); sb.append(nameX); sb.append('\t'); sb.append(nameY); sb.append('\t'); sb.append("Bin counts\t(cropped at 255)"); sb.append('\n'); int x, y, z; double v1, v2; for (int i = 0; i < data.length; i++) { z = data[i] & 0xff; if (z != 0) { x = i % w; y = h - i / w - 1; v1 = sampleMinX + ((x + 0.5) * (sampleMaxX - sampleMinX)) / w; v2 = sampleMinY + ((y + 0.5) * (sampleMaxY - sampleMinY)) / h; sb.append(v1); sb.append('\t'); sb.append(v2); sb.append('\t'); sb.append(z); sb.append('\n'); } } return sb.toString(); } @SuppressWarnings("unused") private static class DataSourceConfig { public boolean useRoiMask; public Mask roiMask; private Product xProduct; private Product yProduct; private RasterDataNode xBand; private RasterDataNode yBand; private Property xProductProperty; private Property yProductProperty; private Property xBandProperty; private Property yBandProperty; } private static class BandListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { this.setText(((RasterDataNode) value).getName()); } return this; } } private static class ProductListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { this.setText(formatProductName((Product) value)); } return this; } } }
33,778
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
InformationTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/InformationTopComponent.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.statistics; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; @TopComponent.Description( preferredID = "InformationTopComponent", iconBase = "org/esa/snap/rcp/icons/Information.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "Information", openAtStartup = false, position = 30 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.InformationTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 35), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_InformationTopComponent_Name", preferredID = "InformationTopComponent" ) @NbBundle.Messages({ "CTL_InformationTopComponent_Name=Information", "CTL_InformationTopComponent_HelpId=informationDialog" }) /** * The tool view containing the product / band information * * @author Marco Zuehlke */ public class InformationTopComponent extends AbstractStatisticsTopComponent { public static final String ID = InformationTopComponent.class.getName(); @Override protected PagePanel createPagePanel() { return new InformationPanel(this, Bundle.CTL_InformationTopComponent_HelpId()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_InformationTopComponent_HelpId()); } }
2,362
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PlotAreaSelectionTool.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/PlotAreaSelectionTool.java
package org.esa.snap.rcp.statistics; import com.bc.ceres.core.Assert; import org.jfree.chart.ChartPanel; import org.jfree.chart.annotations.XYShapeAnnotation; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.ui.RectangleEdge; import java.awt.Color; import java.awt.Paint; import java.awt.Point; import java.awt.Shape; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.Ellipse2D; import java.awt.geom.Rectangle2D; import static java.lang.Math.abs; import static java.lang.Math.min; /** * @author Norman Fomferra */ public class PlotAreaSelectionTool extends MouseAdapter { public enum AreaType { /** * Shape is an instance of {@link java.awt.geom.Rectangle2D}, only X-coordinates are valid. */ X_RANGE, /** * Shape is an instance of {@link java.awt.geom.Rectangle2D}, only Y-coordinates are valid. */ Y_RANGE, /** * Shape is an instance of {@link java.awt.geom.Rectangle2D}. */ RECTANGLE, /** * Shape is an instance of {@link java.awt.geom.Ellipse2D}. */ ELLIPSE, } public interface Action { void areaSelected(AreaType areaType, Shape shape); } private final ChartPanel chartPanel; private final Action action; private Point point1; private Point point2; private SelectedArea selectedArea; private double triggerDistance; private Color fillPaint; private AreaType areaType; public PlotAreaSelectionTool(ChartPanel chartPanel, Action action) { this.chartPanel = chartPanel; this.action = action; triggerDistance = 4; fillPaint = new Color(0, 0, 255, 50); areaType = AreaType.ELLIPSE; } public void install() { chartPanel.addMouseListener(this); chartPanel.addMouseMotionListener(this); chartPanel.setMouseZoomable(false); } public void uninstall() { chartPanel.removeMouseListener(this); chartPanel.removeMouseMotionListener(this); chartPanel.setMouseZoomable(true); } public AreaType getAreaType() { return areaType; } public void setAreaType(AreaType areaType) { Assert.notNull(areaType, "areaType"); this.areaType = areaType; } public double getTriggerDistance() { return triggerDistance; } public void setTriggerDistance(double triggerDistance) { this.triggerDistance = triggerDistance; } public Color getFillPaint() { return fillPaint; } public void setFillPaint(Color fillPaint) { Assert.notNull(fillPaint, "fillPaint"); this.fillPaint = fillPaint; } @Override public void mousePressed(MouseEvent event) { if (!isButton1(event)) { return; } point1 = event.getPoint(); point2 = null; } @Override public void mouseReleased(MouseEvent event) { if (!isButton1(event)) { return; } if (selectedArea == null) { return; } // Make sure, action is only triggered if a new area has been selected if (point1 == null || point2 == null) { return; } action.areaSelected(areaType, selectedArea.getShape()); // Ready for a new area to be selected, but the existing area remains visible point1 = null; point2 = null; } @Override public void mouseDragged(MouseEvent event) { if (point1 == null) { return; } if (point2 == null) { // first drag event after mousePressed --> // then we must check against triggerDistance Point p2 = event.getPoint(); if (Point.distanceSq(point1.getX(), point1.getY(), p2.getX(), p2.getY()) >= triggerDistance * triggerDistance) { point2 = p2; updateAnnotation(); } } else { // already dragging, just update point2 = event.getPoint(); updateAnnotation(); } } private void updateAnnotation() { removeAnnotation(); addAnnotation(); } private void addAnnotation() { selectedArea = new SelectedArea(createShape(), fillPaint); chartPanel.getChart().getXYPlot().addAnnotation(selectedArea); } public void removeAnnotation() { if (selectedArea != null) { chartPanel.getChart().getXYPlot().removeAnnotation(selectedArea); selectedArea = null; } } private boolean isButton1(MouseEvent event) { return event.getButton() == MouseEvent.BUTTON1; } private Shape createShape() { XYPlot plot = chartPanel.getChart().getXYPlot(); Rectangle2D dataArea = chartPanel.getScreenDataArea(); PlotOrientation orientation = plot.getOrientation(); RectangleEdge domainEdge = Plot.resolveDomainAxisLocation(plot.getDomainAxisLocation(), orientation); RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation(plot.getRangeAxisLocation(), orientation); double vx1 = areaType == AreaType.Y_RANGE ? dataArea.getX() : point1.x; double vy1 = areaType == AreaType.X_RANGE ? dataArea.getY() : point1.y; double vx2 = areaType == AreaType.Y_RANGE ? dataArea.getX() + dataArea.getWidth() : point2.x; double vy2 = areaType == AreaType.X_RANGE ? dataArea.getY() + dataArea.getHeight() : point2.y; double x1 = plot.getDomainAxis().java2DToValue(vx1, dataArea, domainEdge); double x2 = plot.getDomainAxis().java2DToValue(vx2, dataArea, domainEdge); double y1 = plot.getRangeAxis().java2DToValue(vy1, dataArea, rangeEdge); double y2 = plot.getRangeAxis().java2DToValue(vy2, dataArea, rangeEdge); double dx = abs(x2 - x1); double dy = abs(y2 - y1); final Shape shape; if (areaType == AreaType.ELLIPSE) { shape = new Ellipse2D.Double(x1 - dx, y1 - dy, 2.0 * dx, 2.0 * dy); } else if (areaType == AreaType.RECTANGLE) { shape = new Rectangle2D.Double(x1 - dx, y1 - dy, 2.0 * dx, 2.0 * dy); } else if (areaType == AreaType.X_RANGE || areaType == AreaType.Y_RANGE) { shape = new Rectangle2D.Double(min(x1, x2), min(y1, y2), dx, dy); } else { throw new IllegalStateException("areaType = " + areaType); } return shape; } private static class SelectedArea extends XYShapeAnnotation { private final Shape shape; private SelectedArea(Shape shape, Paint fillPaint) { super(shape, null, null, fillPaint); this.shape = shape; } // Base class does not off this method :-( public Shape getShape() { return shape; } } }
6,978
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StatisticsUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/StatisticsUtils.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import com.bc.ceres.swing.figure.Figure; import com.bc.ceres.swing.figure.ShapeFigure; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.TransectProfileData; import org.esa.snap.core.util.StringUtils; import org.esa.snap.core.util.math.MathUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.product.ProductSceneView; import java.awt.*; import java.awt.geom.Point2D; /** * Utilities for the statistics dialog. * * @author Marco Peters */ public class StatisticsUtils { public static float round(final float x) { return round(x, 100.0f); } public static float round(final float x, final float v) { return MathUtils.round(x, v); } public static double round(final double x) { return round(x, 100.0); } public static double round(final double x, final double v) { return MathUtils.round(x, v); } public static String getDiagramLabel(final RasterDataNode raster) { final StringBuilder sb = new StringBuilder(); sb.append(raster.getName()); if (StringUtils.isNotNullAndNotEmpty(raster.getUnit())) { sb.append(" ["); sb.append(raster.getUnit()); sb.append("]"); } else { sb.append(" [-]"); } return sb.toString(); } public static class TransectProfile { public static Shape getTransectShape(Product product) { final ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); if (sceneView != null) { if (sceneView.getProduct() == product) { final ShapeFigure currentShapeFigure = sceneView.getCurrentShapeFigure(); if (currentShapeFigure != null && currentShapeFigure.getRank() != Figure.Rank.POINT) { // shape is in model coordinates and shall be in model coordinates return currentShapeFigure.getShape(); } } } return null; } static String createTransectProfileText(RasterDataNode raster, TransectProfileData data) { final Point2D[] pixelPositions = data.getPixelPositions(); final GeoPos[] geoPositions = data.getGeoPositions(); final float[] sampleValues = data.getSampleValues(); final StringBuilder sb = new StringBuilder(1024); final String formatString = "%1$-10s\t"; sb.append(String.format(formatString, "Index")); sb.append(String.format(formatString, "Pixel-X")); sb.append(String.format(formatString, "Pixel-Y")); if (geoPositions.length > 0) { sb.append(String.format(formatString, "Lat")); sb.append(String.format(formatString, "Lon")); } sb.append(String.format(formatString, getDiagramLabel(raster))); sb.append("\n"); for (int i = 0; i < pixelPositions.length; i++) { final Point2D pixelPos = pixelPositions[i]; sb.append(String.format(formatString, i)); sb.append(String.format(formatString, pixelPos.getX())); sb.append(String.format(formatString, pixelPos.getY())); if (geoPositions.length > 0) { final GeoPos geoPos = geoPositions[i]; sb.append(String.format(formatString, geoPos.lat)); sb.append(String.format(formatString, geoPos.lon)); } sb.append(String.format(formatString, sampleValues[i])); sb.append(" \n"); } return sb.toString(); } } }
4,593
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
HistogramPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/HistogramPanel.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.statistics; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueRange; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.swing.binding.Binding; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.Enablement; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.esa.snap.core.datamodel.Mask; 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.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.Stx; import org.esa.snap.core.datamodel.StxFactory; import org.esa.snap.core.dataop.barithm.BandArithmetic; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.GridBagUtils; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.StandardXYBarPainter; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.ui.RectangleInsets; import org.jfree.data.xy.XIntervalSeries; import org.jfree.data.xy.XIntervalSeriesCollection; import org.openide.windows.TopComponent; import javax.media.jai.Histogram; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingUtilities; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Shape; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.concurrent.ExecutionException; /** * A pane within the statistics window which displays a histogram. */ class HistogramPanel extends ChartPagePanel { private static final String NO_DATA_MESSAGE = "No histogram computed yet.\n" + "If a band is selected, a histogram can be created by hitting the 'Refresh View' button.\n" + HELP_TIP_MESSAGE + "\n" + ZOOM_TIP_MESSAGE; private static final String CHART_TITLE = "Histogram"; public static final String PROPERTY_NAME_NUM_BINS = "numBins"; public static final String PROPERTY_NAME_LOGARITHMIC_HISTOGRAM = "histogramLogScaled"; public static final String PROPERTY_NAME_LOG_SCALED = "xAxisLogScaled"; private static final double HISTO_MIN_DEFAULT = 0.0; private static final double HISTO_MAX_DEFAULT = 100.0; private static final int NUM_BINS_DEFAULT = 512; private AxisRangeControl xAxisRangeControl; private XIntervalSeriesCollection dataset; private JFreeChart chart; private HistogramPlotConfig histogramPlotConfig; private BindingContext bindingContext; private boolean isInitialized; private boolean histogramComputing; private Enablement log10AxisEnablement; private Enablement log10HistEnablement; private HistogramPanelModel model; private HistogramPanel.ConfigChangeListener configChangeListener; HistogramPanel(final TopComponent parentComponent, String helpID) { super(parentComponent, helpID, CHART_TITLE, true); } @Override protected void initComponents() { SnapApp.getDefault().getSelectionSupport(ProductNode.class).addHandler((oldValue, newValue) -> { if (newValue != null) { handleMasklessProduct(newValue.getProduct()); } }); SnapApp.getDefault().getProductManager().addListener(new ProductManager.Listener() { @Override public void productAdded(ProductManager.Event event) { //do nothing } @Override public void productRemoved(ProductManager.Event event) { model.removeStxFromProduct(event.getProduct()); } }); model = new HistogramPanelModel(); xAxisRangeControl = new AxisRangeControl("X-Axis"); histogramPlotConfig = new HistogramPlotConfig(); bindingContext = new BindingContext(PropertyContainer.createObjectBacked(histogramPlotConfig)); configChangeListener = new ConfigChangeListener(); bindingContext.addPropertyChangeListener(configChangeListener); createUI(); updateComponents(); } @Override protected void updateComponents() { if (!isInitialized || !isVisible()) { return; } super.updateComponents(); chart.setTitle(getRaster() != null ? CHART_TITLE + " for " + getRaster().getName() : CHART_TITLE); updateXAxis(); if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor("min").setDefaultValue( HISTO_MIN_DEFAULT); xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor("max").setDefaultValue( HISTO_MAX_DEFAULT); } dataset = null; handleStxChange(); updateRefreshButton(); } private void handleMasklessProduct(Product product) { if (product != null && product.getMaskGroup().getNodeCount() == 0) { try { bindingContext.getPropertySet().getProperty("useRoiMask").setValue(Boolean.FALSE); } catch (ValidationException e) { throw new IllegalStateException("Cannot come here"); } } } private void updateRefreshButton() { refreshButton.setEnabled(getRaster() != null && !model.hasStx(createHistogramConfig())); } @Override protected boolean mustHandleSelectionChange() { return isRasterChanged(); } @Override protected void handleNodeSelectionChanged() { super.handleNodeSelectionChanged(); handleMasklessProduct(getProduct()); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateChartData(false); } }); } @Override public void nodeDataChanged(ProductNodeEvent event) { super.nodeDataChanged(event); if (!histogramPlotConfig.useRoiMask) { return; } final Mask roiMask = histogramPlotConfig.roiMask; if (roiMask == null) { return; } final ProductNode sourceNode = event.getSourceNode(); if (!(sourceNode instanceof Mask)) { return; } final String maskName = sourceNode.getName(); if (roiMask.getName().equals(maskName)) { model.removeStx(createHistogramConfig()); updateComponents(); } } private void createUI() { dataset = new XIntervalSeriesCollection(); chart = ChartFactory.createHistogram( CHART_TITLE, "Values", "Frequency in #pixels", dataset, PlotOrientation.VERTICAL, false, // Legend? true, // tooltips false // url ); final XYPlot xyPlot = chart.getXYPlot(); xyPlot.setDomainZeroBaselineStroke(new BasicStroke(0.2f)); final XYBarRenderer renderer = (XYBarRenderer) xyPlot.getRenderer(); renderer.setDrawBarOutline(false); renderer.setShadowVisible(false); renderer.setShadowYOffset(-4.0); renderer.setDefaultToolTipGenerator(new XYPlotToolTipGenerator()); renderer.setBarPainter(new StandardXYBarPainter()); renderer.setSeriesPaint(0, new Color(0, 0, 200)); createUI(createChartPanel(chart), createOptionsPanel(), bindingContext); isInitialized = true; final Binding minBinding = xAxisRangeControl.getBindingContext().getBinding("min"); final double min = (Double) minBinding.getPropertyValue(); final Binding maxBinding = xAxisRangeControl.getBindingContext().getBinding("max"); final double max = (Double) maxBinding.getPropertyValue(); if (!histogramComputing && min > max) { minBinding.setPropertyValue(max); maxBinding.setPropertyValue(min); } updateXAxis(); } private JPanel createOptionsPanel() { final JLabel numBinsLabel = new JLabel("#Bins:"); JTextField numBinsField = new JTextField(Integer.toString(NUM_BINS_DEFAULT)); numBinsField.setPreferredSize(new Dimension(50, numBinsField.getPreferredSize().height)); final JCheckBox histoLogCheck = new JCheckBox("Log10 scaled bins"); histoLogCheck.addActionListener(configChangeListener); bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS).setDescription( "Set the number of bins in the histogram"); bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS).setValueRange( new ValueRange(2.0, 2048.0)); bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_NUM_BINS).setDefaultValue(NUM_BINS_DEFAULT); bindingContext.bind(PROPERTY_NAME_NUM_BINS, numBinsField); bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM).setDescription( "Use log-10 scaled values for computation of histogram"); bindingContext.getPropertySet().getDescriptor(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM).setDefaultValue(false); bindingContext.bind(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM, histoLogCheck); log10HistEnablement = bindingContext.bindEnabledState(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM, true, new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { return getRaster() != null && getRaster().getStx().getMaximum() > 0; } }); PropertyChangeListener logChangeListener = new AxisControlChangeListener(); xAxisRangeControl.getBindingContext().addPropertyChangeListener(logChangeListener); xAxisRangeControl.getBindingContext().getPropertySet().addProperty( bindingContext.getPropertySet().getProperty(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM)); xAxisRangeControl.getBindingContext().getPropertySet().addProperty( bindingContext.getPropertySet().getProperty(PROPERTY_NAME_LOG_SCALED)); xAxisRangeControl.getBindingContext().getPropertySet().getDescriptor(PROPERTY_NAME_LOG_SCALED).setDescription( "Toggle whether to use a logarithmic x-axis"); log10AxisEnablement = xAxisRangeControl.getBindingContext().bindEnabledState(PROPERTY_NAME_LOG_SCALED, true, new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { HistogramPanelModel.HistogramConfig currentConfig = createHistogramConfig(); boolean hasStx = model.hasStx(currentConfig); // log10 xAxis is enabled when current histogram exists and is NOT log10 scaled return dataset != null && hasStx && !model.getStx(currentConfig).isLogHistogram(); } }); JPanel dataSourceOptionsPanel = GridBagUtils.createPanel(); GridBagConstraints dataSourceOptionsConstraints = GridBagUtils.createConstraints( "anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2"); GridBagUtils.addToPanel(dataSourceOptionsPanel, new JLabel(" "), dataSourceOptionsConstraints, "gridwidth=2,gridy=0,gridx=0,weightx=0"); GridBagUtils.addToPanel(dataSourceOptionsPanel, numBinsLabel, dataSourceOptionsConstraints, "insets.top=2,insets.left=4,gridwidth=1,gridy=1,gridx=0,weightx=1"); GridBagUtils.addToPanel(dataSourceOptionsPanel, numBinsField, dataSourceOptionsConstraints, "insets.top=0,insets.left=0,insets.right=2,gridwidth=1,gridy=1,gridx=1"); GridBagUtils.addToPanel(dataSourceOptionsPanel, histoLogCheck, dataSourceOptionsConstraints, "insets.right=0,gridwidth=2,gridy=2,gridx=0"); xAxisRangeControl.getBindingContext().bind(PROPERTY_NAME_LOG_SCALED, new JCheckBox("Log10 scaled")); xAxisRangeControl.getBindingContext().addPropertyChangeListener(PROPERTY_NAME_LOG_SCALED, new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { ValueAxis oldAxis = chart.getXYPlot().getDomainAxis(); ValueAxis newAxis = StatisticChartStyling.updateScalingOfAxis((Boolean) evt.getNewValue(), oldAxis, true); chart.getXYPlot().setDomainAxis(newAxis); } }); JPanel displayOptionsPanel = GridBagUtils.createPanel(); GridBagConstraints displayOptionsConstraints = GridBagUtils.createConstraints( "anchor=SOUTH,fill=HORIZONTAL,weightx=1"); GridBagUtils.addToPanel(displayOptionsPanel, xAxisRangeControl.getPanel(), displayOptionsConstraints, "gridy=2"); JPanel optionsPanel = GridBagUtils.createPanel(); GridBagConstraints gbc = GridBagUtils.createConstraints( "anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2,weightx=1"); GridBagUtils.addToPanel(optionsPanel, dataSourceOptionsPanel, gbc, "gridy=0"); GridBagUtils.addToPanel(optionsPanel, new JPanel(), gbc, "gridy=1,fill=VERTICAL,weighty=1"); GridBagUtils.addToPanel(optionsPanel, displayOptionsPanel, gbc, "gridy=2,fill=HORIZONTAL,weighty=0"); GridBagUtils.addToPanel(optionsPanel, new JPanel(), gbc, "gridy=3,fill=VERTICAL,weighty=1"); GridBagUtils.addToPanel(optionsPanel, xAxisRangeControl.getBindingContext().getBinding( PROPERTY_NAME_LOG_SCALED).getComponents()[0], gbc, "gridy=4"); return optionsPanel; } private HistogramPanelModel.HistogramConfig createHistogramConfig() { if (getRaster() == null || isRasterChanged()) { return null; } return new HistogramPanelModel.HistogramConfig(getRaster(), histogramPlotConfig.useRoiMask ? histogramPlotConfig.roiMask.getName() : null, histogramPlotConfig.numBins, histogramPlotConfig.histogramLogScaled); } private ChartPanel createChartPanel(JFreeChart chart) { XYPlot plot = chart.getXYPlot(); plot.setForegroundAlpha(0.85f); plot.setNoDataMessage(NO_DATA_MESSAGE); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); ChartPanel chartPanel = new ChartPanel(chart); MaskSelectionToolSupport maskSelectionToolSupport = new MaskSelectionToolSupport(this, chartPanel, "histogram_plot_area", "Mask generated from selected histogram plot area", Color.RED, PlotAreaSelectionTool.AreaType.X_RANGE) { @Override protected String createMaskExpression(PlotAreaSelectionTool.AreaType areaType, Shape shape) { Rectangle2D bounds = shape.getBounds2D(); return createMaskExpression(bounds.getMinX(), bounds.getMaxX()); } protected String createMaskExpression(double x1, double x2) { String bandName = BandArithmetic.createExternalName(getRaster().getName()); HistogramPanelModel.HistogramConfig currentConfig = createHistogramConfig(); return String.format("%s >= %s && %s <= %s", bandName, model.hasStx(currentConfig) ? model.getStx(currentConfig).getHistogramScaling().scaleInverse(x1) : x1, bandName, model.hasStx(currentConfig) ? model.getStx(currentConfig).getHistogramScaling().scaleInverse(x2) : x2); } }; chartPanel.getPopupMenu().addSeparator(); chartPanel.getPopupMenu().add(maskSelectionToolSupport.createMaskSelectionModeMenuItem()); chartPanel.getPopupMenu().add(maskSelectionToolSupport.createDeleteMaskMenuItem()); chartPanel.getPopupMenu().addSeparator(); chartPanel.getPopupMenu().add(createCopyDataToClipboardMenuItem()); return chartPanel; } @SuppressWarnings("UnusedDeclaration") // will be used as property container for binding context private static class HistogramPlotConfig { private boolean xAxisLogScaled; private boolean histogramLogScaled; private int numBins = NUM_BINS_DEFAULT; private boolean useRoiMask; private Mask roiMask; } @Override public void updateChartData() { updateChartData(true); } private void updateChartData(boolean recompute) { final boolean autoMinMaxEnabled = getAutoMinMaxEnabled(); final Double min; final Double max; if (autoMinMaxEnabled) { min = null; max = null; } else { min = (Double) xAxisRangeControl.getBindingContext().getBinding("min").getPropertyValue(); max = (Double) xAxisRangeControl.getBindingContext().getBinding("max").getPropertyValue(); } new StxWorker(min, max, autoMinMaxEnabled, recompute).execute(); } private void setStx(Stx stx) { if (stx != null) { HistogramPanelModel.HistogramConfig config = createHistogramConfig(); if (config == null) { return; } if (!model.hasStx(config)) { model.setStx(config, stx); } dataset = new XIntervalSeriesCollection(); final int[] binCounts = stx.getHistogramBins(); final RasterDataNode raster = getRaster(); final XIntervalSeries series = new XIntervalSeries(raster.getName()); final Histogram histogram = stx.getHistogram(); for (int i = 0; i < binCounts.length; i++) { final double xMin = histogram.getBinLowValue(0, i); final double xMax = i < binCounts.length - 1 ? histogram.getBinLowValue(0, i + 1) : histogram.getHighValue(0); series.add(xMin, xMin, xMax, binCounts[i]); } dataset.addSeries(series); } handleStxChange(); } private void handleStxChange() { if (model.hasStx(createHistogramConfig())) { refreshButton.setEnabled(false); } log10HistEnablement.apply(); updateLogXAxisCheckBox(); chart.getXYPlot().setDataset(dataset); updateXAxis(); chart.fireChartChanged(); } private String getAxisLabel() { boolean logScaled = (Boolean) bindingContext.getBinding(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM).getPropertyValue(); return StatisticChartStyling.getAxisLabel(getRaster(), "X", logScaled); } private boolean getAutoMinMaxEnabled() { return xAxisRangeControl.isAutoMinMax(); } @Override public String getDataAsText() { HistogramPanelModel.HistogramConfig config = createHistogramConfig(); if (!model.hasStx(config)) { return null; } Stx stx = model.getStx(config); final int[] binVals = stx.getHistogramBins(); final int numBins = binVals.length; final double min = stx.getMinimum(); final double max = stx.getMaximum(); final StringBuilder sb = new StringBuilder(16000); sb.append("Product name:\t").append(getRaster().getProduct().getName()).append("\n"); sb.append("Dataset name:\t").append(getRaster().getName()).append("\n"); sb.append('\n'); sb.append("Histogram minimum:\t").append(min).append("\t").append(getRaster().getUnit()).append("\n"); sb.append("Histogram maximum:\t").append(max).append("\t").append(getRaster().getUnit()).append("\n"); sb.append("Histogram bin size:\t").append( getRaster().isLog10Scaled() ? ("NA\t") : ((max - min) / numBins + "\t") + getRaster().getUnit() + "\n"); sb.append("Histogram #bins:\t").append(numBins).append("\n"); sb.append('\n'); sb.append("Bin center value"); sb.append('\t'); sb.append("Bin counts"); sb.append('\n'); for (int i = 0; i < numBins; i++) { sb.append(min + ((i + 0.5) * (max - min)) / numBins); sb.append('\t'); sb.append(binVals[i]); sb.append('\n'); } return sb.toString(); } private void updateLogXAxisCheckBox() { HistogramPanelModel.HistogramConfig config = createHistogramConfig(); final boolean enabled = dataset != null && model.hasStx(config) && model.getStx(config).getMinimum() > 0 && !model.getStx(config).isLogHistogram(); Binding binding = xAxisRangeControl.getBindingContext().getBinding(PROPERTY_NAME_LOG_SCALED); if (!enabled) { binding.setPropertyValue(false); } log10AxisEnablement.apply(); binding.adjustComponents(); } private void updateXAxis() { final XYPlot plot = chart.getXYPlot(); plot.getDomainAxis().setLabel(getAxisLabel()); } private class AxisControlChangeListener implements PropertyChangeListener { boolean adjusting; @Override public void propertyChange(PropertyChangeEvent evt) { if (!adjusting) { adjusting = true; if (evt.getPropertyName().equals(PROPERTY_NAME_LOGARITHMIC_HISTOGRAM)) { if (evt.getNewValue().equals(Boolean.TRUE)) { xAxisRangeControl.adjustComponents(Stx.LOG10_SCALING.scale(xAxisRangeControl.getMin()), Stx.LOG10_SCALING.scale(xAxisRangeControl.getMax()), 3); } else { xAxisRangeControl.adjustComponents(Stx.LOG10_SCALING.scaleInverse(xAxisRangeControl.getMin()), Stx.LOG10_SCALING.scaleInverse(xAxisRangeControl.getMax()), 3); } } adjusting = false; } } } private class StxWorker extends ProgressMonitorSwingWorker<Stx, Object> { private final Double min; private final Double max; private final boolean autoMinMaxEnabled; private final boolean compute; public StxWorker(Double min, Double max, boolean autoMinMaxEnabled, boolean compute) { super(HistogramPanel.this, "Computing Histogram"); this.min = min; this.max = max; this.autoMinMaxEnabled = autoMinMaxEnabled; this.compute = compute; } @Override protected Stx doInBackground(ProgressMonitor pm) throws Exception { final Stx stx; HistogramPanelModel.HistogramConfig config = createHistogramConfig(); if (model.hasStx(config)) { return model.getStx(config); } if (!compute) { return null; } if (histogramPlotConfig.useRoiMask || histogramPlotConfig.numBins != Stx.DEFAULT_BIN_COUNT || histogramPlotConfig.histogramLogScaled || min != null || max != null) { final StxFactory factory = new StxFactory(); if (histogramPlotConfig.useRoiMask) { /*if(histogramPlotConfig.roiMask.getValidShape() == null){ handleError("The selected mask is empty.\n"+ "No valid histogram could be computed."); }*/ factory.withRoiMask(histogramPlotConfig.roiMask); } factory.withHistogramBinCount(histogramPlotConfig.numBins); factory.withLogHistogram(histogramPlotConfig.histogramLogScaled); if (min != null) { if (histogramPlotConfig.histogramLogScaled) { factory.withMinimum(Stx.LOG10_SCALING.scaleInverse(min)); } else { factory.withMinimum(min); } } if (max != null) { if (histogramPlotConfig.histogramLogScaled) { factory.withMaximum(Stx.LOG10_SCALING.scaleInverse(max)); } else { factory.withMaximum(max); } } stx = factory.create(getRaster(), pm); } else { stx = getRaster().getStx(true, pm); } if (getRaster() != config.raster) { return null; } return stx; } @Override public void done() { try { Stx stx = get(); if (stx == null) { return; } if (stx.getSampleCount() > 0) { if (autoMinMaxEnabled) { histogramComputing = true; xAxisRangeControl.adjustComponents( stx.getHistogramScaling().scale(stx.getMinimum()), stx.getHistogramScaling().scale(stx.getMaximum()), 4); histogramComputing = false; } setStx(stx); } else { Dialogs.showError("Either the selected ROI is empty or no pixels have been found within the minimum and maximum values specified.\n" + "No valid histogram could be computed.\n"); handleStxChange(); } } catch (ExecutionException e) { if (histogramPlotConfig.useRoiMask) { Dialogs.showError("An internal error occurred.\n" + "No valid histogram could be computed.\n" + "Possible reason: The selected ROI is empty."); } else { Dialogs.showError("An internal error occurred.\n" + "No valid histogram could be computed. Reason:\n" + e.getMessage()); } handleStxChange(); } catch (InterruptedException e) { Dialogs.showError("The histogram computation has been interrupted."); handleStxChange(); } } } private class ConfigChangeListener implements PropertyChangeListener, ActionListener { @Override public void propertyChange(PropertyChangeEvent evt) { handleConfigChanged(); } @Override public void actionPerformed(ActionEvent e) { handleConfigChanged(); } private void handleConfigChanged() { updateChartData(false); updateRefreshButton(); } } }
28,653
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StatisticsDataProvider.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/StatisticsDataProvider.java
/* * Copyright (C) 2011 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VectorDataNode; import javax.media.jai.Histogram; /** * @author Thomas Storm */ interface StatisticsDataProvider { RasterDataNode getRasterDataNode(); Histogram[] getHistograms(); ProductNodeGroup<VectorDataNode> getVectorDataNodeGroup(); }
1,162
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GeoCodingTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/GeoCodingTopComponent.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.statistics; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; @TopComponent.Description( preferredID = "GeoCodingTopComponent", iconBase = "org/esa/snap/rcp/icons/PhiLam.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "GeoCodingMode", openAtStartup = false, position = 30 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.GeoCodingTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 40), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_GeoCodingTopComponent_Name", preferredID = "GeoCodingTopComponent" ) @NbBundle.Messages({ "CTL_GeoCodingTopComponent_Name=Geo-Coding", "CTL_GeoCodingTopComponent_HelpId=geoCodingInfoDialog" }) /** * The tool view containing geo-coding information * * @author Marco Zuehlke */ public class GeoCodingTopComponent extends AbstractStatisticsTopComponent { @Override protected PagePanel createPagePanel() { return new GeoCodingPanel(this, Bundle.CTL_GeoCodingTopComponent_HelpId()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_GeoCodingTopComponent_HelpId()); } }
2,255
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MultipleRoiComputePanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/MultipleRoiComputePanel.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import com.jidesoft.swing.CheckBoxList; 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.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.ProductNodeListener; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.util.StringUtils; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import org.openide.util.ImageUtilities; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; import javax.swing.AbstractButton; import javax.swing.DefaultListModel; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.ArrayList; import java.util.List; /** * A panel which performs the 'compute' action. * * @author Marco Zuehlke */ class MultipleRoiComputePanel extends JPanel { private DefaultListModel<String> maskNameListModel; private final JTextField maskNameSearchField; private int[] indexesInMaskNameList; interface ComputeMasks { void compute(Mask[] selectedMasks); } private final ProductNodeListener productNodeListener; private final AbstractButton refreshButton; private final JCheckBox useRoiCheckBox; private final CheckBoxList maskNameList; private final JCheckBox selectAllCheckBox; private final JCheckBox selectNoneCheckBox; private RasterDataNode raster; private Product product; MultipleRoiComputePanel(final ComputeMasks method, final RasterDataNode rasterDataNode) { productNodeListener = new PNL(); maskNameSearchField = new JTextField(); maskNameSearchField.setEnabled(false); maskNameSearchField.getDocument().addDocumentListener(new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { updateMaskListState(); } @Override public void removeUpdate(DocumentEvent e) { updateMaskListState(); } @Override public void changedUpdate(DocumentEvent e) { updateMaskListState(); } }); maskNameList = new CheckBoxList(new DefaultListModel()); maskNameList.getCheckBoxListSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); maskNameList.getCheckBoxListSelectionModel().addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(ListSelectionEvent e) { updateEnablement(); refreshButton.setEnabled(true); if (!e.getValueIsAdjusting()) { selectAndEnableCheckBoxes(); } } }); useRoiCheckBox = new JCheckBox("Use ROI mask(s):"); useRoiCheckBox.setMnemonic('R'); useRoiCheckBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateEnablement(); } }); final JPanel topPanel = new JPanel(new BorderLayout()); refreshButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/ViewRefresh22.png"), false); refreshButton.setEnabled(rasterDataNode != null); refreshButton.setToolTipText("Refresh View"); refreshButton.setName("refreshButton"); refreshButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { boolean useRoi = useRoiCheckBox.isSelected(); Mask[] selectedMasks; if (useRoi) { int[] listIndexes = maskNameList.getCheckBoxListSelectedIndices(); if (listIndexes.length > 0) { selectedMasks = new Mask[listIndexes.length]; for (int i = 0; i < listIndexes.length; i++) { int listIndex = listIndexes[i]; String maskName = maskNameList.getModel().getElementAt(listIndex).toString(); selectedMasks[i] = raster.getProduct().getMaskGroup().get(maskName); } } else { selectedMasks = new Mask[]{null}; } } else { selectedMasks = new Mask[]{null}; } method.compute(selectedMasks); refreshButton.setEnabled(false); } }); topPanel.add(refreshButton, BorderLayout.WEST); //todo enable showMaskManagerButton AbstractButton showMaskManagerButton = createShowMaskManagerButton(); selectAllCheckBox = new JCheckBox("Select all"); selectAllCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (selectAllCheckBox.isSelected()) { maskNameList.selectAll(); } selectAndEnableCheckBoxes(); } }); selectNoneCheckBox = new JCheckBox("Select none"); selectNoneCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if (selectNoneCheckBox.isSelected()) { maskNameList.selectNone(); } selectAndEnableCheckBoxes(); } }); JPanel checkBoxPanel = new JPanel(); checkBoxPanel.add(selectAllCheckBox); checkBoxPanel.add(selectNoneCheckBox); final JPanel multiRoiComputePanel = GridBagUtils.createPanel(); GridBagConstraints multiRoiComputePanelConstraints = GridBagUtils.createConstraints("anchor=NORTHWEST,weightx=1"); GridBagUtils.addToPanel(multiRoiComputePanel, topPanel, multiRoiComputePanelConstraints, "gridx=0,gridy=0,gridwidth=3"); GridBagUtils.addToPanel(multiRoiComputePanel, new JSeparator(), multiRoiComputePanelConstraints, "gridy=1,fill=HORIZONTAL"); GridBagUtils.addToPanel(multiRoiComputePanel, useRoiCheckBox, multiRoiComputePanelConstraints, "gridy=2,weightx=0"); GridBagUtils.addToPanel(multiRoiComputePanel, new JLabel(("Filter: ")), multiRoiComputePanelConstraints, "gridy=3,gridx=0,gridwidth=1,anchor=WEST"); GridBagUtils.addToPanel(multiRoiComputePanel, maskNameSearchField, multiRoiComputePanelConstraints, "gridx=1,weightx=1"); GridBagUtils.addToPanel(multiRoiComputePanel, showMaskManagerButton, multiRoiComputePanelConstraints, "gridy=3,gridx=2,weightx=0"); GridBagUtils.addToPanel(multiRoiComputePanel, new JScrollPane(maskNameList), multiRoiComputePanelConstraints, "gridy=4,gridx=0,fill=HORIZONTAL,gridwidth=3,anchor=NORTHWEST"); GridBagUtils.addToPanel(multiRoiComputePanel, checkBoxPanel, multiRoiComputePanelConstraints, "gridy=5,weighty=1,gridwidth=3"); add(multiRoiComputePanel); setRaster(rasterDataNode); } private AbstractButton createShowMaskManagerButton() { final AbstractButton showMaskManagerButton = ToolButtonFactory.createButton(ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/MaskManager24.png", false), false); showMaskManagerButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SwingUtilities.invokeLater(new Runnable() { public void run() { final TopComponent maskManagerTopComponent = WindowManager.getDefault().findTopComponent("MaskManagerTopComponent"); maskManagerTopComponent.open(); maskManagerTopComponent.requestActive(); } }); } }); return showMaskManagerButton; } void setRaster(final RasterDataNode newRaster) { if (this.raster != newRaster) { this.raster = newRaster; if (newRaster == null) { if (product != null) { product.removeProductNodeListener(productNodeListener); } product = null; } else if (product != newRaster.getProduct()) { if (product != null) { product.removeProductNodeListener(productNodeListener); } product = newRaster.getProduct(); if (product != null) { product.addProductNodeListener(productNodeListener); } } resetMaskListState(); refreshButton.setEnabled(raster != null); } } private void selectAndEnableCheckBoxes() { final int numEntries = maskNameList.getModel().getSize(); final int numSelected = maskNameList.getCheckBoxListSelectedIndices().length; selectNoneCheckBox.setEnabled(numSelected > 0); selectAllCheckBox.setEnabled(numSelected < numEntries); selectNoneCheckBox.setSelected(numSelected == 0); selectAllCheckBox.setSelected(numSelected == numEntries); } private String[] getSelectedMaskNames() { final Object[] selectedValues = maskNameList.getCheckBoxListSelectedValues(); return StringUtils.toStringArray(selectedValues); } private void resetMaskListState() { maskNameListModel = new DefaultListModel<>(); final String[] currentSelectedMaskNames = getSelectedMaskNames(); if (product != null && raster != null) { //todo [multisize_products] compare scenerastertransform (or its successor) rather than size (tf) final ProductNodeGroup<Mask> maskGroup = product.getMaskGroup(); for (int i = 0; i < maskGroup.getNodeCount(); i++) { final Mask mask = maskGroup.get(i); if (mask.getRasterSize().equals(raster.getRasterSize())) { maskNameListModel.addElement(mask.getName()); } } maskNameList.setModel(maskNameListModel); } final String[] allNames = StringUtils.toStringArray(maskNameListModel.toArray()); indexesInMaskNameList = new int[allNames.length]; for (int i = 0; i < allNames.length; i++) { String name = allNames[i]; if (StringUtils.contains(currentSelectedMaskNames, name)) { maskNameList.getCheckBoxListSelectionModel().addSelectionInterval(i, i); } indexesInMaskNameList[i] = i; } updateEnablement(); } void updateEnablement() { boolean hasMasks = (product != null && product.getMaskGroup().getNodeCount() > 0); boolean canSelectMasks = hasMasks && useRoiCheckBox.isSelected(); useRoiCheckBox.setEnabled(hasMasks); maskNameSearchField.setEnabled(canSelectMasks); maskNameList.setEnabled(canSelectMasks); selectAllCheckBox.setEnabled(canSelectMasks && maskNameList.getCheckBoxListSelectedIndices().length < maskNameList.getModel().getSize()); selectNoneCheckBox.setEnabled(canSelectMasks && maskNameList.getCheckBoxListSelectedIndices().length > 0); refreshButton.setEnabled(raster != null); } private void updateMaskListState() { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { final String text = maskNameSearchField.getText(); final DefaultListModel<Object> updatedListModel = new DefaultListModel<>(); List<Boolean> selected = new ArrayList<>(); int[] newIndexesInMaskNameList = new int[maskNameListModel.getSize()]; int counter = 0; for (int i = 0; i < maskNameListModel.getSize(); i++) { if (maskNameListModel.get(i).toLowerCase().contains(text.toLowerCase())) { updatedListModel.addElement(maskNameListModel.get(i)); if (indexesInMaskNameList[i] >= 0) { selected.add(maskNameList.getCheckBoxListSelectionModel().isSelectedIndex(indexesInMaskNameList[i])); } else { selected.add(false); } newIndexesInMaskNameList[i] = counter++; } else { newIndexesInMaskNameList[i] = -1; } } indexesInMaskNameList = newIndexesInMaskNameList; maskNameList.setModel(updatedListModel); for (int i = 0; i < selected.size(); i++) { if (selected.get(i)) { maskNameList.getCheckBoxListSelectionModel().addSelectionInterval(i, i); } } } }); } private class PNL implements ProductNodeListener { @Override public void nodeAdded(ProductNodeEvent event) { handleEvent(event); } @Override public void nodeChanged(ProductNodeEvent event) { // handleEvent(event); } @Override public void nodeDataChanged(ProductNodeEvent event) { if (!useRoiCheckBox.isSelected()) { return; } final ProductNode sourceNode = event.getSourceNode(); if (!(sourceNode instanceof Mask)) { return; } final String maskName = ((Mask) sourceNode).getName(); final String[] selectedNames = getSelectedMaskNames(); if (StringUtils.contains(selectedNames, maskName)) { updateEnablement(); } } @Override public void nodeRemoved(ProductNodeEvent event) { handleEvent(event); } private void handleEvent(ProductNodeEvent event) { ProductNode sourceNode = event.getSourceNode(); if (sourceNode instanceof Mask) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { resetMaskListState(); } }); } } } }
15,876
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ScatterPlotPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ScatterPlotPanel.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.statistics; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueRange; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.datamodel.GeoCoding; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Mask; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.core.dataop.barithm.BandArithmetic; import org.esa.snap.core.util.SystemUtils; 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.rcp.util.RoiMaskSelector; import org.esa.snap.ui.GridBagUtils; import org.geotools.feature.FeatureCollection; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.annotations.XYTitleAnnotation; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.block.BlockBorder; import org.jfree.chart.event.AxisChangeListener; import org.jfree.chart.plot.DatasetRenderingOrder; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DeviationRenderer; import org.jfree.chart.renderer.xy.XYErrorRenderer; import org.jfree.chart.title.TextTitle; import org.jfree.chart.ui.HorizontalAlignment; import org.jfree.chart.ui.RectangleAnchor; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.RectangleInsets; import org.jfree.data.Range; import org.jfree.data.function.Function2D; import org.jfree.data.function.LineFunction2D; import org.jfree.data.general.DatasetUtils; import org.jfree.data.statistics.Regression; import org.jfree.data.xy.XYDataItem; import org.jfree.data.xy.XYIntervalSeries; import org.jfree.data.xy.XYIntervalSeriesCollection; import org.jfree.data.xy.XYSeries; import org.locationtech.jts.geom.Point; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.AttributeDescriptor; import org.openide.windows.TopComponent; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; import java.util.logging.Level; /** * The scatter plot pane within the statistics window. * * @author Olaf Danne * @author Sabine Embacher */ class ScatterPlotPanel extends ChartPagePanel { public static final String CHART_TITLE = "Correlative Plot"; private static final String NO_DATA_MESSAGE = "No correlative plot computed yet.\n" + "To create a correlative plot\n" + " -Select a band" + "\n" + " -Select vector data (e.g., a SeaDAS 6.x track)" + "\n" + " -Select the data as point data source" + "\n" + " -Select a data field" + "\n" + HELP_TIP_MESSAGE + "\n" + ZOOM_TIP_MESSAGE; private final String PROPERTY_NAME_X_AXIS_LOG_SCALED = "xAxisLogScaled"; private final String PROPERTY_NAME_Y_AXIS_LOG_SCALED = "yAxisLogScaled"; private final String PROPERTY_NAME_DATA_FIELD = "dataField"; private final String PROPERTY_NAME_POINT_DATA_SOURCE = "pointDataSource"; private final String PROPERTY_NAME_BOX_SIZE = "boxSize"; private final String PROPERTY_NAME_SHOW_ACCEPTABLE_DEVIATION = "showAcceptableDeviation"; private final String PROPERTY_NAME_ACCEPTABLE_DEVIATION = "acceptableDeviationInterval"; private final String PROPERTY_NAME_SHOW_REGRESSION_LINE = "showRegressionLine"; private final ScatterPlotModel scatterPlotModel; private final BindingContext bindingContext; private final AxisRangeControl xAxisRangeControl; private final AxisRangeControl yAxisRangeControl; private final XYIntervalSeriesCollection scatterpointsDataset; private final XYIntervalSeriesCollection acceptableDeviationDataset; private final XYIntervalSeriesCollection regressionDataset; private final JFreeChart chart; private final ProductManager.Listener productRemovedListener; private final Map<Product, UserSettings> userSettingsMap; private ChartPanel scatterPlotDisplay; private ComputedData[] computedDatas; private CorrelativeFieldSelector correlativeFieldSelector; private Range xAutoRangeAxisRange; private Range yAutoRangeAxisRange; private AxisChangeListener domainAxisChangeListener; private boolean computingData; private XYTitleAnnotation r2Annotation; ScatterPlotPanel(TopComponent parentDialog, String helpId) { super(parentDialog, helpId, CHART_TITLE, false); userSettingsMap = new HashMap<>(); productRemovedListener = new ProductManager.Listener() { @Override public void productAdded(ProductManager.Event event) { } @Override public void productRemoved(ProductManager.Event event) { final UserSettings userSettings = userSettingsMap.remove(event.getProduct()); if (userSettings != null) { userSettings.dispose(); } } }; xAxisRangeControl = new AxisRangeControl("X-Axis"); yAxisRangeControl = new AxisRangeControl("Y-Axis"); scatterPlotModel = new ScatterPlotModel(); bindingContext = new BindingContext(PropertyContainer.createObjectBacked(scatterPlotModel)); scatterpointsDataset = new XYIntervalSeriesCollection(); acceptableDeviationDataset = new XYIntervalSeriesCollection(); regressionDataset = new XYIntervalSeriesCollection(); r2Annotation = new XYTitleAnnotation(0, 0, new TextTitle("")); chart = ChartFactory.createScatterPlot(CHART_TITLE, "", "", scatterpointsDataset, PlotOrientation.VERTICAL, true, true, false); chart.getXYPlot().setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); createDomainAxisChangeListener(); final PropertyChangeListener userSettingsUpdateListener = evt -> { if (getRaster() != null) { final VectorDataNode pointDataSourceValue = scatterPlotModel.pointDataSource; final AttributeDescriptor dataFieldValue = scatterPlotModel.dataField; final UserSettings userSettings = getUserSettings(getRaster().getProduct()); userSettings.set(getRaster().getName(), pointDataSourceValue, dataFieldValue); } }; bindingContext.addPropertyChangeListener(PROPERTY_NAME_DATA_FIELD, userSettingsUpdateListener); bindingContext.addPropertyChangeListener(PROPERTY_NAME_POINT_DATA_SOURCE, userSettingsUpdateListener); } @Override protected void handleLayerContentChanged() { computeChartDataIfPossible(); } @Override protected String getDataAsText() { if (scatterpointsDataset.getItemCount(0) > 0) { final ScatterPlotTableModel scatterPlotTableModel; scatterPlotTableModel = new ScatterPlotTableModel(getRasterName(), getCorrelativeDataName(), computedDatas); return scatterPlotTableModel.toCVS(); } return ""; } @Override protected void initComponents() { getAlternativeView().initComponents(); initParameters(); createUI(); SnapApp.getDefault().getProductManager().addListener(productRemovedListener); } @Override protected void updateComponents() { super.updateComponents(); if (!isVisible()) { return; } final AttributeDescriptor dataField = scatterPlotModel.dataField; xAxisRangeControl.setTitleSuffix(dataField != null ? dataField.getLocalName() : null); final RasterDataNode raster = getRaster(); yAxisRangeControl.setTitleSuffix(raster != null ? raster.getName() : null); if (raster != null) { final Product product = getProduct(); final String rasterName = raster.getName(); final UserSettings userSettings = getUserSettings(product); final VectorDataNode userSelectedPointDataSource = userSettings.getPointDataSource(rasterName); final AttributeDescriptor userSelectedDataField = userSettings.getDataField(rasterName); correlativeFieldSelector.updatePointDataSource(product); correlativeFieldSelector.updateDataField(); if (userSelectedPointDataSource != null) { correlativeFieldSelector.tryToSelectPointDataSource(userSelectedPointDataSource); } if (userSelectedDataField != null) { correlativeFieldSelector.tryToSelectDataField(userSelectedDataField); } } if (isRasterChanged()) { getPlot().getRangeAxis().setLabel(StatisticChartStyling.getAxisLabel(raster, "X", false)); computeChartDataIfPossible(); } } private String getCorrelativeDataName() { return scatterPlotModel.dataField.getLocalName(); } @Override protected void updateChartData() { } @Override public void nodeAdded(ProductNodeEvent event) { if (event.getSourceNode() instanceof Placemark) { updateComponents(); } } @Override public void nodeRemoved(ProductNodeEvent event) { if (event.getSourceNode() instanceof VectorDataNode) { updateComponents(); computeChartDataIfPossible(); } } @Override protected void showAlternativeView() { final TableModel model; if (computedDatas != null && computedDatas.length > 0) { model = new ScatterPlotTableModel(getRasterName(), getCorrelativeDataName(), computedDatas); } else { model = new DefaultTableModel(); } final TableViewPagePanel alternativPanel = (TableViewPagePanel) getAlternativeView(); alternativPanel.setModel(model); super.showAlternativeView(); } private String getRasterName() { return getRaster() != null ? getRaster().getName() : ""; } private void initParameters() { final PropertyChangeListener recomputeListener = evt -> computeChartDataIfPossible(); bindingContext.addPropertyChangeListener(RoiMaskSelector.PROPERTY_NAME_USE_ROI_MASK, recomputeListener); bindingContext.addPropertyChangeListener(RoiMaskSelector.PROPERTY_NAME_ROI_MASK, recomputeListener); bindingContext.addPropertyChangeListener(PROPERTY_NAME_BOX_SIZE, recomputeListener); bindingContext.addPropertyChangeListener(PROPERTY_NAME_DATA_FIELD, recomputeListener); final PropertyChangeListener computeLineDataListener = evt -> computeRegressionAndAcceptableDeviationData(); bindingContext.addPropertyChangeListener(PROPERTY_NAME_SHOW_ACCEPTABLE_DEVIATION, computeLineDataListener); bindingContext.addPropertyChangeListener(PROPERTY_NAME_ACCEPTABLE_DEVIATION, computeLineDataListener); bindingContext.addPropertyChangeListener(PROPERTY_NAME_SHOW_REGRESSION_LINE, computeLineDataListener); final PropertyChangeListener rangeLabelUpdateListener = evt -> { final VectorDataNode pointDataSource = scatterPlotModel.pointDataSource; final AttributeDescriptor dataField = scatterPlotModel.dataField; if (dataField != null && pointDataSource != null) { final String dataFieldName = dataField.getLocalName(); getPlot().getDomainAxis().setLabel(dataFieldName); xAxisRangeControl.setTitleSuffix(dataFieldName); } else { getPlot().getDomainAxis().setLabel(""); xAxisRangeControl.setTitleSuffix(""); } }; bindingContext.addPropertyChangeListener(PROPERTY_NAME_DATA_FIELD, rangeLabelUpdateListener); bindingContext.addPropertyChangeListener(PROPERTY_NAME_POINT_DATA_SOURCE, rangeLabelUpdateListener); bindingContext.addPropertyChangeListener(PROPERTY_NAME_X_AXIS_LOG_SCALED, evt -> updateScalingOfXAxis()); bindingContext.addPropertyChangeListener(PROPERTY_NAME_Y_AXIS_LOG_SCALED, evt -> updateScalingOfYAxis()); xAxisRangeControl.getBindingContext().addPropertyChangeListener( evt -> handleAxisRangeControlChanges(evt, xAxisRangeControl, getPlot().getDomainAxis(), xAutoRangeAxisRange)); yAxisRangeControl.getBindingContext().addPropertyChangeListener( evt -> handleAxisRangeControlChanges(evt, yAxisRangeControl, getPlot().getRangeAxis(), yAutoRangeAxisRange)); } private void handleAxisRangeControlChanges(PropertyChangeEvent evt, AxisRangeControl axisRangeControl, ValueAxis valueAxis, Range computedAutoRange) { final String propertyName = evt.getPropertyName(); switch (propertyName) { case AxisRangeControl.PROPERTY_NAME_AUTO_MIN_MAX: if (axisRangeControl.isAutoMinMax()) { final double min = computedAutoRange.getLowerBound(); final double max = computedAutoRange.getUpperBound(); axisRangeControl.adjustComponents(min, max, 3); } break; case AxisRangeControl.PROPERTY_NAME_MIN: valueAxis.setLowerBound(axisRangeControl.getMin()); break; case AxisRangeControl.PROPERTY_NAME_MAX: valueAxis.setUpperBound(axisRangeControl.getMax()); break; } } private void createUI() { final XYPlot plot = getPlot(); plot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); plot.setNoDataMessage(NO_DATA_MESSAGE); int confidenceDSIndex = 0; int regressionDSIndex = 1; int scatterpointsDSIndex = 2; plot.setDataset(confidenceDSIndex, acceptableDeviationDataset); plot.setDataset(regressionDSIndex, regressionDataset); plot.setDataset(scatterpointsDSIndex, scatterpointsDataset); plot.addAnnotation(r2Annotation); final DeviationRenderer identityRenderer = new DeviationRenderer(true, false); identityRenderer.setSeriesPaint(0, StatisticChartStyling.SAMPLE_DATA_PAINT); identityRenderer.setSeriesFillPaint(0, StatisticChartStyling.SAMPLE_DATA_FILL_PAINT); plot.setRenderer(confidenceDSIndex, identityRenderer); final DeviationRenderer regressionRenderer = new DeviationRenderer(true, false); regressionRenderer.setSeriesPaint(0, StatisticChartStyling.REGRESSION_DATA_PAINT); regressionRenderer.setSeriesFillPaint(0, StatisticChartStyling.REGRESSION_DATA_FILL_PAINT); plot.setRenderer(regressionDSIndex, regressionRenderer); final XYErrorRenderer scatterPointsRenderer = new XYErrorRenderer(); scatterPointsRenderer.setDrawXError(true); scatterPointsRenderer.setErrorStroke(new BasicStroke(1)); scatterPointsRenderer.setErrorPaint(StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesShape(0, StatisticChartStyling.CORRELATIVE_POINT_SHAPE); scatterPointsRenderer.setSeriesOutlinePaint(0, StatisticChartStyling.CORRELATIVE_POINT_OUTLINE_PAINT); scatterPointsRenderer.setSeriesFillPaint(0, StatisticChartStyling.CORRELATIVE_POINT_FILL_PAINT); scatterPointsRenderer.setSeriesLinesVisible(0, false); scatterPointsRenderer.setSeriesShapesVisible(0, true); scatterPointsRenderer.setSeriesOutlineStroke(0, new BasicStroke(1.0f)); scatterPointsRenderer.setSeriesToolTipGenerator(0, (dataset, series, item) -> { final XYIntervalSeriesCollection collection = (XYIntervalSeriesCollection) dataset; final Comparable key = collection.getSeriesKey(series); final double xValue = collection.getXValue(series, item); final double endYValue = collection.getEndYValue(series, item); final double yValue = collection.getYValue(series, item); return String.format("%s: mean = %6.2f, sigma = %6.2f | %s: value = %6.2f", getRasterName(), yValue, endYValue - yValue, key, xValue); }); plot.setRenderer(scatterpointsDSIndex, scatterPointsRenderer); final boolean autoRangeIncludesZero = false; final boolean xLog = scatterPlotModel.xAxisLogScaled; final boolean yLog = scatterPlotModel.yAxisLogScaled; plot.setDomainAxis( StatisticChartStyling.updateScalingOfAxis(xLog, plot.getDomainAxis(), autoRangeIncludesZero)); plot.setRangeAxis(StatisticChartStyling.updateScalingOfAxis(yLog, plot.getRangeAxis(), autoRangeIncludesZero)); createUI(createChartPanel(chart), createInputParameterPanel(), bindingContext); plot.getDomainAxis().addChangeListener(domainAxisChangeListener); scatterPlotDisplay.setMouseWheelEnabled(true); scatterPlotDisplay.setMouseZoomable(true); } private void createDomainAxisChangeListener() { domainAxisChangeListener = event -> { if (!computingData) { computeRegressionAndAcceptableDeviationData(); } }; } private ChartPanel createChartPanel(final JFreeChart chart) { scatterPlotDisplay = new ChartPanel(chart) { @Override public void restoreAutoBounds() { // here we tweak the notify flag on the plot so that only // one notification happens even though we update multiple // axes... final XYPlot plot = chart.getXYPlot(); boolean savedNotify = plot.isNotify(); plot.setNotify(false); xAxisRangeControl.adjustAxis(plot.getDomainAxis(), 3); yAxisRangeControl.adjustAxis(plot.getRangeAxis(), 3); plot.setNotify(savedNotify); } }; MaskSelectionToolSupport maskSelectionToolSupport = new MaskSelectionToolSupport(this, scatterPlotDisplay, "correlative_plot_area", "Mask generated from selected correlative plot area", Color.RED, PlotAreaSelectionTool.AreaType.Y_RANGE) { @Override protected String createMaskExpression(PlotAreaSelectionTool.AreaType areaType, Shape shape) { Rectangle2D bounds = shape.getBounds2D(); return createMaskExpression(bounds.getMinY(), bounds.getMaxY()); } protected String createMaskExpression(double x1, double x2) { String bandName = BandArithmetic.createExternalName(getRaster().getName()); return String.format("%s >= %s && %s <= %s", bandName, x1, bandName, x2); } }; scatterPlotDisplay.getPopupMenu().addSeparator(); scatterPlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createMaskSelectionModeMenuItem()); scatterPlotDisplay.getPopupMenu().add(maskSelectionToolSupport.createDeleteMaskMenuItem()); scatterPlotDisplay.getPopupMenu().addSeparator(); scatterPlotDisplay.getPopupMenu().add(createCopyDataToClipboardMenuItem()); return scatterPlotDisplay; } private JPanel createInputParameterPanel() { final PropertyDescriptor boxSizeDescriptor = bindingContext.getPropertySet().getDescriptor( PROPERTY_NAME_BOX_SIZE); boxSizeDescriptor.setValueRange(new ValueRange(1, 101)); boxSizeDescriptor.setAttribute("stepSize", 2); boxSizeDescriptor.setValidator((property, value) -> { if (((Number) value).intValue() % 2 == 0) { throw new ValidationException("Only odd values allowed as box size."); } }); final JSpinner boxSizeSpinner = new JSpinner(); bindingContext.bind(PROPERTY_NAME_BOX_SIZE, boxSizeSpinner); final JPanel boxSizePanel = new JPanel(new BorderLayout(5, 3)); boxSizePanel.add(new JLabel("Box size:"), BorderLayout.WEST); boxSizePanel.add(boxSizeSpinner); correlativeFieldSelector = new CorrelativeFieldSelector(bindingContext); final JPanel pointDataSourcePanel = new JPanel(new BorderLayout(5, 3)); pointDataSourcePanel.add(correlativeFieldSelector.pointDataSourceLabel, BorderLayout.NORTH); pointDataSourcePanel.add(correlativeFieldSelector.pointDataSourceList); final JPanel pointDataFieldPanel = new JPanel(new BorderLayout(5, 3)); pointDataFieldPanel.add(correlativeFieldSelector.dataFieldLabel, BorderLayout.NORTH); pointDataFieldPanel.add(correlativeFieldSelector.dataFieldList); final JCheckBox xLogCheck = new JCheckBox("Log10 scaled"); bindingContext.bind(PROPERTY_NAME_X_AXIS_LOG_SCALED, xLogCheck); final JPanel xAxisOptionPanel = new JPanel(new BorderLayout()); xAxisOptionPanel.add(xAxisRangeControl.getPanel()); xAxisOptionPanel.add(xLogCheck, BorderLayout.SOUTH); final JCheckBox yLogCheck = new JCheckBox("Log10 scaled"); bindingContext.bind(PROPERTY_NAME_Y_AXIS_LOG_SCALED, yLogCheck); final JPanel yAxisOptionPanel = new JPanel(new BorderLayout()); yAxisOptionPanel.add(yAxisRangeControl.getPanel()); yAxisOptionPanel.add(yLogCheck, BorderLayout.SOUTH); final JCheckBox acceptableCheck = new JCheckBox("Show tolerance range"); JLabel fieldPrefix = new JLabel("+/-"); final JTextField acceptableField = new JTextField(); acceptableField.setPreferredSize(new Dimension(40, acceptableField.getPreferredSize().height)); acceptableField.setHorizontalAlignment(JTextField.RIGHT); final JLabel percentLabel = new JLabel(" %"); bindingContext.bind(PROPERTY_NAME_SHOW_ACCEPTABLE_DEVIATION, acceptableCheck); bindingContext.bind(PROPERTY_NAME_ACCEPTABLE_DEVIATION, acceptableField); bindingContext.getBinding(PROPERTY_NAME_ACCEPTABLE_DEVIATION).addComponent(percentLabel); bindingContext.getBinding(PROPERTY_NAME_ACCEPTABLE_DEVIATION).addComponent(fieldPrefix); bindingContext.bindEnabledState(PROPERTY_NAME_ACCEPTABLE_DEVIATION, true, PROPERTY_NAME_SHOW_ACCEPTABLE_DEVIATION, true); final JPanel confidencePanel = GridBagUtils.createPanel(); GridBagConstraints confidencePanelConstraints = GridBagUtils.createConstraints( "anchor=NORTHWEST,fill=HORIZONTAL,insets.top=5,weighty=0,weightx=1"); GridBagUtils.addToPanel(confidencePanel, acceptableCheck, confidencePanelConstraints, "gridy=0,gridwidth=3"); GridBagUtils.addToPanel(confidencePanel, fieldPrefix, confidencePanelConstraints, "weightx=0,insets.left=22,gridy=1,gridx=0,insets.top=4,gridwidth=1"); GridBagUtils.addToPanel(confidencePanel, acceptableField, confidencePanelConstraints, "weightx=1,gridx=1,insets.left=2,insets.top=2"); GridBagUtils.addToPanel(confidencePanel, percentLabel, confidencePanelConstraints, "weightx=0,gridx=2,insets.left=0,insets.top=4"); final JCheckBox regressionCheck = new JCheckBox("Show regression line"); bindingContext.bind(PROPERTY_NAME_SHOW_REGRESSION_LINE, regressionCheck); // UI arrangement JPanel middlePanel = GridBagUtils.createPanel(); GridBagConstraints middlePanelConstraints = GridBagUtils.createConstraints( "anchor=NORTHWEST,fill=HORIZONTAL,insets.top=6,weighty=0,weightx=1"); GridBagUtils.addToPanel(middlePanel, boxSizePanel, middlePanelConstraints, "gridy=0,insets.left=6"); GridBagUtils.addToPanel(middlePanel, pointDataSourcePanel, middlePanelConstraints, "gridy=1"); GridBagUtils.addToPanel(middlePanel, pointDataFieldPanel, middlePanelConstraints, "gridy=2"); GridBagUtils.addToPanel(middlePanel, xAxisOptionPanel, middlePanelConstraints, "gridy=3,insets.left=0"); GridBagUtils.addToPanel(middlePanel, yAxisOptionPanel, middlePanelConstraints, "gridy=4"); GridBagUtils.addToPanel(middlePanel, new JSeparator(), middlePanelConstraints, "gridy=5,insets.left=4"); GridBagUtils.addToPanel(middlePanel, confidencePanel, middlePanelConstraints, "gridy=6,fill=HORIZONTAL,insets.left=-4"); GridBagUtils.addToPanel(middlePanel, regressionCheck, middlePanelConstraints, "gridy=7,insets.left=-4,insets.top=8"); return middlePanel; } private void updateScalingOfXAxis() { final boolean logScaled = scatterPlotModel.xAxisLogScaled; final ValueAxis oldAxis = getPlot().getDomainAxis(); ValueAxis newAxis = StatisticChartStyling.updateScalingOfAxis(logScaled, oldAxis, false); oldAxis.removeChangeListener(domainAxisChangeListener); newAxis.addChangeListener(domainAxisChangeListener); getPlot().setDomainAxis(newAxis); finishScalingUpdate(xAxisRangeControl, newAxis, oldAxis); } private void updateScalingOfYAxis() { final boolean logScaled = scatterPlotModel.yAxisLogScaled; final ValueAxis oldAxis = getPlot().getRangeAxis(); ValueAxis newAxis = StatisticChartStyling.updateScalingOfAxis(logScaled, oldAxis, false); getPlot().setRangeAxis(newAxis); finishScalingUpdate(yAxisRangeControl, newAxis, oldAxis); } private void finishScalingUpdate(AxisRangeControl axisRangeControl, ValueAxis newAxis, ValueAxis oldAxis) { if (axisRangeControl.isAutoMinMax()) { newAxis.setAutoRange(false); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); newAxis.setAutoRange(true); axisRangeControl.adjustComponents(newAxis, 3); newAxis.setAutoRange(false); computeRegressionAndAcceptableDeviationData(); } else { newAxis.setAutoRange(false); newAxis.setRange(oldAxis.getRange()); } } private XYPlot getPlot() { return chart.getXYPlot(); } private void computeChartDataIfPossible() { // need to do this later: all GUI events must be processed first in order to get the correct state SwingUtilities.invokeLater(() -> { if (scatterPlotModel.pointDataSource != null && scatterPlotModel.dataField != null && scatterPlotModel.pointDataSource.getFeatureCollection() != null && scatterPlotModel.pointDataSource.getFeatureCollection().features() != null && scatterPlotModel.pointDataSource.getFeatureCollection().features().hasNext() && scatterPlotModel.pointDataSource.getFeatureCollection().features().next() != null && scatterPlotModel.pointDataSource.getFeatureCollection().features().next().getAttribute( scatterPlotModel.dataField.getLocalName()) != null && getRaster() != null) { compute(scatterPlotModel.useRoiMask ? scatterPlotModel.roiMask : null); } else { scatterpointsDataset.removeAllSeries(); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); computedDatas = null; } }); } private void compute(final Mask selectedMask) { final RasterDataNode raster = getRaster(); final AttributeDescriptor dataField = scatterPlotModel.dataField; if (raster == null || dataField == null) { return; } SwingWorker<ComputedData[], Object> swingWorker = new SwingWorker<ComputedData[], Object>() { @Override protected ComputedData[] doInBackground() throws Exception { SystemUtils.LOG.finest("start computing scatter plot data"); final List<ComputedData> computedDataList = new ArrayList<>(); final FeatureCollection<SimpleFeatureType, SimpleFeature> collection = scatterPlotModel.pointDataSource.getFeatureCollection(); final SimpleFeature[] features = collection.toArray(new SimpleFeature[collection.size()]); final int boxSize = scatterPlotModel.boxSize; final Rectangle sceneRect = new Rectangle(raster.getRasterWidth(), raster.getRasterHeight()); final GeoCoding geoCoding = raster.getGeoCoding(); final AffineTransform imageToModelTransform; imageToModelTransform = Product.findImageToModelTransform(geoCoding); for (SimpleFeature feature : features) { final Point point = (Point) feature.getDefaultGeometryProperty().getValue(); Point2D modelPos = new Point2D.Float((float) point.getX(), (float) point.getY()); final Point2D imagePos = imageToModelTransform.inverseTransform(modelPos, null); if (!sceneRect.contains(imagePos)) { continue; } final float imagePosX = (float) imagePos.getX(); final float imagePosY = (float) imagePos.getY(); final Rectangle imageRect = sceneRect.intersection(new Rectangle(((int) imagePosX) - boxSize / 2, ((int) imagePosY) - boxSize / 2, boxSize, boxSize)); if (imageRect.isEmpty()) { continue; } final double[] rasterValues = new double[imageRect.width * imageRect.height]; raster.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, rasterValues); final int[] maskBuffer = new int[imageRect.width * imageRect.height]; Arrays.fill(maskBuffer, 1); if (selectedMask != null) { selectedMask.readPixels(imageRect.x, imageRect.y, imageRect.width, imageRect.height, maskBuffer); } final int centerIndex = imageRect.width * (imageRect.height / 2) + (imageRect.width / 2); if (maskBuffer[centerIndex] == 0) { continue; } double sum = 0; double sumSqr = 0; int n = 0; boolean valid = false; for (int y = 0; y < imageRect.height; y++) { for (int x = 0; x < imageRect.width; x++) { final int index = y * imageRect.height + x; if (raster.isPixelValid(x + imageRect.x, y + imageRect.y) && maskBuffer[index] != 0) { final double rasterValue = rasterValues[index]; sum += rasterValue; sumSqr += rasterValue * rasterValue; n++; valid = true; } } } if (!valid) { continue; } double rasterMean = sum / n; double rasterSigma = n > 1 ? Math.sqrt((sumSqr - (sum * sum) / n) / (n - 1)) : 0.0; String localName = dataField.getLocalName(); Number attribute = (Number) feature.getAttribute(localName); final Collection<org.opengis.feature.Property> featureProperties = feature.getProperties(); final float correlativeData = attribute.floatValue(); final GeoPos geoPos = new GeoPos(); if (geoCoding.canGetGeoPos()) { final PixelPos pixelPos = new PixelPos(imagePosX, imagePosY); geoCoding.getGeoPos(pixelPos, geoPos); } else { geoPos.setInvalid(); } computedDataList.add( new ComputedData(imagePosX, imagePosY, (float) geoPos.getLat(), (float) geoPos.getLon(), (float) rasterMean, (float) rasterSigma, correlativeData, featureProperties)); } return computedDataList.toArray(new ComputedData[computedDataList.size()]); } @Override public void done() { try { final ValueAxis xAxis = getPlot().getDomainAxis(); final ValueAxis yAxis = getPlot().getRangeAxis(); xAxis.setAutoRange(false); yAxis.setAutoRange(false); scatterpointsDataset.removeAllSeries(); acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); computedDatas = null; final ComputedData[] data = get(); if (data.length == 0) { return; } computedDatas = data; final XYIntervalSeries scatterValues = new XYIntervalSeries(getCorrelativeDataName()); for (ComputedData computedData : computedDatas) { final float rasterMean = computedData.rasterMean; final float rasterSigma = computedData.rasterSigma; final float correlativeData = computedData.correlativeData; scatterValues.add(correlativeData, correlativeData, correlativeData, rasterMean, rasterMean - rasterSigma, rasterMean + rasterSigma); } computingData = true; scatterpointsDataset.addSeries(scatterValues); xAxis.setAutoRange(true); yAxis.setAutoRange(true); xAxis.setAutoRange(false); yAxis.setAutoRange(false); xAutoRangeAxisRange = new Range(xAxis.getLowerBound(), xAxis.getUpperBound()); yAutoRangeAxisRange = new Range(yAxis.getLowerBound(), yAxis.getUpperBound()); if (xAxisRangeControl.isAutoMinMax()) { xAxisRangeControl.adjustComponents(xAxis, 3); } else { xAxisRangeControl.adjustAxis(xAxis, 3); } if (yAxisRangeControl.isAutoMinMax()) { yAxisRangeControl.adjustComponents(yAxis, 3); } else { yAxisRangeControl.adjustAxis(yAxis, 3); } computeRegressionAndAcceptableDeviationData(); computingData = false; } catch (InterruptedException | CancellationException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n" + "Calculation canceled.", JOptionPane.ERROR_MESSAGE, null); } catch (ExecutionException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to compute correlative plot.", e); Dialogs.showMessage(CHART_TITLE, "Failed to compute correlative plot.\n" + "An error occurred:\n" + e.getCause().getMessage(), JOptionPane.ERROR_MESSAGE, null); } } }; swingWorker.execute(); } private void computeRegressionAndAcceptableDeviationData() { acceptableDeviationDataset.removeAllSeries(); regressionDataset.removeAllSeries(); getPlot().removeAnnotation(r2Annotation); if (computedDatas != null) { final ValueAxis domainAxis = getPlot().getDomainAxis(); final double min = domainAxis.getLowerBound(); final double max = domainAxis.getUpperBound(); acceptableDeviationDataset.addSeries(computeAcceptableDeviationData(min, max)); if (scatterPlotModel.showRegressionLine) { final XYIntervalSeries series = computeRegressionData(min, max); if (series != null) { regressionDataset.addSeries(series); computeCoefficientOfDetermination(); } } } } private XYIntervalSeries computeRegressionData(double xStart, double xEnd) { if (scatterpointsDataset.getItemCount(0) > 1) { final double[] coefficients = Regression.getOLSRegression(scatterpointsDataset, 0); final Function2D curve = new LineFunction2D(coefficients[0], coefficients[1]); final XYSeries regressionData = DatasetUtils.sampleFunction2DToSeries(curve, xStart, xEnd, 100, "regression line"); final XYIntervalSeries xyIntervalRegression = new XYIntervalSeries(regressionData.getKey()); for (int i = 0; i < regressionData.getItemCount(); i++) { XYDataItem item = regressionData.getDataItem(i); final double x = item.getXValue(); final double y = item.getYValue(); xyIntervalRegression.add(x, x, x, y, y, y); } return xyIntervalRegression; } else { Dialogs.showInformation("Unable to compute regression line.\n" + "At least 2 values are needed to compute regression coefficients."); return null; } } private void computeCoefficientOfDetermination() { int numberOfItems = scatterpointsDataset.getSeries(0).getItemCount(); double arithmeticMeanOfX = 0; //arithmetic mean of X double arithmeticMeanOfY = 0; //arithmetic mean of Y double varX = 0; //variance of X double varY = 0; //variance of Y double coVarXY = 0; //covariance of X and Y; //compute arithmetic means for (int i = 0; i < numberOfItems; i++) { arithmeticMeanOfX += scatterpointsDataset.getXValue(0, i); arithmeticMeanOfY += scatterpointsDataset.getYValue(0, i); } arithmeticMeanOfX /= numberOfItems; arithmeticMeanOfY /= numberOfItems; //compute variances and covariance for (int i = 0; i < numberOfItems; i++) { varX += Math.pow(scatterpointsDataset.getXValue(0, i) - arithmeticMeanOfX, 2); varY += Math.pow(scatterpointsDataset.getYValue(0, i) - arithmeticMeanOfY, 2); coVarXY += (scatterpointsDataset.getXValue(0, i) - arithmeticMeanOfX) * (scatterpointsDataset.getYValue(0, i) - arithmeticMeanOfY); } //computation of coefficient of determination double r2 = Math.pow(coVarXY, 2) / (varX * varY); r2 = MathUtils.round(r2, Math.pow(10.0, 5)); final double[] coefficients = Regression.getOLSRegression(scatterpointsDataset, 0); final double intercept = coefficients[0]; final double slope = coefficients[1]; final String linearEquation; if (intercept >= 0) { linearEquation = "y = " + (float) slope + "x + " + (float) intercept; } else { linearEquation = "y = " + (float) slope + "x - " + Math.abs((float) intercept); } TextTitle tt = new TextTitle(linearEquation + "\nR² = " + r2); tt.setTextAlignment(HorizontalAlignment.RIGHT); tt.setFont(chart.getLegend().getItemFont()); tt.setBackgroundPaint(new Color(200, 200, 255, 100)); tt.setFrame(new BlockBorder(Color.white)); tt.setPosition(RectangleEdge.BOTTOM); r2Annotation = new XYTitleAnnotation(0.98, 0.02, tt, RectangleAnchor.BOTTOM_RIGHT); r2Annotation.setMaxWidth(0.48); getPlot().addAnnotation(r2Annotation); } private XYIntervalSeries computeAcceptableDeviationData(double lowerBound, double upperBound) { final XYSeries identity = DatasetUtils.sampleFunction2DToSeries(x -> x, lowerBound, upperBound, 100, "1:1 line"); final XYIntervalSeries xyIntervalSeries = new XYIntervalSeries(identity.getKey()); for (int i = 0; i < identity.getItemCount(); i++) { XYDataItem item = identity.getDataItem(i); final double x = item.getXValue(); final double y = item.getYValue(); if (scatterPlotModel.showAcceptableDeviation) { final double acceptableDeviation = scatterPlotModel.acceptableDeviationInterval; final double xOff = acceptableDeviation * x / 100; final double yOff = acceptableDeviation * y / 100; xyIntervalSeries.add(x, x - xOff, x + xOff, y, y - yOff, y + yOff); } else { xyIntervalSeries.add(x, x, x, y, y, y); } } return xyIntervalSeries; } private UserSettings getUserSettings(Product product) { if (product == null) { return null; } if (userSettingsMap.get(product) == null) { userSettingsMap.put(product, new UserSettings()); } return userSettingsMap.get(product); } // The fields of this class are used by the binding framework @SuppressWarnings({"UnusedDeclaration", "FieldMayBeFinal"}) static class ScatterPlotModel { public boolean showRegressionLine; private int boxSize = 1; private boolean useRoiMask; private Mask roiMask; private VectorDataNode pointDataSource; private AttributeDescriptor dataField; private boolean xAxisLogScaled; private boolean yAxisLogScaled; private boolean showAcceptableDeviation; private double acceptableDeviationInterval = 15; } static class ComputedData { final float x; final float y; final float lat; final float lon; final float rasterMean; final float rasterSigma; final float correlativeData; final Collection<org.opengis.feature.Property> featureProperties; ComputedData(float x, float y, float lat, float lon, float rasterMean, float rasterSigma, float correlativeData, Collection<org.opengis.feature.Property> featureProperties) { this.x = x; this.y = y; this.lat = lat; this.lon = lon; this.rasterMean = rasterMean; this.rasterSigma = rasterSigma; this.correlativeData = correlativeData; this.featureProperties = featureProperties; } } private static class UserSettings { Map<String, VectorDataNode> pointDataSource = new HashMap<>(); Map<String, AttributeDescriptor> dataField = new HashMap<>(); public void set(String rasterName, VectorDataNode pointDataSourceValue, AttributeDescriptor dataFieldValue) { if (pointDataSourceValue != null && dataFieldValue != null) { pointDataSource.put(rasterName, pointDataSourceValue); dataField.put(rasterName, dataFieldValue); } } public VectorDataNode getPointDataSource(String rasterName) { return pointDataSource.get(rasterName); } public AttributeDescriptor getDataField(String rasterName) { return dataField.get(rasterName); } public void dispose() { pointDataSource.clear(); pointDataSource = null; dataField.clear(); dataField = null; } } }
46,322
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RefreshActionEnabler.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/RefreshActionEnabler.java
package org.esa.snap.rcp.statistics; import com.bc.ceres.binding.PropertyContainer; import java.util.ArrayList; import java.util.List; import javax.swing.AbstractButton; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.Arrays; import java.util.HashSet; /** * @author Tonio Fincke */ public class RefreshActionEnabler implements PropertyChangeListener { private final static String PROPERTY_NAME_AUTO_MIN_MAX = "autoMinMax"; private final static String PROPERTY_NAME_MIN = "min"; private final static String PROPERTY_NAME_MAX = "max"; private final static String PROPERTY_NAME_USE_ROI_MASK = "useRoiMask"; private final static String PROPERTY_NAME_ROI_MASK = "roiMask"; private HashSet<String> names = new HashSet<>(); private List<ProductBandEnablement> productBandEnablements = new ArrayList<>(); private AbstractButton refreshButton; public RefreshActionEnabler(AbstractButton rb, String... componentNames) { names.addAll(Arrays.asList(componentNames)); refreshButton = rb; } public void addProductBandEnablement(String productPropertyName, String bandPropertyName) { addProductBandEnablement(productPropertyName, bandPropertyName, false); } public void addProductBandEnablement(String productPropertyName, String bandPropertyName, boolean isOptional) { productBandEnablements.add(new ProductBandEnablement(productPropertyName, bandPropertyName, isOptional)); names.add(productPropertyName); names.add(bandPropertyName); } @Override public void propertyChange(PropertyChangeEvent evt) { if (names.contains(evt.getPropertyName())) { final PropertyContainer container = (PropertyContainer) evt.getSource(); boolean enableRefreshButton = true; if (evt.getPropertyName().equals(PROPERTY_NAME_USE_ROI_MASK) && evt.getNewValue().equals(true) && container.getProperty(PROPERTY_NAME_ROI_MASK).getValue() == null) { return; } else if (evt.getPropertyName().equals(PROPERTY_NAME_AUTO_MIN_MAX) && evt.getNewValue().equals(false)) { return; } else if (evt.getPropertyName().equals(PROPERTY_NAME_MIN) && (evt.getOldValue().equals(evt.getNewValue()) || container.getProperty(PROPERTY_NAME_AUTO_MIN_MAX).getValue().equals(true))) { return; } else if (evt.getPropertyName().equals(PROPERTY_NAME_MAX) && (evt.getOldValue().equals(evt.getNewValue()) || container.getProperty(PROPERTY_NAME_AUTO_MIN_MAX).getValue().equals(true))) { return; } else if (isFromMandatoryProduct(evt.getPropertyName()) && ((evt.getOldValue() == null && evt.getNewValue() != null) || (evt.getOldValue() != null && evt.getNewValue() == null) || !evt.getOldValue().equals(evt.getNewValue()))) { enableRefreshButton = false; } else if (isFromOptionalProduct(evt.getPropertyName()) && ((evt.getOldValue() == null && evt.getNewValue() != null) || (evt.getOldValue() != null && evt.getNewValue() == null) || !evt.getOldValue().equals(evt.getNewValue()))) { enableRefreshButton = true; } else if (isFromBand(evt.getPropertyName())) { if (notAllMandatoryBandsAreValid(container)) { enableRefreshButton = false; } else if ((evt.getOldValue() == null && evt.getNewValue() != null) || (evt.getOldValue() != null && evt.getNewValue() == null) || !evt.getOldValue().equals(evt.getNewValue())) { enableRefreshButton = true; } } else if ((evt.getOldValue() == null && evt.getNewValue() == null) || (evt.getOldValue() != null && evt.getNewValue() != null && evt.getOldValue().equals(evt.getNewValue()))) { return; } refreshButton.setEnabled(enableRefreshButton); } } private boolean notAllMandatoryBandsAreValid(PropertyContainer container) { for (ProductBandEnablement enablement : productBandEnablements) { if (container.getProperty(enablement.bandName).getValue() == null && !enablement.isOptional) { return true; } } return false; } private boolean isFromBand(String propertyName) { for (ProductBandEnablement enablement : productBandEnablements) { if (propertyName.equals(enablement.bandName)) { return true; } } return false; } private boolean isFromMandatoryProduct(String propertyName) { for (ProductBandEnablement enablement : productBandEnablements) { if (propertyName.equals(enablement.productName) && !enablement.isOptional) { return true; } } return false; } private boolean isFromOptionalProduct(String propertyName) { for (ProductBandEnablement enablement : productBandEnablements) { if (propertyName.equals(enablement.productName) && enablement.isOptional) { return true; } } return false; } private static class ProductBandEnablement { String productName; String bandName; boolean isOptional; ProductBandEnablement(String productName, String bandName, boolean isOptional) { this.productName = productName; this.bandName = bandName; this.isOptional = isOptional; } } }
5,782
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
HistogramPanelModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/HistogramPanelModel.java
/* * Copyright (C) 2013 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.Stx; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Thomas Storm */ class HistogramPanelModel { Map<HistogramConfig, Stx> stxMap = new HashMap<>(31); public boolean hasStx(HistogramConfig config) { return config != null && stxMap.containsKey(config); } public Stx getStx(HistogramConfig config) { if (!stxMap.containsKey(config)) { throw new IllegalArgumentException("No such key: " + config); } return stxMap.get(config); } public void setStx(HistogramConfig config, Stx stx) { if (hasStx(config)) { throw new IllegalArgumentException("Trying to overwrite valid stx for config: " + config); } stxMap.put(config, stx); } public void removeStxFromProduct(Product product) { List<HistogramConfig> toRemove = new ArrayList<>(7); for (HistogramConfig histogramConfig : stxMap.keySet()) { if (histogramConfig.raster.getProduct() == product) { toRemove.add(histogramConfig); } } for (HistogramConfig histogramConfig : toRemove) { stxMap.remove(histogramConfig); } } public void removeStx(HistogramConfig histogramPlotConfig) { stxMap.remove(histogramPlotConfig); } static class HistogramConfig { RasterDataNode raster; String roiMask; int numBins; boolean logScaledBins; HistogramConfig(RasterDataNode raster, String roiMask, int numBins, boolean logScaledBins) { this.raster = raster; this.roiMask = roiMask; this.numBins = numBins; this.logScaledBins = logScaledBins; } @Override public String toString() { return "HistogramConfig{" + "raster='" + raster + '\'' + "roiMask='" + roiMask + '\'' + ", numBins=" + numBins + ", logScaledBins=" + logScaledBins + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; HistogramConfig that = (HistogramConfig) o; return logScaledBins == that.logScaledBins && numBins == that.numBins && !(roiMask != null ? !roiMask.equals(that.roiMask) : that.roiMask != null) && raster == that.raster; } @Override public int hashCode() { int result = roiMask != null ? roiMask.hashCode() : 0; result = 31 * result + numBins; result = 31 * result + (logScaledBins ? 1 : 0); return result; } } }
3,742
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProfilePlotTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ProfilePlotTopComponent.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.statistics; import org.esa.snap.ui.UIUtils; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.Icon; @TopComponent.Description( preferredID = "ProfilePlotTopComponent", iconBase = "org/esa/snap/rcp/icons/ProfilePlot.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "ProfilePlot", openAtStartup = false, position = 30 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.ProfilePlotTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 30), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_ProfilePlotTopComponent_Name", preferredID = "ProfilePlotTopComponent" ) @NbBundle.Messages({ "CTL_ProfilePlotTopComponent_Name=Profile Plot", "CTL_ProfilePlotTopComponent_HelpId=profilePlotDialog" }) /** * The tool view containing a profile plot * * @author Marco Zuehlke */ public class ProfilePlotTopComponent extends AbstractStatisticsTopComponent { public static final String ID = ProfilePlotTopComponent.class.getName(); public static final String tableHelpID = "tableView"; @Override protected PagePanel createPagePanel() { final String helpId = Bundle.CTL_ProfilePlotTopComponent_HelpId(); final String chartTitle = ProfilePlotPanel.CHART_TITLE; final Icon largeIcon = UIUtils.loadImageIcon("icons/ProfilePlot24.gif"); ProfilePlotPanel profilePlotPanel = new ProfilePlotPanel(this, helpId); final TableViewPagePanel tableViewPagePanel = new TableViewPagePanel(this, tableHelpID, chartTitle, largeIcon); profilePlotPanel.setAlternativeView(tableViewPagePanel); tableViewPagePanel.setAlternativeView(profilePlotPanel); return profilePlotPanel; } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_ProfilePlotTopComponent_HelpId()); } }
2,959
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StatisticsTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/StatisticsTopComponent.java
package org.esa.snap.rcp.statistics; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; @TopComponent.Description( preferredID = "StatisticsTopComponent", iconBase = "org/esa/snap/rcp/icons/Statistics.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "Statistics", openAtStartup = false, position = 40 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.StatisticsTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 60), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_StatisticsTopComponent_Name", preferredID = "StatisticsTopComponent" ) @NbBundle.Messages({ "CTL_StatisticsTopComponent_Name=Statistics", "CTL_StatisticsTopComponent_HelpId=statisticsDialog" }) /** * @author Tonio Fincke */ public class StatisticsTopComponent extends AbstractStatisticsTopComponent { @Override protected PagePanel createPagePanel() { return new StatisticsPanel(this, Bundle.CTL_StatisticsTopComponent_HelpId()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_StatisticsTopComponent_HelpId()); } }
1,485
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
HistogramPlotTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/HistogramPlotTopComponent.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.statistics; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; @TopComponent.Description( preferredID = "HistogramPlotTopComponent", iconBase = "org/esa/snap/rcp/icons/Histogram.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "HistogramPlotMode", openAtStartup = false, position = 40 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.HistogramPlotTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 50), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_HistogramPlotTopComponent_Name", preferredID = "HistogramPlotTopComponent" ) @NbBundle.Messages({ "CTL_HistogramPlotTopComponent_Name=Histogram", "CTL_HistogramPlotTopComponent_HelpId=histogramDialog" }) /** * The tool view containing the histogram of a band * * @author Marco Zuehlke */ public class HistogramPlotTopComponent extends AbstractStatisticsTopComponent { public static final String ID = HistogramPlotTopComponent.class.getName(); @Override protected PagePanel createPagePanel() { return new HistogramPanel(this, Bundle.CTL_HistogramPlotTopComponent_HelpId()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_HistogramPlotTopComponent_HelpId()); } }
2,373
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MetadataPlotTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/MetadataPlotTableModel.java
package org.esa.snap.rcp.statistics; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYDataset; import javax.swing.table.AbstractTableModel; import java.util.ArrayList; import java.util.List; /** * @author Marco Peters */ class MetadataPlotTableModel extends AbstractTableModel { private XYPlot plot; private List<String> columList; MetadataPlotTableModel(XYPlot plot) { this.plot = plot; columList = new ArrayList<>(); columList.add(plot.getDomainAxis().getLabel()); for(int i = 0; i < plot.getDatasetCount(); i++) { columList.add(String.valueOf(plot.getDataset(i).getSeriesKey(0))); } } @Override public int getRowCount() { return plot.getDataset().getItemCount(0); } @Override public int getColumnCount() { return columList.size(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return plot.getDataset(columnIndex).getXValue(0, rowIndex); } else { XYDataset dataset = plot.getDataset(columnIndex - 1); int itemCount = dataset.getItemCount(0); if (rowIndex < itemCount) { return dataset.getYValue(0, rowIndex); }else { return null; } } } @Override public String getColumnName(int column) { return columList.get(column); } }
1,465
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MetadataPlotTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/MetadataPlotTopComponent.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.statistics; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.Icon; import javax.swing.ImageIcon; import java.awt.BorderLayout; /** * The tool view containing a density plot * */ @TopComponent.Description( preferredID = "MetadataPlotTopComponent", iconBase = "org/esa/snap/rcp/icons/MetadataPlot.png" ) @TopComponent.Registration( mode = "MetadataPlot", openAtStartup = false, position = 50 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.MetadataPlotTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 70), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_MetadataPlotTopComponent_Name", preferredID = "MetadataPlotTopComponent" ) @NbBundle.Messages({ "CTL_MetadataPlotTopComponent_Name=Metadata Plot", "CTL_MetadataPlotTopComponent_HelpId=metadataPlotDialog" }) public class MetadataPlotTopComponent extends AbstractStatisticsTopComponent { @Override protected PagePanel createPagePanel() { final Icon largeIcon = new ImageIcon(MetadataPlotTopComponent.class.getResource("/org/esa/snap/rcp/icons/MetadataPlot24.png")); MetadataPlotPanel metadataPlotPanel = new MetadataPlotPanel(this, Bundle.CTL_MetadataPlotTopComponent_HelpId()); final TableViewPagePanel tableViewPanel = new MetadataTableViewPagePanel(metadataPlotPanel, largeIcon); metadataPlotPanel.setAlternativeView(tableViewPanel); tableViewPanel.setAlternativeView(metadataPlotPanel); return metadataPlotPanel; } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_MetadataPlotTopComponent_HelpId()); } @Override protected void componentOpened() { super.componentOpened(); } private class MetadataTableViewPagePanel extends TableViewPagePanel { private MetadataTableViewPagePanel(MetadataPlotPanel metadataPlotPanel, Icon largeIcon) { super(MetadataPlotTopComponent.this, Bundle.CTL_MetadataPlotTopComponent_HelpId(), metadataPlotPanel.getTitle(), largeIcon); } @Override protected void showAlternativeView() { // this is overridden to avoid the clearance of the MetadataPlotPanel when // switching back from the MetadataTableViewPagePanel final TopComponent parent = (TopComponent) this.getParent(); parent.remove(this); this.setVisible(false); final PagePanel alternativeView = getAlternativeView(); alternativeView.handleLayerContentChanged(); parent.add(alternativeView, BorderLayout.CENTER); alternativeView.setVisible(true); parent.revalidate(); } } }
3,766
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CustomLogarithmicAxis.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/CustomLogarithmicAxis.java
package org.esa.snap.rcp.statistics; import org.jfree.chart.axis.LogarithmicAxis; import org.jfree.chart.axis.NumberTick; import org.jfree.chart.ui.RectangleEdge; import org.jfree.chart.ui.TextAnchor; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.text.NumberFormat; import java.util.List; /** * A logarithmic axis representation with improved scaling and labelling * * @author olafd * Date: 10.04.12 * Time: 21:06 */ public class CustomLogarithmicAxis extends LogarithmicAxis { static final int VERTICAL = 0; static final int HORIZONTAL = 1; /** * Creates a new axis. * * @param label the axis label. */ public CustomLogarithmicAxis(String label) { super(label); } @Override protected List refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { return refreshTicks(edge, HORIZONTAL); } @Override protected List refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) { return refreshTicks(edge, VERTICAL); } List refreshTicks(RectangleEdge edge, int mode) { // a much simpler approach compared to LogarithmicAxis... List ticks = new java.util.ArrayList(); double upperBoundVal = 0.0; double lowerBoundVal = 0.0; boolean NEGATIVE = false; if (getRange().getLowerBound() >= 0.0 && getRange().getUpperBound() >= 0.0) { upperBoundVal = getRange().getUpperBound(); lowerBoundVal = getRange().getLowerBound(); if (getRange().getLowerBound() == 0.0) { lowerBoundVal = SMALL_LOG_VALUE; } } else if (getRange().getLowerBound() < 0.0 && getRange().getUpperBound() < 0.0) { upperBoundVal = -1.0 * getRange().getLowerBound(); lowerBoundVal = -1.0 * getRange().getUpperBound(); NEGATIVE = true; } //get log10 version of upper bound and round to integer: final int iEndCount = (int) Math.floor(Math.log10(upperBoundVal)); //get log10 version of lower bound and round to integer: int iBegCount; if (lowerBoundVal == SMALL_LOG_VALUE) { iBegCount = iEndCount - 3; } else { iBegCount = (int) Math.floor(Math.log10(lowerBoundVal)); } String tickLabel; for (int i = iBegCount; i <= iEndCount; i++) { int jEndCount = 9; if (i == iEndCount) { if (iEndCount == 0) { jEndCount = (int) Math.abs(Math.floor(upperBoundVal)); } else { jEndCount = (int) (upperBoundVal / Math.pow(10.0, iEndCount)); } } for (int j = 0; j < jEndCount; j++) { final boolean displayTickLabel = (j == 0) || (iEndCount - iBegCount < 2); double tickVal = Math.pow(10, i) + (Math.pow(10, i) * j); if (NEGATIVE) { tickVal *= -1.0; } if (displayTickLabel) { //create label for tick: tickLabel = NumberFormat.getNumberInstance().format(tickVal); } else { //no label tickLabel = ""; } if (tickValInRange(lowerBoundVal, upperBoundVal, tickVal, NEGATIVE)) { switch (mode) { case VERTICAL: if (NEGATIVE) { addVerticalTicks(edge, ticks, -upperBoundVal, tickLabel, tickVal); } else { addVerticalTicks(edge, ticks, lowerBoundVal, tickLabel, tickVal); } break; case HORIZONTAL: if (NEGATIVE) { addHorizontalTicks(edge, ticks, -upperBoundVal, tickLabel, tickVal); } else { addHorizontalTicks(edge, ticks, lowerBoundVal, tickLabel, tickVal); } break; default: throw new IllegalStateException("Illegal axis orientation - cannot add ticks"); } } } } return ticks; } private boolean tickValInRange(double lowerBoundVal, double upperBoundVal, double tickVal, boolean negative) { if (negative) { return (-upperBoundVal <= tickVal && -lowerBoundVal >= tickVal); } else { return (lowerBoundVal <= tickVal && upperBoundVal >= tickVal); } } private void addHorizontalTicks(RectangleEdge edge, List ticks, double lowerBoundVal, String tickLabel, double tickVal) { if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) { //tick value not below lowest data value TextAnchor anchor; TextAnchor rotationAnchor; double angle = 0.0; if (isVerticalTickLabels()) { anchor = TextAnchor.CENTER_RIGHT; rotationAnchor = TextAnchor.CENTER_RIGHT; if (edge == RectangleEdge.TOP) { angle = Math.PI / 2.0; } else { angle = -Math.PI / 2.0; } } else { if (edge == RectangleEdge.TOP) { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; } else { anchor = TextAnchor.TOP_CENTER; rotationAnchor = TextAnchor.TOP_CENTER; } } ticks.add(new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle)); } } private void addVerticalTicks(RectangleEdge edge, List ticks, double lowerBoundVal, String tickLabel, double tickVal) { if (tickVal >= lowerBoundVal - SMALL_LOG_VALUE) { //tick value not below lowest data value TextAnchor anchor; TextAnchor rotationAnchor; double angle = 0.0; if (isVerticalTickLabels()) { if (edge == RectangleEdge.LEFT) { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; angle = -Math.PI / 2.0; } else { anchor = TextAnchor.BOTTOM_CENTER; rotationAnchor = TextAnchor.BOTTOM_CENTER; angle = Math.PI / 2.0; } } else { if (edge == RectangleEdge.LEFT) { anchor = TextAnchor.CENTER_RIGHT; rotationAnchor = TextAnchor.CENTER_RIGHT; } else { anchor = TextAnchor.CENTER_LEFT; rotationAnchor = TextAnchor.CENTER_LEFT; } } //create tick object and add to list: ticks.add(new NumberTick(new Double(tickVal), tickLabel, anchor, rotationAnchor, angle)); } } }
7,261
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ScatterPlotTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ScatterPlotTableModel.java
package org.esa.snap.rcp.statistics; import org.esa.snap.ui.io.CsvEncoder; import org.esa.snap.ui.io.TableModelCsvEncoder; import org.opengis.feature.Property; import javax.swing.table.AbstractTableModel; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Sabine Embacher */ class ScatterPlotTableModel extends AbstractTableModel implements CsvEncoder { private final static String REF_SUFFIX = "_ref"; private final List<String> colNames; private final Map<Integer, Integer> propertyIndices; private final ScatterPlotPanel.ComputedData[] computedDatas; public ScatterPlotTableModel(String rasterName, String correlativDataName, ScatterPlotPanel.ComputedData[] computedDatas) { this.computedDatas = computedDatas; colNames = new ArrayList<>(); colNames.add("pixel_no"); colNames.add("pixel_x"); colNames.add("pixel_y"); colNames.add("latitude"); colNames.add("longitude"); colNames.add(rasterName + "_mean"); colNames.add(rasterName + "_sigma"); colNames.add(correlativDataName + REF_SUFFIX); final int colStart = 8; propertyIndices = new HashMap<>(); int validPropertyCount = 0; final Collection<Property> props = computedDatas[0].featureProperties; final Property[] properties = props.toArray(new Property[props.size()]); for (int i = 0; i < properties.length; i++) { final String name = properties[i].getName().toString(); if (!correlativDataName.equals(name)) { colNames.add(name + REF_SUFFIX); propertyIndices.put(colStart + validPropertyCount, i); validPropertyCount++; } } } @Override public void encodeCsv(Writer writer) throws IOException { new TableModelCsvEncoder(this).encodeCsv(writer); } @Override public int getRowCount() { return computedDatas.length; } @Override public int getColumnCount() { return colNames.size(); } @Override public String getColumnName(int column) { return colNames.get(column); } @Override public Object getValueAt(int rowIndex, int columnIndex) { if (columnIndex == 0) { return rowIndex + 1; } else if (columnIndex == 1) { return computedDatas[rowIndex].x; } else if (columnIndex == 2) { return computedDatas[rowIndex].y; } else if (columnIndex == 3) { return computedDatas[rowIndex].lat; } else if (columnIndex == 4) { return computedDatas[rowIndex].lon; } else if (columnIndex == 5) { return computedDatas[rowIndex].rasterMean; } else if (columnIndex == 6) { return computedDatas[rowIndex].rasterSigma; } else if (columnIndex == 7) { return computedDatas[rowIndex].correlativeData; } else if (columnIndex < getColumnCount()) { final Collection<Property> propColl = computedDatas[rowIndex].featureProperties; final Property[] properties = propColl.toArray(new Property[propColl.size()]); final Integer propertyIndex = propertyIndices.get(columnIndex); return properties[propertyIndex].getValue(); } return null; } public String toCVS() { StringWriter sw = new StringWriter(); try { encodeCsv(sw); sw.close(); } catch (IOException e) { throw new IllegalStateException(e); } return sw.toString(); } }
3,780
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TitledSeparator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/TitledSeparator.java
package org.esa.snap.rcp.statistics; import com.bc.ceres.swing.TableLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; /** * @author Tonio Fincke */ public class TitledSeparator extends JPanel { private final JLabel labelComponent; public TitledSeparator(String title) { final TableLayout tableLayout = new TableLayout(3); tableLayout.setTableAnchor(TableLayout.Anchor.CENTER); tableLayout.setTableWeightY(0.0); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTablePadding(2, 0); tableLayout.setColumnWeightX(0, 1.0); tableLayout.setColumnWeightX(1, 0.0); tableLayout.setColumnWeightX(2, 1.0); setLayout(tableLayout); add(new JSeparator()); labelComponent = new JLabel(title); add(labelComponent); add(new JSeparator()); } JLabel getLabelComponent() { return labelComponent; } }
984
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StatisticChartStyling.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/StatisticChartStyling.java
package org.esa.snap.rcp.statistics; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.VectorDataNode; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.opengis.feature.type.AttributeDescriptor; import java.awt.Color; import java.awt.Paint; import java.awt.Shape; import java.awt.geom.Ellipse2D; class StatisticChartStyling { static final Paint CORRELATIVE_POINT_PAINT = new Color(200, 0, 0); static final Paint CORRELATIVE_POINT_OUTLINE_PAINT = CORRELATIVE_POINT_PAINT; static final Paint CORRELATIVE_POINT_FILL_PAINT = new Color(255, 150, 150); static final Shape CORRELATIVE_POINT_SHAPE = new Ellipse2D.Float(-4, -4, 8, 8); static final boolean CORRELATIVE_POINT_SHAPES_FILLED = true; static final Paint SAMPLE_DATA_PAINT = new Color(0, 0, 200); static final Paint SAMPLE_DATA_FILL_PAINT = new Color(150, 150, 255); static final Shape SAMPLE_DATA_POINT_SHAPE = new Ellipse2D.Float(-4, -4, 8, 8); static final Paint REGRESSION_DATA_PAINT = new Color(0, 190, 60); static final Paint REGRESSION_DATA_FILL_PAINT = new Color(0, 190, 60, 80); static ValueAxis updateScalingOfAxis(boolean logScaled, ValueAxis oldAxis, final boolean autoRangeIncludesZero) { ValueAxis newAxis = oldAxis; if (logScaled) { if (!(oldAxis instanceof CustomLogarithmicAxis)) { final CustomLogarithmicAxis logarithmicAxis = createLogarithmicAxis(oldAxis.getLabel()); logarithmicAxis.setAutoRange(oldAxis.isAutoRange()); newAxis = logarithmicAxis; } } else { if (oldAxis instanceof CustomLogarithmicAxis) { final NumberAxis numberAxis = createNumberAxis(oldAxis.getLabel(), autoRangeIncludesZero); numberAxis.setAutoRange(oldAxis.isAutoRange()); newAxis = numberAxis; } } newAxis.setLabelFont(oldAxis.getLabelFont()); newAxis.setLabelPaint(oldAxis.getLabelPaint()); newAxis.setTickLabelFont(oldAxis.getTickLabelFont()); newAxis.setTickLabelPaint(oldAxis.getTickLabelPaint()); return newAxis; } static NumberAxis createNumberAxis(String label, boolean autoRangeIncludesZero) { final NumberAxis numberAxis = new NumberAxis(label); numberAxis.setAutoRangeIncludesZero(autoRangeIncludesZero); return numberAxis; } static CustomLogarithmicAxis createLogarithmicAxis(String label) { CustomLogarithmicAxis logAxis = new CustomLogarithmicAxis(label); logAxis.setAllowNegativesFlag(false); logAxis.setLog10TickLabelsFlag(true); logAxis.setMinorTickCount(10); return logAxis; } // todo - Check how we can draw an axis label that uses a sub-scripted "10" in "log10". (ts, nf) public static String getAxisLabel(RasterDataNode raster, String defaultVariableName, boolean log10Scaled) { if (raster != null) { if (log10Scaled) { return "log10 of " + raster.getName(); } final String unit = raster.getUnit(); if (unit != null && !unit.isEmpty()) { return raster.getName() + " in " + unit; } return raster.getName(); } else { if (log10Scaled) { return "log10 of " + defaultVariableName; } else { return defaultVariableName; } } } private static String getAxisLabel0(boolean logScaled, RasterDataNode raster) { if (logScaled) { return "log10(" + raster.getName() + ")"; } final String unit = raster.getUnit(); if (unit != null && !unit.isEmpty()) { return raster.getName() + " (" + unit + ")"; } return raster.getName(); } public static String getCorrelativeDataLabel(VectorDataNode pointDataSource, AttributeDescriptor dataField1) { final String vdsName = pointDataSource.getName(); final String dataFieldName = dataField1.getLocalName(); return vdsName + "/" + dataFieldName; } }
4,188
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ScatterPlotTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ScatterPlotTopComponent.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.statistics; import org.esa.snap.ui.UIUtils; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.Icon; @TopComponent.Description( preferredID = "ScatterPlotTopComponent", iconBase = "org/esa/snap/rcp/icons/ScatterPlot.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "CorrelativePlot", openAtStartup = false, position = 5 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.ScatterPlotTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Analysis",position = 10), @ActionReference(path = "Toolbars/Analysis") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_ScatterPlotTopComponent_Name", preferredID = "ScatterPlotTopComponent" ) @NbBundle.Messages({ "CTL_ScatterPlotTopComponent_Name=Correlative Plot", "CTL_ScatterPlotTopComponent_HelpId=correlativePlotDialog" }) /** * The tool view containing a scatter plot * * @author Marco Zuehlke */ public class ScatterPlotTopComponent extends AbstractStatisticsTopComponent { @Override protected PagePanel createPagePanel() { final Icon largeIcon = UIUtils.loadImageIcon("icons/ScatterPlot24.gif"); final String chartTitle = ScatterPlotPanel.CHART_TITLE; final ScatterPlotPanel scatterPlotPanel = new ScatterPlotPanel(this, Bundle.CTL_ScatterPlotTopComponent_HelpId()); final TableViewPagePanel tableViewPanel = new TableViewPagePanel(this, Bundle.CTL_ScatterPlotTopComponent_HelpId(), chartTitle, largeIcon); scatterPlotPanel.setAlternativeView(tableViewPanel); tableViewPanel.setAlternativeView(scatterPlotPanel); return scatterPlotPanel; } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_ScatterPlotTopComponent_HelpId()); } }
2,822
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
InformationPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/InformationPanel.java
/* * Copyright (C) 2011 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.statistics; import org.esa.snap.core.dataio.ProductReader; import org.esa.snap.core.dataio.ProductReaderPlugIn; import org.esa.snap.core.datamodel.AbstractBand; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.ConvolutionFilterBand; import org.esa.snap.core.datamodel.FilterBand; import org.esa.snap.core.datamodel.GeneralFilterBand; import org.esa.snap.core.datamodel.Kernel; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.core.datamodel.VirtualBand; import org.esa.snap.core.util.ModuleMetadata; import org.esa.snap.core.util.StringUtils; import org.esa.snap.core.util.SystemUtils; import org.openide.windows.TopComponent; import javax.swing.JScrollPane; import javax.swing.JTable; import java.awt.Dimension; import java.util.Arrays; import java.util.List; /** * @author Thomas Storm * @author Sabine Embacher */ class InformationPanel extends TablePagePanel { private static final String DEFAULT_INFORMATION_TEXT = "No information available."; private static final String TITLE_PREFIX = "Information"; private static final String NO_PRODUCT_READER_MESSAGE = "No product reader set"; private static final int index_of_name_column = 0; private static final int index_of_value_and_unit_column = 1; private InformationTableModel tableModel; private int widthOfNameColumn = -1; private int widthOfValueAndUnitColumn = -1; InformationPanel(TopComponent parentComponent, String helpId) { super(parentComponent, helpId, TITLE_PREFIX, DEFAULT_INFORMATION_TEXT); } @Override protected void initComponents() { tableModel = new InformationTableModel(); getTable().setModel(tableModel); getTable().setTableHeader(null); getTable().addMouseListener(new PopupHandler()); getTable().setShowGrid(false); getTable().setRowSelectionAllowed(false); getTable().setColumnSelectionAllowed(false); getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF); add(new JScrollPane(getTable())); } @Override protected String getDataAsText() { StringBuilder builder = new StringBuilder(); final List<TableRow> rows = tableModel.rows; for (int i = 0; i < rows.size(); i++) { InformationTableRow row = (InformationTableRow) rows.get(i); builder.append(row.label) .append("\t") .append(row.value) .append(StringUtils.isNotNullAndNotEmpty(row.unit) ? "\t" + row.unit : ""); if (i < rows.size() - 1) { builder.append("\n"); } } return builder.toString(); } @Override protected void updateComponents() { tableModel.clear(); widthOfNameColumn = -1; widthOfValueAndUnitColumn = -1; if (getRaster() instanceof AbstractBand) { final Band band = (Band) getRaster(); addEntry("Name:", band.getName(), ""); addEntry("Type:", "Band", ""); addEntry("Description:", band.getDescription(), ""); addEntry("Geophysical unit:", band.getUnit(), ""); addEntry("Geophysical data type:", ProductData.getTypeString(band.getGeophysicalDataType()), ""); addEntry("Raw data type:", ProductData.getTypeString(band.getDataType()), ""); addEntry("Raster width:", String.valueOf(band.getRasterWidth()), "pixels"); addEntry("Raster height:", String.valueOf(band.getRasterHeight()), "pixels"); addEntry("Scaling factor:", String.valueOf(band.getScalingFactor()), ""); addEntry("Scaling offset:", String.valueOf(band.getScalingOffset()), ""); addEntry("Is log 10 scaled:", String.valueOf(band.isLog10Scaled()), ""); addEntry("Is no-data value used:", String.valueOf(band.isNoDataValueUsed()), ""); addEntry("No-data value:", String.valueOf(band.getNoDataValue()), ""); addEntry("Geophysical no-data value:", String.valueOf(band.getGeophysicalNoDataValue()), ""); addEntry("Valid pixel expression:", String.valueOf(band.getValidPixelExpression()), ""); addEntry("Spectral band index:", String.valueOf(band.getSpectralBandIndex()), ""); addEntry("Wavelength:", String.valueOf(band.getSpectralWavelength()), "nm"); addEntry("Bandwidth:", String.valueOf(band.getSpectralBandwidth()), "nm"); addEntry("Solar flux:", String.valueOf(band.getSolarFlux()), "mW/(m^2*nm)"); if (band instanceof FilterBand) { addEmptyLine(); addEntry("FilterBand:", band.getClass().getTypeName(), ""); final FilterBand fb = (FilterBand) band; addEntry("Source band name:", fb.getSource().getName(), ""); Kernel kernel = null; if (band instanceof ConvolutionFilterBand) { final ConvolutionFilterBand cfb = (ConvolutionFilterBand) band; addEntry("Iteration count:", "" + cfb.getIterationCount(), ""); kernel = cfb.getKernel(); } else if (band instanceof GeneralFilterBand) { final GeneralFilterBand gfb = (GeneralFilterBand) band; addEntry("Iteration count:", "" + gfb.getIterationCount(), ""); addEntry("Op type:", "" + gfb.getOpType(), ""); kernel = gfb.getStructuringElement(); } if (kernel != null) { addEntry("Kernel width:", "" + kernel.getWidth(), ""); addEntry("Kernel height:", "" + kernel.getHeight(), ""); addEntry("Kernel xOrigin:", "" + kernel.getXOrigin(), ""); addEntry("Kernel yOrigin:", "" + kernel.getYOrigin(), ""); addEntry("Kernel factor:", "" + kernel.getFactor(), ""); addEntry("Kernel data:", Arrays.toString( kernel.getKernelData(null)), ""); } } if (band instanceof VirtualBand) { final VirtualBand vb = (VirtualBand) band; addEntry("VirtualBand Expression:", vb.getExpression(), ""); } } else if (getRaster() instanceof TiePointGrid) { final TiePointGrid grid = (TiePointGrid) getRaster(); addEntry("Name:", grid.getName(), ""); addEntry("Type:", "Tie Point Grid", ""); addEntry("Description:", grid.getDescription(), ""); addEntry("Geophysical unit:", grid.getUnit(), ""); addEntry("Geophysical data type:", ProductData.getTypeString(grid.getGeophysicalDataType()), ""); addEntry("Grid width:", String.valueOf(grid.getGridWidth()), "tie points"); addEntry("Grid height:", String.valueOf(grid.getGridHeight()), "tie points"); addEntry("Offset X:", String.valueOf(grid.getOffsetX()), "pixels"); addEntry("Offset Y:", String.valueOf(grid.getOffsetY()), "pixels"); addEntry("Sub-sampling X:", String.valueOf(grid.getSubSamplingX()), "pixels"); addEntry("Sub-sampling Y:", String.valueOf(grid.getSubSamplingY()), "pixels"); addEntry("Raster width:", String.valueOf(grid.getRasterWidth()), "pixels"); addEntry("Raster height:", String.valueOf(grid.getRasterHeight()), "pixels"); } final Product product = getProduct(); if (product == null) { showNoInformationAvailableMessage(); return; } if (tableModel.getRowCount() > 0) { addEmptyLine(); } addEntry("Product name:", product.getName(), ""); addEntry("Product type:", product.getProductType(), ""); addEntry("Product description:", product.getDescription(), ""); final String productFormatName = getProductFormatName(product); final String productFormatNameString = productFormatName != null ? productFormatName : "unknown"; addEntry("Product format:", productFormatNameString, ""); addEntry("Product reader:", getProductReaderDescription(product), ""); addEntry("Product reader class:", getProductReaderClass(product), ""); addEntry("Product reader module:", getProductReaderModule(product), ""); addEntry("Product file location:", product.getFileLocation() != null ? product.getFileLocation().getPath() : "Not yet saved", ""); addEntry("Product scene width:", String.valueOf(product.getSceneRasterWidth()), "pixels"); addEntry("Product scene height:", String.valueOf(product.getSceneRasterHeight()), "pixels"); Dimension preferredTileSize = product.getPreferredTileSize(); if (preferredTileSize != null) { addEntry("Product preferred tile width:", String.valueOf((int) preferredTileSize.getWidth()), "pixels"); addEntry("Product preferred tile height:", String.valueOf((int) preferredTileSize.getHeight()), "pixels"); } final String startTimeString = product.getStartTime() != null ? product.getStartTime().getElemString() : "Not available"; addEntry("Product start time (UTC):", startTimeString, ""); final String stopTimeString = product.getEndTime() != null ? product.getEndTime().getElemString() : "Not available"; addEntry("Product end time (UTC):", stopTimeString, ""); ensureTableModel(); } private void ensureTableModel() { if (getTable().getModel() != tableModel) { getTable().setModel(tableModel); getTable().setAutoResizeMode(JTable.AUTO_RESIZE_OFF); } getTable().getColumnModel().getColumn(index_of_name_column).setPreferredWidth(widthOfNameColumn); getTable().getColumnModel().getColumn(index_of_name_column).setMinWidth(widthOfNameColumn); getTable().getColumnModel().getColumn(index_of_name_column).setMaxWidth(widthOfNameColumn); getTable().getColumnModel().getColumn(index_of_value_and_unit_column).setPreferredWidth(widthOfValueAndUnitColumn); getTable().getColumnModel().getColumn(index_of_value_and_unit_column).setMinWidth(widthOfValueAndUnitColumn); getTable().getColumnModel().getColumn(index_of_value_and_unit_column).setMaxWidth(widthOfValueAndUnitColumn); setColumnRenderer(0, RendererFactory.createRenderer(RendererFactory.ALTERNATING_ROWS)); setColumnRenderer(1, RendererFactory.createRenderer(RendererFactory.ALTERNATING_ROWS | RendererFactory.TOOLTIP_AWARE)); } private void addEmptyLine() { addEntry("", "", ""); } private void addEntry(final String label, final String value, final String unit) { String formattedLabel = String.format("%1$-30s \t", label); widthOfNameColumn = Math.max(widthOfNameColumn, getFontMetrics(getFont()).stringWidth(formattedLabel) + 10); widthOfValueAndUnitColumn = Math.max(widthOfValueAndUnitColumn, getFontMetrics(getFont()).stringWidth( value + (StringUtils.isNotNullAndNotEmpty(unit) ? " " + unit : "")) + 10); TableRow row = new InformationTableRow(formattedLabel, value, unit); tableModel.addRow(row); } private static String getProductReaderDescription(final Product product) { final ProductReader productReader = product.getProductReader(); if (productReader != null) { final ProductReaderPlugIn readerPlugIn = productReader.getReaderPlugIn(); if (readerPlugIn != null) { String description = readerPlugIn.getDescription(null); if (description != null) { return description; } } } return NO_PRODUCT_READER_MESSAGE; } private static String getProductReaderClass(final Product product) { final ProductReader productReader = product.getProductReader(); if (productReader != null) { final ProductReaderPlugIn readerPlugIn = productReader.getReaderPlugIn(); if (readerPlugIn != null) { return readerPlugIn.getClass().getName(); } } return NO_PRODUCT_READER_MESSAGE; } private static String getProductReaderModule(final Product product) { final ProductReader productReader = product.getProductReader(); if (productReader != null) { ModuleMetadata moduleMetadata = SystemUtils.loadModuleMetadata(productReader.getClass()); if (moduleMetadata != null) { return String.format("%s - v%s", moduleMetadata.getDisplayName(), moduleMetadata.getVersion()); } return "unknown"; } return NO_PRODUCT_READER_MESSAGE; } private static String getProductFormatName(final Product product) { final ProductReader productReader = product.getProductReader(); if (productReader == null) { return null; } final ProductReaderPlugIn readerPlugIn = productReader.getReaderPlugIn(); if (readerPlugIn != null) { return getProductFormatName(readerPlugIn); } return null; } // todo - make this a method in ProductReader and ProductWriter private static String getProductFormatName(final ProductReaderPlugIn readerPlugIn) { final String[] formatNames = readerPlugIn.getFormatNames(); if (formatNames != null && formatNames.length > 0) { return formatNames[0]; } return null; } static class InformationTableRow implements TablePagePanel.TableRow { String label; String value; String unit; public InformationTableRow(String label, String value, String unit) { this.label = label; this.value = value; this.unit = unit; } } private static class InformationTableModel extends TablePagePanelModel { @Override public int getColumnCount() { return 2; } @Override public String getColumnName(int columnIndex) { switch (columnIndex) { case index_of_name_column: return "Name"; case index_of_value_and_unit_column: return "Value and Unit"; } throw new IllegalStateException("Should never come here"); } @Override public Object getValueAt(int rowIndex, int columnIndex) { TableRow row = rows.get(rowIndex); if (!(row instanceof InformationTableRow)) { return row.toString(); } InformationTableRow tableRow = (InformationTableRow) row; switch (columnIndex) { case index_of_name_column: return tableRow.label; case index_of_value_and_unit_column: return tableRow.value + (StringUtils.isNotNullAndNotEmpty(tableRow.unit) ? " " + tableRow.unit : ""); } throw new IllegalStateException("Invalid index: row=" + rowIndex + "; column=" + columnIndex); } } }
16,180
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CorrelativeFieldSelector.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/CorrelativeFieldSelector.java
package org.esa.snap.rcp.statistics; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.core.Assert; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.VectorDataNode; import org.geotools.feature.NameImpl; import org.opengis.feature.type.AttributeDescriptor; import org.opengis.feature.type.AttributeType; import org.opengis.feature.type.GeometryDescriptor; import org.opengis.feature.type.Name; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import java.awt.Component; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * @author Norman Fomferra */ class CorrelativeFieldSelector { final JLabel pointDataSourceLabel; final JComboBox pointDataSourceList; final JLabel dataFieldLabel; final JComboBox dataFieldList; final Property pointDataSourceProperty; final Property dataFieldProperty; final static String NULL_NAME = " "; CorrelativeFieldSelector(BindingContext bindingContext) { Assert.argument(bindingContext.getPropertySet().getProperty("pointDataSource") != null, "bindingContext"); Assert.argument(bindingContext.getPropertySet().getProperty("dataField") != null, "bindingContext"); Assert.argument(bindingContext.getPropertySet().getProperty("pointDataSource").getType().equals(VectorDataNode.class), "bindingContext"); Assert.argument(bindingContext.getPropertySet().getProperty("dataField").getType().equals(AttributeDescriptor.class), "bindingContext"); pointDataSourceLabel = new JLabel("Point data source:"); pointDataSourceList = new JComboBox(); dataFieldLabel = new JLabel("Data field:"); dataFieldList = new JComboBox(); pointDataSourceList.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { this.setText(((VectorDataNode) value).getName()); } return this; } }); dataFieldList.setRenderer(new DefaultListCellRenderer() { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value != null) { this.setText(((AttributeDescriptor) value).getName().getLocalPart()); } return this; } }); bindingContext.bind("pointDataSource", pointDataSourceList); pointDataSourceProperty = bindingContext.getPropertySet().getProperty("pointDataSource"); dataFieldProperty = bindingContext.getPropertySet().getProperty("dataField"); pointDataSourceProperty.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { updateDataField(); } }); bindingContext.getBinding("pointDataSource").addComponent(pointDataSourceLabel); bindingContext.bind("dataField", dataFieldList); bindingContext.getBinding("dataField").addComponent(dataFieldLabel); } public void updatePointDataSource(Product product) { if (product != null) { final Class pointClass = org.locationtech.jts.geom.Point.class; final ProductNodeGroup<VectorDataNode> vectorDataGroup = product.getVectorDataGroup(); final List<VectorDataNode> vectorDataNodes = new ArrayList<VectorDataNode>(); for (VectorDataNode vectorDataNode : vectorDataGroup.toArray(new VectorDataNode[vectorDataGroup.getNodeCount()])) { final GeometryDescriptor geometryDescriptor = vectorDataNode.getFeatureType().getGeometryDescriptor(); if (geometryDescriptor != null && pointClass.isAssignableFrom(geometryDescriptor.getType().getBinding())) { vectorDataNodes.add(vectorDataNode); } } final ValueSet valueSet = new ValueSet(vectorDataNodes.toArray()); pointDataSourceProperty.getDescriptor().setValueSet(valueSet); } else { pointDataSourceProperty.getDescriptor().setValueSet(null); dataFieldProperty.getDescriptor().setValueSet(null); try { pointDataSourceProperty.setValue(null); dataFieldProperty.setValue(null); } catch (ValidationException ignore) { } } } public void updateDataField() { if (pointDataSourceProperty.getValue() != null) { final List<AttributeDescriptor> attributeDescriptors = ((VectorDataNode) pointDataSourceProperty.getValue()).getFeatureType().getAttributeDescriptors(); final List<AttributeDescriptor> result = new ArrayList<AttributeDescriptor>(); result.add(new NullAttributeDescriptor()); for (AttributeDescriptor attributeDescriptor : attributeDescriptors) { if (Number.class.isAssignableFrom(attributeDescriptor.getType().getBinding())) { result.add(attributeDescriptor); } } dataFieldProperty.getDescriptor().setValueSet(new ValueSet(result.toArray())); } else { dataFieldProperty.getDescriptor().setValueSet(null); try { dataFieldProperty.setValue(null); } catch (ValidationException ignore) { } } } public void tryToSelectPointDataSource(VectorDataNode pointDataSource) { pointDataSourceList.setSelectedItem(pointDataSource); } public void tryToSelectDataField(AttributeDescriptor dataField) { dataFieldList.setSelectedItem(dataField); } private class NullAttributeDescriptor implements AttributeDescriptor { @Override public AttributeType getType() { return null; } @Override public String getLocalName() { return NULL_NAME; } @Override public Object getDefaultValue() { return null; } @Override public Name getName() { return new NameImpl(NULL_NAME); } @Override public int getMinOccurs() { return 0; } @Override public int getMaxOccurs() { return 0; } @Override public boolean isNillable() { return true; } @Override public Map<Object, Object> getUserData() { return null; } } }
7,284
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AxisRangeControl.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/AxisRangeControl.java
package org.esa.snap.rcp.statistics; 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.swing.binding.BindingContext; import org.esa.snap.core.util.math.MathUtils; import org.esa.snap.ui.GridBagUtils; import org.jfree.chart.axis.ValueAxis; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.GridBagConstraints; /** * @author Norman Fomferra */ public class AxisRangeControl { public final static String PROPERTY_NAME_AUTO_MIN_MAX = "autoMinMax"; public final static String PROPERTY_NAME_MIN = "min"; public final static String PROPERTY_NAME_MAX = "max"; private final BindingContext bindingContext; private final String axisName; private JPanel panel; private TitledSeparator titledSeparator; public AxisRangeControl(String axisName) { this.axisName = axisName; PropertySet propertyContainer = PropertyContainer.createObjectBacked(new Model()); bindingContext = new BindingContext(propertyContainer); } public JPanel getPanel() { if (panel == null) { panel = createPanel(); panel.setName(axisName); } return panel; } private JPanel createPanel() { final JCheckBox autoMinMaxBox = new JCheckBox("Auto min/max"); final JLabel minLabel = new JLabel("Min:"); final JLabel maxLabel = new JLabel("Max:"); final JTextField minTextField = new JTextField(); final JTextField maxTextField = new JTextField(); final JPanel panel = GridBagUtils.createPanel(); final GridBagConstraints gbc = GridBagUtils.createConstraints("anchor=WEST,fill=HORIZONTAL"); GridBagUtils.setAttributes(gbc, "gridwidth=2,insets.top=2,weightx=1"); titledSeparator = new TitledSeparator(axisName); GridBagUtils.addToPanel(panel, titledSeparator, gbc, "gridy=0,insets.right=-2"); GridBagUtils.addToPanel(panel, autoMinMaxBox, gbc, "gridy=1"); GridBagUtils.setAttributes(gbc, "gridwidth=1"); GridBagUtils.addToPanel(panel, minLabel, gbc, "insets.left=22,gridx=0,gridy=2,weightx=0"); GridBagUtils.addToPanel(panel, minTextField, gbc, "insets=2,gridx=1,gridy=2,weightx=1"); GridBagUtils.addToPanel(panel, maxLabel, gbc, "insets.left=22,gridx=0,gridy=3,weightx=0"); GridBagUtils.addToPanel(panel, maxTextField, gbc, "insets=2,gridx=1,gridy=3,weightx=1"); bindingContext.bind("autoMinMax", autoMinMaxBox); bindingContext.bind("min", minTextField); bindingContext.bind("max", maxTextField); bindingContext.getPropertySet().getDescriptor("min").setDescription("Minimum display value for " + axisName); bindingContext.getPropertySet().getDescriptor("max").setDescription("Maximum display value for " + axisName); bindingContext.getPropertySet().getDescriptor("min").setValidator(new Validator() { @Override public void validateValue(Property property, Object value) throws ValidationException { final Double max = bindingContext.getPropertySet().getValue("max"); if ((Double) value >= max) { throw new ValidationException("min value has to be less than " + max); } } }); bindingContext.getPropertySet().getDescriptor("max").setValidator(new Validator() { @Override public void validateValue(Property property, Object value) throws ValidationException { final Double min = bindingContext.getPropertySet().getValue("min"); if ((Double) value <= min) { throw new ValidationException("max value has to be greater than " + min); } } }); bindingContext.getBinding("min").addComponent(minLabel); bindingContext.getBinding("max").addComponent(maxLabel); bindingContext.bindEnabledState("min", true, "autoMinMax", false); bindingContext.bindEnabledState("max", true, "autoMinMax", false); return panel; } void addValidators() { } public void setTitleSuffix(String suffix) { final JLabel label = titledSeparator.getLabelComponent(); if (suffix == null || suffix.trim().length() == 0) { label.setText(axisName); } else { label.setText(axisName + " (" + suffix.trim() + ")"); } titledSeparator.repaint(); } public BindingContext getBindingContext() { return bindingContext; } public void setComponentsEnabled(boolean enabled) { if (!enabled) { for (Property property : bindingContext.getPropertySet().getProperties()) { bindingContext.setComponentsEnabled(property.getName(), enabled); } } else { for (Property property : bindingContext.getPropertySet().getProperties()) { if (property.getName().equals("min") || property.getName().equals("max")) { bindingContext.setComponentsEnabled(property.getName(), !isAutoMinMax()); } else { bindingContext.setComponentsEnabled(property.getName(), enabled); } } } } public boolean isAutoMinMax() { return (Boolean) bindingContext.getBinding("autoMinMax").getPropertyValue(); } public void adjustComponents(ValueAxis axis, int numDecimalPlaces) { adjustComponents(axis.getLowerBound(), axis.getUpperBound(), numDecimalPlaces); } public void adjustComponents(double min, double max, int numDecimalPlaces) { final Double oldMax = getMax(); double newMax = MathUtils.round(max, roundFactor(numDecimalPlaces)); double newMin = MathUtils.round(min, roundFactor(numDecimalPlaces)); if(newMin == newMax) { newMax += Math.pow(10, -numDecimalPlaces); } if (newMin >= oldMax) { setMax(newMax); setMin(newMin); } else { setMin(newMin); setMax(newMax); } } public void adjustAxis(ValueAxis axis, int numDecimalPlaces) { final double lowerRange = MathUtils.round((Double) getBindingContext().getBinding("min").getPropertyValue(), roundFactor(numDecimalPlaces)); final double upperRange = MathUtils.round((Double) getBindingContext().getBinding("max").getPropertyValue(), roundFactor(numDecimalPlaces)); axis.setRange(lowerRange, upperRange); } private double roundFactor(int n) { return Math.pow(10.0, n); } public Double getMin() { return (Double) getBindingContext().getPropertySet().getValue("min"); } public Double getMax() { return (Double) getBindingContext().getPropertySet().getValue("max"); } private void setMin(double min) { getBindingContext().getPropertySet().setValue("min", min); } private void setMax(double max) { getBindingContext().getPropertySet().setValue("max", max); } private static class Model { private boolean autoMinMax = true; private double min = 0.0; private double max = 100.0; } }
7,447
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
XYPlotMarker.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/XYPlotMarker.java
package org.esa.snap.rcp.statistics; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.panel.AbstractOverlay; import org.jfree.chart.panel.Overlay; import org.jfree.chart.plot.Plot; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.ui.RectangleEdge; import org.jfree.data.xy.XYDataset; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.Stroke; import java.awt.geom.Ellipse2D; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; /** * @author Norman Fomferra */ public class XYPlotMarker implements ChartMouseListener { private final ChartPanel chartPanel; private final Listener listener; private XYDataset xyDataset; private int seriesIndex; private ShapeOverlay overlay; private Paint fillPaint; private Paint outlinePaint; private Stroke outlineStroke; private double markerSize; public XYPlotMarker(ChartPanel chartPanel, Listener listener) { this.chartPanel = chartPanel; this.listener = listener; fillPaint = new Color(255, 255, 255, 127); outlinePaint = new Color(50, 50, 50, 200); outlineStroke = new BasicStroke(1.5F); markerSize = 20; } public double getMarkerSize() { return markerSize; } public void setMarkerSize(double markerSize) { this.markerSize = markerSize; } public Paint getFillPaint() { return fillPaint; } public void setFillPaint(Paint fillPaint) { this.fillPaint = fillPaint; } public Paint getOutlinePaint() { return outlinePaint; } public void setOutlinePaint(Paint outlinePaint) { this.outlinePaint = outlinePaint; } public void setInvisible() { removeDataset(); removeOverlay(); } private void removeDataset() { xyDataset = null; seriesIndex = -1; } @Override public void chartMouseClicked(ChartMouseEvent event) { removeDataset(); final boolean overlayRemoved = removeOverlay(); if (overlayRemoved) { listener.pointDeselected(); return; } XYPlot plot = chartPanel.getChart().getXYPlot(); Rectangle2D dataArea = chartPanel.getScreenDataArea(); Point point = event.getTrigger().getPoint(); if (dataArea.contains(point)) { PlotOrientation orientation = plot.getOrientation(); RectangleEdge domainEdge = Plot.resolveDomainAxisLocation( plot.getDomainAxisLocation(), orientation); RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation( plot.getRangeAxisLocation(), orientation); double mx = plot.getDomainAxis().java2DToValue(point.x, dataArea, domainEdge); double my = plot.getRangeAxis().java2DToValue(point.y, dataArea, rangeEdge); int datasetCount = chartPanel.getChart().getXYPlot().getDatasetCount(); double minDist = Double.POSITIVE_INFINITY; for (int datasetIndex = 0; datasetIndex < datasetCount; datasetIndex++) { XYDataset xyDataset = chartPanel.getChart().getXYPlot().getDataset(datasetIndex); if (xyDataset != null) { int seriesCount = xyDataset.getSeriesCount(); for (int seriesIndex = 0; seriesIndex < seriesCount; seriesIndex++) { int itemCount = xyDataset.getItemCount(seriesIndex); for (int itemIndex = 0; itemIndex < itemCount; itemIndex++) { double x = xyDataset.getXValue(seriesIndex, itemIndex); double y = xyDataset.getYValue(seriesIndex, itemIndex); double dist = (x - mx) * (x - mx) + (y - my) * (y - my); if (dist < minDist) { minDist = dist; this.xyDataset = xyDataset; this.seriesIndex = seriesIndex; } } } } } } if (xyDataset != null) { updatePoint(event); } } @Override public void chartMouseMoved(ChartMouseEvent event) { updatePoint(event); } public interface Listener { void pointSelected(XYDataset xyDataset, int seriesIndex, Point2D dataPoint); void pointDeselected(); } private void updatePoint(ChartMouseEvent event) { if (xyDataset == null || xyDataset.getSeriesCount() == 0 // This situation appears, if the dataset has changed while the overlay is still visible || (seriesIndex < 0 || seriesIndex >= xyDataset.getSeriesCount())) { if (removeOverlay()) { // FIXME - exception here: // listener.pointDeselected(); /* Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at ProductSceneView.getRaster(ProductSceneView.java:511) at ProductSceneView.getProduct(ProductSceneView.java:468) at org.esa.snap.visat.toolviews.nav.CursorSynchronizer.removePPL(CursorSynchronizer.java:133) at org.esa.snap.visat.toolviews.nav.CursorSynchronizer.clearPsvOverlayMap(CursorSynchronizer.java:116) at org.esa.snap.visat.toolviews.nav.CursorSynchronizer.setEnabled(CursorSynchronizer.java:67) at org.esa.snap.visat.toolviews.stat.ProfilePlotPanel$3.pointDeselected(ProfilePlotPanel.java:211) */ } return; } addOverlay(); XYPlot plot = chartPanel.getChart().getXYPlot(); Rectangle2D dataArea = chartPanel.getScreenDataArea(); PlotOrientation orientation = plot.getOrientation(); RectangleEdge domainEdge = Plot.resolveDomainAxisLocation( plot.getDomainAxisLocation(), orientation); RectangleEdge rangeEdge = Plot.resolveRangeAxisLocation( plot.getRangeAxisLocation(), orientation); double xView = event.getTrigger().getPoint().x; double xData = plot.getDomainAxis().java2DToValue(xView, dataArea, domainEdge); int itemCount = xyDataset.getItemCount(seriesIndex); for (int i = 0; i < itemCount - 1; i++) { double x1 = xyDataset.getXValue(seriesIndex, i); double x2 = xyDataset.getXValue(seriesIndex, i + 1); if (xData >= x1 && xData <= x2) { double y1 = xyDataset.getYValue(seriesIndex, i); double y2 = xyDataset.getYValue(seriesIndex, i + 1); double yData = y1 + (xData - x1) * (y2 - y1) / (x2 - x1); double yView = plot.getRangeAxis().valueToJava2D(yData, dataArea, rangeEdge); Point2D.Double viewPoint = new Point2D.Double(xView, yView); Point2D.Double dataPoint = new Point2D.Double(xData, yData); overlay.setPoint(viewPoint, dataPoint); listener.pointSelected(xyDataset, seriesIndex, dataPoint); break; } } } private boolean addOverlay() { if (overlay == null) { overlay = new ShapeOverlay(); chartPanel.addOverlay(overlay); return true; } return false; } private boolean removeOverlay() { if (overlay != null) { chartPanel.removeOverlay(overlay); overlay = null; return true; } return false; } private class ShapeOverlay extends AbstractOverlay implements Overlay { Point2D viewPoint; Point2D dataPoint; public void setPoint(Point2D viewPoint, Point2D dataPoint) { if (this.viewPoint == null || !this.viewPoint.equals(dataPoint)) { this.viewPoint = viewPoint; this.dataPoint = dataPoint; fireOverlayChanged(); } } @Override public void paintOverlay(Graphics2D g2, ChartPanel chartPanel) { if (viewPoint != null) { Shape oldClip = g2.getClip(); Rectangle2D dataArea = chartPanel.getScreenDataArea(); g2.setClip(dataArea); g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); Ellipse2D.Double ellipse = new Ellipse2D.Double(viewPoint.getX() - 0.5 * markerSize, viewPoint.getY() - 0.5 * markerSize, markerSize, markerSize); g2.setPaint(fillPaint); g2.fill(ellipse); g2.setStroke(outlineStroke); g2.setPaint(outlinePaint); g2.draw(ellipse); Rectangle2D box = new Rectangle2D.Double(dataArea.getX() + 5, dataArea.getY() + 5, 100, 52); g2.setPaint(fillPaint); g2.fill(box); g2.setStroke(outlineStroke); g2.setPaint(outlinePaint); g2.draw(box); g2.drawString(String.format("x = %.3f", dataPoint.getX()), (int) (dataArea.getX() + 5 + 5), (int) (dataArea.getY() + 5 + 20)); g2.drawString(String.format("y = %.3f", dataPoint.getY()), (int) (dataArea.getX() + 5 + 5), (int) (dataArea.getY() + 5 + 40)); g2.setClip(oldClip); } } } }
9,959
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MetadataPlotSettings.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/MetadataPlotSettings.java
package org.esa.snap.rcp.statistics; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.datamodel.MetadataAttribute; import org.esa.snap.core.datamodel.MetadataElement; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author Marco Peters */ @SuppressWarnings({"unused", "FieldCanBeLocal"}) class MetadataPlotSettings { static final String FIELD_NAME_NONE = "None"; static final String FIELD_NAME_RECORD_INDEX = "Record Index"; static final String FIELD_NAME_ARRAY_FIELD_INDEX = "Array Field Index [n]"; static final String PROP_NAME_METADATA_ELEMENT = "metadataElement"; static final String PROP_NAME_RECORD_START_INDEX = "recordStartIndex"; static final String PROP_NAME_RECORDS_PER_PLOT = "recordsPerPlot"; static final String PROP_NAME_FIELD_X = "fieldX"; static final String PROP_NAME_FIELD_Y1 = "fieldY1"; static final String PROP_NAME_FIELD_Y2 = "fieldY2"; private MetadataElement metadataElement; private double recordStartIndex = 1.0; private int recordsPerPlot = 1; private String fieldX; private String fieldY1; private String fieldY2; private BindingContext context; private AtomicBoolean isSynchronising = new AtomicBoolean(false); public MetadataPlotSettings() { context = new BindingContext(PropertyContainer.createObjectBacked(this, new ParameterDescriptorFactory())); Property propertyRecordStart = context.getPropertySet().getProperty(PROP_NAME_RECORD_START_INDEX); propertyRecordStart.getDescriptor().setAttribute("stepSize", 1); Property propertyMetaElement = context.getPropertySet().getProperty(PROP_NAME_METADATA_ELEMENT); propertyMetaElement.addPropertyChangeListener(evt -> { try { if (!isSynchronising.getAndSet(true)) { PropertySet propertySet = context.getPropertySet(); // clear current settings propertySet.setValue(PROP_NAME_RECORD_START_INDEX, 1.0); propertySet.setValue(PROP_NAME_RECORDS_PER_PLOT, 1); propertySet.setValue(PROP_NAME_FIELD_X, null); propertySet.setValue(PROP_NAME_FIELD_Y1, null); propertySet.setValue(PROP_NAME_FIELD_Y2, null); List<String> usableFieldNames = retrieveUsableFieldNames(metadataElement); ArrayList<String> usableYFieldNames = new ArrayList<>(usableFieldNames); usableYFieldNames.add(0, FIELD_NAME_NONE); PropertyDescriptor propertyFieldY1 = propertySet.getProperty(PROP_NAME_FIELD_Y1).getDescriptor(); propertyFieldY1.setValueSet(new ValueSet(usableYFieldNames.toArray(new String[0]))); PropertyDescriptor propertyFieldY2 = propertySet.getProperty(PROP_NAME_FIELD_Y2).getDescriptor(); propertyFieldY2.setValueSet(new ValueSet(usableYFieldNames.toArray(new String[0]))); PropertyDescriptor propertyFieldX = propertySet.getProperty(PROP_NAME_FIELD_X).getDescriptor(); ArrayList<String> usableXFieldNames = new ArrayList<>(usableFieldNames); usableXFieldNames.add(0, FIELD_NAME_RECORD_INDEX); usableXFieldNames.add(1, FIELD_NAME_ARRAY_FIELD_INDEX); propertyFieldX.setValueSet(new ValueSet(usableXFieldNames.toArray(new String[0]))); } } finally { isSynchronising.set(false); } }); } /** * Retrieves the binding context, to be used to bind the UI elements to. */ BindingContext getContext() { return context; } /** * Returns the currently selected metadata element */ MetadataElement getMetadataElement() { return metadataElement; } /** * Name of the field to be used for the domain(X) axis. */ String getNameX() { return fieldX; } /** * Name of the field to be used for the first range(Y) axis. */ public String getNameY1() { return fieldY1; } /** * Name of the field to be used for the second range(Y) axis. */ public String getFieldY2() { return fieldY2; } void setMetadataElements(MetadataElement[] elements) { if (elements == null) { context.getPropertySet().setDefaultValues(); return; } Property property = context.getPropertySet().getProperty(PROP_NAME_METADATA_ELEMENT); property.getDescriptor().setValueSet(new ValueSet(filterElements(elements))); try { property.setValue(elements[0]); } catch (ValidationException e) { e.printStackTrace(); } } int getNumRecords() { return getNumRecords(metadataElement); } int getRecordStartIndex() { return (int) recordStartIndex; } public int getRecordsPerPlot() { return recordsPerPlot; } static List<String> retrieveUsableFieldNames(MetadataElement element) { int numRecords = getNumRecords(element); if (numRecords > 1) { return retrieveUsableFieldNames(element.getElements()[0]); } else { List<String> list = new ArrayList<>(); String[] attributeNames = element.getAttributeNames(); for (String fullAttribName : attributeNames) { String fieldName = getFieldName(fullAttribName); if (list.contains(fieldName)) { // skip over split array attributes if already added continue; } MetadataAttribute attribute = element.getAttribute(fullAttribName); if (isNumericType(attribute)) { list.add(fieldName); } } return list; } } private static String getFieldName(String fullAttribName) { String fieldName; Pattern p = Pattern.compile("(.*)\\.(\\d+)"); final Matcher m = p.matcher(fullAttribName); if (m.matches()) { fieldName = m.group(1); } else { fieldName = fullAttribName; } return fieldName; } private static boolean isNumericType(MetadataAttribute attribute) { return ProductData.isIntType(attribute.getDataType()) || ProductData.isFloatingPointType(attribute.getDataType()); } private MetadataElement[] filterElements(MetadataElement[] elements) { return elements; } private static int getNumRecords(MetadataElement metadataElement) { if (metadataElement == null) { return 1; } int numSubElements = metadataElement.getNumElements(); if (numSubElements > 0) { MetadataElement[] subElements = metadataElement.getElements(); int count = 0; for (MetadataElement subElement : subElements) { if (subElement.getName().matches(metadataElement.getName() + "\\.\\d+")) { // subelements should only have a number suffix count++; } } if (count == numSubElements) { return count; } } return 1; } }
7,828
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ChartPagePanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/ChartPagePanel.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.statistics; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.jidesoft.swing.SimpleScrollPane; import org.esa.snap.rcp.util.RoiMaskSelector; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.StandardChartTheme; import org.openide.windows.TopComponent; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JLayeredPane; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.ScrollPaneConstants; import java.awt.BorderLayout; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; /** * A common class for chart based panels * * @author Marcoz * @author Tonio */ public abstract class ChartPagePanel extends PagePanel { protected static final String HELP_TIP_MESSAGE = "For more information about this plot\n" + "hit the help button at the bottom right."; protected static final String ZOOM_TIP_MESSAGE = "TIP: To zoom within the chart, draw a rectangle\n" + "with the mouse or use the context menu."; private AbstractButton hideAndShowButton; private JPanel backgroundPanel; private RoiMaskSelector roiMaskSelector; protected AbstractButton refreshButton; private final boolean refreshButtonEnabled; static { final StandardChartTheme theme = (StandardChartTheme) ChartFactory.getChartTheme(); theme.setPlotBackgroundPaint(new Color(225, 225, 225)); } public ChartPagePanel(TopComponent parentComponent, String helpId, String titlePrefix, boolean refreshButtonEnabled) { super(parentComponent, helpId, titlePrefix); this.refreshButtonEnabled = refreshButtonEnabled; } /** * Asks the chart panel to update its chart data. This involve a (re-)computation of all datasets. */ protected abstract void updateChartData(); @Override protected void updateComponents() { if (roiMaskSelector != null) { roiMaskSelector.updateMaskSource(getProduct(), getRaster()); } refreshButton.setEnabled(refreshButtonEnabled && (getRaster() != null)); } private JPanel createTopPanel() { refreshButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/ViewRefresh22.png"), false); refreshButton.setToolTipText("Refresh View"); refreshButton.setName("refreshButton"); refreshButton.addActionListener(e -> { updateChartData(); refreshButton.setEnabled(false); }); AbstractButton switchToTableButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/Table24.png"), false); switchToTableButton.setToolTipText("Switch to Table View"); switchToTableButton.setName("switchToTableButton"); switchToTableButton.setEnabled(hasAlternativeView()); switchToTableButton.addActionListener(e -> showAlternativeView()); final TableLayout tableLayout = new TableLayout(6); tableLayout.setColumnFill(2, TableLayout.Fill.HORIZONTAL); tableLayout.setColumnWeightX(2, 1.0); tableLayout.setRowPadding(0, new Insets(0, 4, 0, 0)); JPanel buttonPanel = new JPanel(tableLayout); buttonPanel.add(refreshButton); tableLayout.setRowPadding(0, new Insets(0, 0, 0, 0)); buttonPanel.add(switchToTableButton); buttonPanel.add(new JPanel()); return buttonPanel; } private JPanel createChartBottomPanel(final ChartPanel chartPanel) { final AbstractButton zoomAllButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/view-fullscreen.png"), false); zoomAllButton.setToolTipText("Zoom all."); zoomAllButton.setName("zoomAllButton."); zoomAllButton.addActionListener(e -> { chartPanel.restoreAutoBounds(); chartPanel.repaint(); }); final AbstractButton propertiesButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/Edit24.gif"), false); propertiesButton.setToolTipText("Edit properties."); propertiesButton.setName("propertiesButton."); propertiesButton.addActionListener(e -> chartPanel.doEditChartProperties()); final AbstractButton saveButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/Export24.gif"), false); saveButton.setToolTipText("Save chart as image."); saveButton.setName("saveButton."); saveButton.addActionListener(e -> { try { chartPanel.doSaveAs(); } catch (IOException e1) { AbstractDialog.showErrorDialog(chartPanel, "Could not save chart:\n" + e1.getMessage(), "Error"); } }); final AbstractButton printButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/Print24.gif"), false); printButton.setToolTipText("Print chart."); printButton.setName("printButton."); printButton.addActionListener(e -> chartPanel.createChartPrintJob()); final TableLayout tableLayout = new TableLayout(6); tableLayout.setColumnFill(4, TableLayout.Fill.HORIZONTAL); tableLayout.setColumnWeightX(4, 1.0); JPanel buttonPanel = new JPanel(tableLayout); tableLayout.setRowPadding(0, new Insets(0, 4, 0, 0)); buttonPanel.add(zoomAllButton); tableLayout.setRowPadding(0, new Insets(0, 0, 0, 0)); buttonPanel.add(propertiesButton); buttonPanel.add(saveButton); buttonPanel.add(printButton); buttonPanel.add(new JPanel()); buttonPanel.add(getHelpButton()); return buttonPanel; } /** * @deprecated since 5.0.5, use {@link #createUI(ChartPanel, JPanel, RoiMaskSelector)} instead. */ @Deprecated protected void createUI(final ChartPanel chartPanel, final JPanel optionsPanel, BindingContext bindingContext) { createUI(chartPanel, optionsPanel, new RoiMaskSelector(bindingContext)); } /** * Responsible for creating the UI layout. * * @param chartPanel the panel of the chart * @param optionsPanel the options panel for changing settings * @param roiMaskSelector optional ROI mask selector, can be {@code null} if not wanted. */ protected void createUI(ChartPanel chartPanel, JPanel optionsPanel, RoiMaskSelector roiMaskSelector) { this.roiMaskSelector = roiMaskSelector; final JPanel extendedOptionsPanel = GridBagUtils.createPanel(); GridBagConstraints extendedOptionsPanelConstraints = GridBagUtils.createConstraints("insets.left=4,insets.right=2,anchor=NORTHWEST,fill=HORIZONTAL,insets.top=2,weightx=1"); GridBagUtils.addToPanel(extendedOptionsPanel, new JSeparator(), extendedOptionsPanelConstraints, "gridy=0"); if (this.roiMaskSelector != null) { GridBagUtils.addToPanel(extendedOptionsPanel, this.roiMaskSelector.createPanel(), extendedOptionsPanelConstraints, "gridy=1,insets.left=-4"); GridBagUtils.addToPanel(extendedOptionsPanel, new JPanel(), extendedOptionsPanelConstraints, "gridy=1,insets.left=-4"); } GridBagUtils.addToPanel(extendedOptionsPanel, optionsPanel, extendedOptionsPanelConstraints, "insets.left=0,insets.right=0,gridy=2,fill=VERTICAL,fill=HORIZONTAL,weighty=1"); GridBagUtils.addToPanel(extendedOptionsPanel, new JSeparator(), extendedOptionsPanelConstraints, "insets.left=4,insets.right=2,gridy=5,anchor=SOUTHWEST"); final SimpleScrollPane optionsScrollPane = new SimpleScrollPane(extendedOptionsPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); optionsScrollPane.setBorder(null); optionsScrollPane.getVerticalScrollBar().setUnitIncrement(20); final JPanel rightPanel = new JPanel(new BorderLayout()); rightPanel.add(createTopPanel(), BorderLayout.NORTH); rightPanel.add(optionsScrollPane, BorderLayout.CENTER); rightPanel.add(createChartBottomPanel(chartPanel), BorderLayout.SOUTH); final ImageIcon collapseIcon = UIUtils.loadImageIcon("icons/PanelRight12.png"); final ImageIcon collapseRolloverIcon = ToolButtonFactory.createRolloverIcon(collapseIcon); final ImageIcon expandIcon = UIUtils.loadImageIcon("icons/PanelLeft12.png"); final ImageIcon expandRolloverIcon = ToolButtonFactory.createRolloverIcon(expandIcon); hideAndShowButton = ToolButtonFactory.createButton(collapseIcon, false); hideAndShowButton.setToolTipText("Collapse Options Panel"); hideAndShowButton.setName("switchToChartButton"); hideAndShowButton.addActionListener(new ActionListener() { private boolean rightPanelShown; @Override public void actionPerformed(ActionEvent e) { rightPanel.setVisible(rightPanelShown); if (rightPanelShown) { hideAndShowButton.setIcon(collapseIcon); hideAndShowButton.setRolloverIcon(collapseRolloverIcon); hideAndShowButton.setToolTipText("Collapse Options Panel"); } else { hideAndShowButton.setIcon(expandIcon); hideAndShowButton.setRolloverIcon(expandRolloverIcon); hideAndShowButton.setToolTipText("Expand Options Panel"); } rightPanelShown = !rightPanelShown; } }); backgroundPanel = new JPanel(new BorderLayout()); backgroundPanel.add(chartPanel, BorderLayout.CENTER); backgroundPanel.add(rightPanel, BorderLayout.EAST); JLayeredPane layeredPane = new JLayeredPane(); layeredPane.add(backgroundPanel, new Integer(0)); layeredPane.add(hideAndShowButton, new Integer(1)); add(layeredPane); } @Override public void doLayout() { super.doLayout(); backgroundPanel.setBounds(0, 0, getWidth() - 8, getHeight() - 8); hideAndShowButton.setBounds(getWidth() - hideAndShowButton.getWidth() - 12, 2, 24, 24); } }
11,501
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MetadataPlotPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/statistics/MetadataPlotPanel.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.statistics; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.internal.SliderAdapter; import org.esa.snap.core.datamodel.MetadataAttribute; 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.ProductNodeEvent; import org.esa.snap.core.util.StringUtils; import org.esa.snap.rcp.util.RoiMaskSelector; import org.esa.snap.ui.io.TableModelCsvEncoder; import org.jfree.chart.ChartColor; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.axis.AxisLocation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.labels.StandardXYItemLabelGenerator; import org.jfree.chart.labels.StandardXYToolTipGenerator; import org.jfree.chart.plot.DefaultDrawingSupplier; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.DefaultXYItemRenderer; import org.jfree.chart.ui.RectangleInsets; import org.jfree.data.xy.DefaultXYDataset; import org.openide.windows.TopComponent; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JSlider; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import java.awt.Component; import java.awt.Font; import java.awt.Paint; import java.awt.Shape; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Hashtable; import java.util.Locale; import java.util.TimeZone; import static org.esa.snap.rcp.statistics.MetadataPlotSettings.*; /** * The metadata plot pane within the statistics window. */ class MetadataPlotPanel extends ChartPagePanel { private static final String DEFAULT_SAMPLE_DATASET_NAME = "Sample"; private static final String NO_DATA_MESSAGE = "No metadata plot computed yet.\n" + "To create a plot, select metadata elements in both combo boxes.\n" + "The plot will be computed when you click the 'Refresh View' button.\n" + HELP_TIP_MESSAGE + "\n" + ZOOM_TIP_MESSAGE; private static final String CHART_TITLE = "Metadata Plot"; private static final String DEFAULT_X_AXIS_LABEL = "x-values"; private final static Paint[] DEFAULT_PAINT_ARRAY = ChartColor.createDefaultPaintArray(); private final static Shape[] DEFAULT_SHAPE_ARRAY = DefaultDrawingSupplier.createStandardSeriesShapes(); public static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); public static final String TOOL_TIP_FORMAT = "{0}: {1}, {2}"; public static final String ITEM_LABEL_FORMAT = "{2}"; private MetadataPlotSettings plotSettings; private boolean isInitialized; private JSlider recordSlider; private SpinnerNumberModel numRecSpinnerModel; private XYPlot xyPlot; private JTextField recordValueField; MetadataPlotPanel(TopComponent parentComponent, String helpId) { super(parentComponent, helpId, CHART_TITLE, false); } @Override protected void initComponents() { if (hasAlternativeView()) { getAlternativeView().initComponents(); } JFreeChart chart = ChartFactory.createXYLineChart( CHART_TITLE, DEFAULT_X_AXIS_LABEL, DEFAULT_SAMPLE_DATASET_NAME, new DefaultXYDataset(), PlotOrientation.VERTICAL, true, true, false ); xyPlot = chart.getXYPlot(); xyPlot.setNoDataMessage(NO_DATA_MESSAGE); xyPlot.setAxisOffset(new RectangleInsets(5, 5, 5, 5)); ChartPanel profilePlotDisplay = new ChartPanel(chart); profilePlotDisplay.setInitialDelay(200); profilePlotDisplay.setDismissDelay(1500); profilePlotDisplay.setReshowDelay(200); profilePlotDisplay.setZoomTriggerDistance(5); profilePlotDisplay.getPopupMenu().addSeparator(); profilePlotDisplay.getPopupMenu().add(createCopyDataToClipboardMenuItem()); plotSettings = new MetadataPlotSettings(); final BindingContext bindingContext = plotSettings.getContext(); JPanel settingsPanel = createSettingsPanel(bindingContext); createUI(profilePlotDisplay, settingsPanel, (RoiMaskSelector) null); bindingContext.setComponentsEnabled(PROP_NAME_RECORD_START_INDEX, false); bindingContext.setComponentsEnabled(PROP_NAME_RECORDS_PER_PLOT, false); isInitialized = true; updateComponents(); updateChartData(); bindingContext.addPropertyChangeListener(PROP_NAME_METADATA_ELEMENT, evt -> updateUiState()); bindingContext.addPropertyChangeListener(evt -> updateChartData()); } private DefaultXYItemRenderer creatItemRenderer(int index, int yDataType) { DefaultXYItemRenderer itemRenderer = new DefaultXYItemRenderer(); itemRenderer.setSeriesPaint(0, DEFAULT_PAINT_ARRAY[index % DEFAULT_PAINT_ARRAY.length]); itemRenderer.setSeriesShape(0, DEFAULT_SHAPE_ARRAY[index % DEFAULT_SHAPE_ARRAY.length]); itemRenderer.setDefaultToolTipGenerator(new StandardXYToolTipGenerator()); final DecimalFormat numberFormat = new DecimalFormat("0.00#"); numberFormat.setGroupingUsed(false); StandardXYToolTipGenerator toolTipGenerator; if (ProductData.TYPE_UTC == yDataType) { toolTipGenerator = new StandardXYToolTipGenerator(TOOL_TIP_FORMAT, numberFormat, SIMPLE_DATE_FORMAT); } else { toolTipGenerator = new StandardXYToolTipGenerator(TOOL_TIP_FORMAT, numberFormat, numberFormat); } itemRenderer.setSeriesToolTipGenerator(0, toolTipGenerator); StandardXYItemLabelGenerator itemLabelGenerator; if (ProductData.TYPE_UTC == yDataType) { itemLabelGenerator = new StandardXYItemLabelGenerator(ITEM_LABEL_FORMAT, numberFormat, SIMPLE_DATE_FORMAT); } else { itemLabelGenerator = new StandardXYItemLabelGenerator(ITEM_LABEL_FORMAT, numberFormat, numberFormat); } itemRenderer.setSeriesItemLabelGenerator(0, itemLabelGenerator); return itemRenderer; } @Override protected void showAlternativeView() { final TableModel model; if (xyPlot != null && xyPlot.getSeriesCount() > 0) { model = new MetadataPlotTableModel(xyPlot); } else { model = new DefaultTableModel(); } final TableViewPagePanel alternativPanel = (TableViewPagePanel) getAlternativeView(); alternativPanel.setModel(model); super.showAlternativeView(); } @Override public void nodeDataChanged(ProductNodeEvent event) { // probably nothing needs to be done here super.nodeDataChanged(event); } @Override protected void updateComponents() { super.updateComponents(); updateSettings(); updateUiState(); } @Override protected void updateChartData() { resetChart(); MetadataElement metadataElement = plotSettings.getMetadataElement(); String nameX = plotSettings.getNameX(); String nameY1 = plotSettings.getNameY1(); if (metadataElement == null || nameX == null || StringUtils.isNullOrEmpty(nameY1) || MetadataPlotSettings.FIELD_NAME_NONE.equals(nameY1)) { return; } int numRecords = plotSettings.getNumRecords(); int recordsPerPlot = plotSettings.getRecordsPerPlot(); int startIndex = plotSettings.getRecordStartIndex(); String nameY2 = plotSettings.getFieldY2(); double[] recordIndices = getRecordIndices(startIndex, recordsPerPlot, numRecords); String[] recordElementNames = new String[recordIndices.length]; Arrays.setAll(recordElementNames, i -> String.format("%s.%.0f", metadataElement.getName(), recordIndices[i])); switch (nameX) { case MetadataPlotSettings.FIELD_NAME_RECORD_INDEX: configureChartForRecordIndex(metadataElement, nameX, nameY1, nameY2, recordElementNames, String.format("%s.1", metadataElement.getName()), recordIndices); break; case MetadataPlotSettings.FIELD_NAME_ARRAY_FIELD_INDEX: configureChartForArrayIndex(metadataElement, nameX, nameY1, nameY2, recordElementNames, String.format("%s.1", metadataElement.getName())); break; default: if (recordElementNames.length == 0) { break; } if (metadataElement.containsElement(recordElementNames[0])) { configureChartForDefault(metadataElement.getElement(recordElementNames[0]), nameX, nameY1, nameY2); } else { configureChartForDefault(metadataElement, nameX, nameY1, nameY2); } break; } } private void configureChartForDefault(MetadataElement metadataElement, String nameX, String nameY1, String nameY2) { if (!isValidYField(metadataElement, metadataElement.getName(), nameY1)) { return; } MetadataAttribute xAttribute = metadataElement.getAttribute(nameX); int xDataType = getAttributeType(xAttribute); configureDomainAxis(0, nameX, xDataType); double[] xData = new double[1]; Arrays.setAll(xData, i -> getDataAsDouble(xAttribute.getData())); MetadataAttribute y1Attribute = metadataElement.getAttribute(nameY1); int y1DataType = getAttributeType(y1Attribute); ValueAxis y1Axis = configureRangeIndex(0, y1DataType); String unitY1 = y1Attribute.getUnit(); y1Axis.setLabel(getYAxisLabel(nameY1, unitY1)); double[] y1AxisData = new double[1]; Arrays.setAll(y1AxisData, i -> getDataAsDouble(y1Attribute.getData())); DefaultXYDataset dataset1 = new DefaultXYDataset(); dataset1.addSeries(nameY1, new double[][]{xData, y1AxisData}); xyPlot.setDataset(0, dataset1); xyPlot.mapDatasetToRangeAxis(0, 0); xyPlot.setRenderer(0, creatItemRenderer(0, y1DataType)); if (!isValidYField(metadataElement, metadataElement.getName(), nameY2)) { return; } MetadataAttribute y2Attribute = metadataElement.getAttribute(nameY2); int y2DataType = getAttributeType(y2Attribute); ValueAxis y2Axis = configureRangeIndex(1, y2DataType); String unitY2 = y2Attribute.getUnit(); y2Axis.setLabel(getYAxisLabel(nameY2, unitY2)); double[] y2AxisData = new double[1]; Arrays.setAll(y2AxisData, i -> getDataAsDouble(y2Attribute.getData())); DefaultXYDataset dataset2 = new DefaultXYDataset(); dataset2.addSeries(nameY2, new double[][]{xData, y2AxisData}); xyPlot.setDataset(1, dataset2); xyPlot.mapDatasetToRangeAxis(1, 1); xyPlot.setRenderer(1, creatItemRenderer(1, y1DataType)); } private void configureChartForArrayIndex(MetadataElement metadataElement, String nameX, String nameY1, String nameY2, String[] recordElementNames, String refRecordName) { if (!isValidArrayYField(metadataElement, refRecordName, nameY1)) { return; } configureDomainAxis(0, nameX, ProductData.TYPE_INT32); MetadataElement refElem = metadataElement.getElement(refRecordName); int y1ArrayLength = (int) refElem.getAttribute(nameY1).getNumDataElems(); double[] y1ArrayIndices = new double[y1ArrayLength]; Arrays.setAll(y1ArrayIndices, i -> i); MetadataAttribute y1Attribute = metadataElement.getElement(refRecordName).getAttribute(nameY1); int y1DataType = getAttributeType(y1Attribute); ValueAxis y1Axis = configureRangeIndex(0, y1DataType); String unitY1 = y1Attribute.getUnit(); y1Axis.setLabel(getYAxisLabel(nameY1, unitY1)); int dataSetCnt = 0; for (int i = 0; i < recordElementNames.length; i++, dataSetCnt++) { String recordElementName = recordElementNames[i]; addArrayDataToSeries(0, 0, dataSetCnt, nameY1, metadataElement, y1ArrayIndices, recordElementName); } if (!isValidArrayYField(metadataElement, refRecordName, nameY2)) { return; } MetadataAttribute y2Attribute = metadataElement.getElement(refRecordName).getAttribute(nameY2); int y2DataType = getAttributeType(y2Attribute); ValueAxis y2Axis = configureRangeIndex(1, y2DataType); String unitY2 = y2Attribute.getUnit(); y2Axis.setLabel(getYAxisLabel(nameY2, unitY2)); int y2ArrayLength = (int) refElem.getAttribute(nameY2).getNumDataElems(); double[] y2ArrayIndices = new double[y2ArrayLength]; Arrays.setAll(y2ArrayIndices, i -> i); if (y2ArrayLength != y1ArrayLength) { configureDomainAxis(0, nameY1 + " - " + nameX, ProductData.TYPE_INT32); configureDomainAxis(1, nameY2 + " - " + nameX, ProductData.TYPE_INT32); } for (int i = 0; i < recordElementNames.length; i++, dataSetCnt++) { String recordElementName = recordElementNames[i]; addArrayDataToSeries(y2ArrayLength != y1ArrayLength ? 1 : 0, 1, dataSetCnt, nameY2, metadataElement, y2ArrayIndices, recordElementName); } } private void addArrayDataToSeries(int domainAxisIndex, int rangeAxisIndex, int datasetIndex, String yName, MetadataElement metadataElement, double[] arrayIndices, String recordElementName) { double[] yAxisData = new double[arrayIndices.length]; ProductData attributeData = metadataElement.getElement(recordElementName).getAttribute(yName).getData(); Arrays.setAll(yAxisData, attributeData::getElemDoubleAt); String seriesKey = String.format("%s/%s", recordElementName, yName); DefaultXYDataset dataset = new DefaultXYDataset(); dataset.addSeries(seriesKey, new double[][]{arrayIndices, yAxisData}); xyPlot.setDataset(datasetIndex, dataset); xyPlot.mapDatasetToRangeAxis(datasetIndex, rangeAxisIndex); xyPlot.mapDatasetToDomainAxis(datasetIndex, domainAxisIndex); xyPlot.setRenderer(datasetIndex, creatItemRenderer(datasetIndex, ProductData.TYPE_INT32)); } private void configureChartForRecordIndex(MetadataElement metadataElement, String nameX, String nameY1, String nameY2, String[] recordElementNames, String refRecordName, double[] recordIndices) { if (!isValidYField(metadataElement, refRecordName, nameY1)) { return; } configureRangeAxis(0, metadataElement, nameY1, recordElementNames, refRecordName, recordIndices); configureDomainAxis(0, nameX, ProductData.TYPE_INT32); if (!isValidYField(metadataElement, recordElementNames[0], nameY2)) { return; } configureRangeAxis(1, metadataElement, nameY2, recordElementNames, refRecordName, recordIndices); } private void configureRangeAxis(int index, MetadataElement metadataElement, String yAttributeName, String[] recordElementNames, String refRecordName, double[] recordIndices) { double[] yAxisData = new double[recordIndices.length]; Arrays.setAll(yAxisData, i -> getDataAsDouble(metadataElement.getElement(recordElementNames[i]).getAttribute(yAttributeName).getData())); DefaultXYDataset dataset2 = new DefaultXYDataset(); dataset2.addSeries(yAttributeName, new double[][]{recordIndices, yAxisData}); xyPlot.setDataset(index, dataset2); xyPlot.mapDatasetToRangeAxis(index, index); int yDataType = getAttributeType(metadataElement.getElement(refRecordName).getAttribute(yAttributeName)); ValueAxis yAxis = configureRangeIndex(index, yDataType); String yUnit = metadataElement.getElement(refRecordName).getAttribute(yAttributeName).getUnit(); yAxis.setLabel(getYAxisLabel(yAttributeName, yUnit)); xyPlot.setRenderer(index, creatItemRenderer(index, yDataType)); } private ValueAxis configureRangeIndex(int index, int dataType) { ValueAxis axis = createAxis(dataType); axis.setAutoRange(true); Font axisFont = axis.getLabelFont().deriveFont(Font.BOLD); axis.setLabelFont(axisFont); axis.setLabel(String.format("Y%d Samples", index + 1)); xyPlot.setRangeAxis(index, axis); xyPlot.setRangeAxisLocation(index, index == 0 ? AxisLocation.BOTTOM_OR_LEFT : AxisLocation.BOTTOM_OR_RIGHT); return axis; } private ValueAxis createAxis(int dataType) { ValueAxis axis; if (ProductData.TYPE_UTC == dataType) { axis = new DateAxis("Date", TimeZone.getTimeZone("UTC"), Locale.ENGLISH); ((DateAxis) axis).setDateFormatOverride(SIMPLE_DATE_FORMAT); } else { axis = new NumberAxis(); ((NumberAxis) axis).setAutoRangeIncludesZero(false); } return axis; } private void configureDomainAxis(int index, String nameX, int dataType) { ValueAxis axis = createAxis(dataType); axis.setAutoRange(true); axis.setAutoRangeMinimumSize(2); axis.setLabel(nameX); Font axisFont = axis.getLabelFont().deriveFont(Font.BOLD); axis.setLabelFont(axisFont); xyPlot.setDomainAxis(index, axis); } private int getAttributeType(MetadataAttribute attribute) { return ProductData.getType(attribute.getData().getTypeString()); } private double getDataAsDouble(ProductData data) { if (data instanceof ProductData.UTC) { return ((ProductData.UTC) data).getAsDate().getTime(); } else { return data.getElemDouble(); } } private String getYAxisLabel(String name, String unit) { return name + (StringUtils.isNullOrEmpty(unit) || unit.equals("-") ? "" : (" in " + unit)); } private void resetChart() { removeAllDatasetSeries(); xyPlot.clearRangeAxes(); xyPlot.clearDomainAxes(); configureDomainAxis(0, DEFAULT_X_AXIS_LABEL, ProductData.TYPE_FLOAT64); xyPlot.getRenderer().setDefaultSeriesVisibleInLegend(true); } private boolean isValidYField(MetadataElement metadataElement, String elementName, String nameY) { MetadataElement element = metadataElement.getName().equals(elementName) ? metadataElement : metadataElement.getElement(elementName); return StringUtils.isNotNullAndNotEmpty(nameY) && !MetadataPlotSettings.FIELD_NAME_NONE.equals(nameY) && element != null && element.getAttribute(nameY) != null; } private boolean isValidArrayYField(MetadataElement metadataElement, String elementName, String nameY) { MetadataElement element = metadataElement.getElement(elementName); if (element == null || StringUtils.isNullOrEmpty(nameY)) { return false; } MetadataAttribute attribute = element.getAttribute(nameY); return attribute != null && !MetadataPlotSettings.FIELD_NAME_NONE.equals( nameY) && attribute.getNumDataElems() > 1; } private void removeAllDatasetSeries() { int datasetCount = xyPlot.getDatasetCount(); for (int i = 0; i < datasetCount; i++) { xyPlot.setDataset(i, null); } } static double[] getRecordIndices(int startIndex, int recordsPerPlot, int numRecords) { int clippedStartIndex = Math.max(1, Math.min(startIndex, numRecords)); int clippedEndIndex = Math.min(numRecords, Math.min((startIndex - 1) + recordsPerPlot, numRecords)); double[] indexArray = new double[clippedEndIndex - clippedStartIndex + 1]; Arrays.setAll(indexArray, index -> index + clippedStartIndex); return indexArray; } @Override protected String getDataAsText() { StringWriter sw = new StringWriter(); try { encodeCsv(sw); sw.close(); } catch (IOException e) { throw new IllegalStateException(e); } return sw.toString(); } private void encodeCsv(Writer writer) throws IOException { new TableModelCsvEncoder(new MetadataPlotTableModel(xyPlot)).encodeCsv(writer); } private JPanel createSettingsPanel(BindingContext bindingContext) { final JLabel datasetLabel = new JLabel("Dataset: "); final JComboBox<MetadataElement> datasetBox = new JComboBox<>(); datasetBox.setRenderer(new ProductNodeListCellRenderer()); JLabel recordLabel = new JLabel("Record: "); recordValueField = new JTextField(7); recordSlider = new JSlider(SwingConstants.HORIZONTAL, 1, 1, 1); recordSlider.setPaintTrack(true); recordSlider.setPaintTicks(true); recordSlider.setPaintLabels(true); configureSilderLabels(recordSlider); JLabel numRecordsLabel = new JLabel("Records / Plot: "); numRecSpinnerModel = new SpinnerNumberModel(1, 1, 1, 1); JSpinner numRecordsSpinner = new JSpinner(numRecSpinnerModel); numRecordsSpinner.setEditor(new JSpinner.NumberEditor(numRecordsSpinner, "#")); final JLabel xFieldLabel = new JLabel("X Field: "); final JComboBox<MetadataAttribute> xFieldBox = new JComboBox<>(); xFieldBox.setRenderer(new ProductNodeListCellRenderer()); final JLabel y1FieldLabel = new JLabel("Y Field: "); final JComboBox<MetadataAttribute> y1FieldBox = new JComboBox<>(); y1FieldBox.setRenderer(new ProductNodeListCellRenderer()); final JLabel y2FieldLabel = new JLabel("Y2 Field: "); final JComboBox<MetadataAttribute> y2FieldBox = new JComboBox<>(); y2FieldBox.setRenderer(new ProductNodeListCellRenderer()); bindingContext.bind(PROP_NAME_METADATA_ELEMENT, datasetBox); bindingContext.bind(PROP_NAME_RECORD_START_INDEX, recordValueField); bindingContext.bind(PROP_NAME_RECORD_START_INDEX, new SliderAdapter(recordSlider)); bindingContext.bind(PROP_NAME_RECORDS_PER_PLOT, numRecordsSpinner); bindingContext.bind(PROP_NAME_FIELD_X, xFieldBox); bindingContext.bind(PROP_NAME_FIELD_Y1, y1FieldBox); bindingContext.bind(PROP_NAME_FIELD_Y2, y2FieldBox); TableLayout layout = new TableLayout(3); JPanel plotSettingsPanel = new JPanel(layout); layout.setTableWeightX(0.0); layout.setTableAnchor(TableLayout.Anchor.NORTHWEST); layout.setTableFill(TableLayout.Fill.HORIZONTAL); layout.setTablePadding(4, 4); layout.setCellWeightX(0, 1, 1.0); layout.setCellColspan(0, 1, 2); plotSettingsPanel.add(datasetLabel); plotSettingsPanel.add(datasetBox); layout.setCellWeightX(1, 1, 0.2); layout.setCellWeightX(1, 2, 0.8); plotSettingsPanel.add(recordLabel); plotSettingsPanel.add(recordValueField); plotSettingsPanel.add(recordSlider); layout.setCellWeightX(2, 1, 1.0); layout.setCellColspan(2, 1, 2); plotSettingsPanel.add(numRecordsLabel); plotSettingsPanel.add(numRecordsSpinner); layout.setCellWeightX(3, 1, 1.0); layout.setCellColspan(3, 1, 2); plotSettingsPanel.add(xFieldLabel); plotSettingsPanel.add(xFieldBox); layout.setCellWeightX(4, 1, 1.0); layout.setCellColspan(4, 1, 2); plotSettingsPanel.add(y1FieldLabel); plotSettingsPanel.add(y1FieldBox); layout.setCellWeightX(5, 1, 1.0); layout.setCellColspan(5, 1, 2); plotSettingsPanel.add(y2FieldLabel); plotSettingsPanel.add(y2FieldBox); updateSettings(); updateUiState(); return plotSettingsPanel; } private void configureSilderLabels(JSlider recordSlider) { Hashtable<Integer, JLabel> labelTable = new Hashtable<>(); JLabel minLabel = new JLabel(String.valueOf(recordSlider.getMinimum())); labelTable.put(recordSlider.getMinimum(), minLabel); JLabel maxLabel = new JLabel(String.valueOf(recordSlider.getMaximum())); labelTable.put(recordSlider.getMaximum(), maxLabel); recordSlider.setLabelTable(labelTable); } private void updateUiState() { if (!isInitialized) { return; } int numRecords = plotSettings.getNumRecords(); recordSlider.setMaximum(numRecords); configureSilderLabels(recordSlider); numRecSpinnerModel.setMaximum(numRecords); plotSettings.getContext().setComponentsEnabled(PROP_NAME_RECORD_START_INDEX, numRecords > 1); plotSettings.getContext().setComponentsEnabled(PROP_NAME_RECORDS_PER_PLOT, numRecords > 1); recordValueField.setEditable(numRecords > 1); } private void updateSettings() { Product product = getProduct(); if (product == null) { plotSettings.setMetadataElements(null); return; } removeAllDatasetSeries(); MetadataElement metadataRoot = product.getMetadataRoot(); MetadataElement[] elements = metadataRoot.getElements(); recordSlider.setValue(1); plotSettings.setMetadataElements(elements); } private static class ProductNodeListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel rendererComponent = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof ProductNode) { ProductNode element = (ProductNode) value; rendererComponent.setText(element.getName()); } return rendererComponent; } } }
27,650
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DragScrollListener.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/quicklooks/DragScrollListener.java
package org.esa.snap.rcp.quicklooks; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Point2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; /** * Listener to allow for iPhone like drag scrolling of a Component within a JScrollPane. * * @author Greg Cope * <p> * <p> * <p> * This program is free software: you can redistribute it and/or modify * <p> * it under the terms of the GNU General Public License as published by * <p> * the Free Software Foundation, either version 3 of the License, or * <p> * (at your option) any later version. * <p> * <p> * <p> * This program is distributed in the hope that it will be useful, * <p> * but WITHOUT ANY WARRANTY; without even the implied warranty of * <p> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * <p> * GNU General Public License for more details. * <p> * <p> * <p> * You should have received a copy of the GNU General Public License * <p> * along with this program. If not, see //www.gnu.org/licenses/>. */ public class DragScrollListener implements MouseListener, MouseMotionListener { //flags used to turn on/off draggable scrolling directions public static final int DRAGABLE_HORIZONTAL_SCROLL_BAR = 1; public static final int DRAGABLE_VERTICAL_SCROLL_BAR = 2; //defines the intensity of automatic scrolling. private int scrollingIntensity = 10; //value used to decrease scrolling intensity during animation private double damping = 0.05; //indicates the number of milliseconds between animation updates. private int animationSpeed = 20; //Animation timer private Timer animationTimer = null; //the time of the last mouse drag event private long lastDragTime = 0; private Point lastDragPoint = null; //animation rates private double pixelsPerMSX; private double pixelsPerMSY; //flag which defines the draggable scroll directions private int scrollBarMask = DRAGABLE_HORIZONTAL_SCROLL_BAR | DRAGABLE_VERTICAL_SCROLL_BAR; //the draggable component private final Component draggableComponent; //the JScrollPane containing the component private JScrollPane scroller = null; //the default cursor private Cursor defaultCursor; //List of drag speeds used to calculate animation speed //Uses the Point2D class to represent speeds rather than locations private java.util.List<Point2D> dragSpeeds = new ArrayList<Point2D>(); public DragScrollListener(final Component c) { this.draggableComponent = c; this.defaultCursor = draggableComponent.getCursor(); this.draggableComponent.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent arg0) { setScroller(); defaultCursor = draggableComponent.getCursor(); } }); setScroller(); } private void setScroller() { Component c = getParentScroller(draggableComponent); if (c != null) { scroller = (JScrollPane) c; } else { scroller = null; } } /** * Sets the Draggable elements - the Horizontal or Vertical Direction. One * <p> * can use a bitmasked 'or' (HORIZONTAL_SCROLL_BAR | VERTICAL_SCROLL_BAR ). * * @param mask One of HORIZONTAL_SCROLL_BAR, VERTICAL_SCROLL_BAR, or HORIZONTAL_SCROLL_BAR | VERTICAL_SCROLL_BAR */ public void setDraggableElements(int mask) { scrollBarMask = mask; } /** * Sets the scrolling intensity - the default value being 5. Note, that this has an * <p> * inverse relationship to intensity (1 has the biggest difference, higher numbers having * <p> * less impact). * * @param intensity The new intensity value (Note the inverse relationship). */ public void setScrollingIntensity(int intensity) { scrollingIntensity = intensity; } /** * Sets how frequently the animation will occur in milliseconds. Default * <p> * value is 30 milliseconds. 60+ will get a bit flickery. * * @param timing The timing, in milliseconds. */ public void setAnimationTiming(int timing) { animationSpeed = timing; } /** * Sets the animation damping. * * @param damping The new value */ public void setDamping(double damping) { this.damping = damping; } /** * Empty implementation */ public void mouseEntered(MouseEvent e) { } /** * Empty implementation */ public void mouseExited(MouseEvent e) { } /** * Mouse pressed implementation */ public void mousePressed(MouseEvent e) { if (animationTimer != null && animationTimer.isRunning()) { animationTimer.stop(); } draggableComponent.setCursor(new Cursor(Cursor.MOVE_CURSOR)); dragSpeeds.clear(); lastDragPoint = e.getPoint(); } /** * Mouse released implementation. This determines if further animation * <p> * is necessary and launches the appropriate times. */ public void mouseReleased(MouseEvent e) { draggableComponent.setCursor(defaultCursor); if (scroller == null) { return; } //make sure the mouse ended in a dragging event long durationSinceLastDrag = System.currentTimeMillis() - lastDragTime; if (durationSinceLastDrag > 20) { return; } //get average speed for last few drags pixelsPerMSX = 0; pixelsPerMSY = 0; int j = 0; for (int i = dragSpeeds.size() - 1; i >= 0 && i > dragSpeeds.size() - 6; i--, j++) { pixelsPerMSX += dragSpeeds.get(i).getX(); pixelsPerMSY += dragSpeeds.get(i).getY(); } pixelsPerMSX /= -(double) j; pixelsPerMSY /= -(double) j; //start the timer if (Math.abs(pixelsPerMSX) > 0 || Math.abs(pixelsPerMSY) > 0) { animationTimer = new Timer(animationSpeed, new ScrollAnimator()); animationTimer.start(); } } /** * Empty implementation */ public void mouseClicked(MouseEvent e) { } /** * MouseDragged implementation. Sets up timing and frame animation. */ public void mouseDragged(MouseEvent e) { if (scroller == null) { return; } final Point p = e.getPoint(); final int diffx = p.x - lastDragPoint.x; final int diffy = p.y - lastDragPoint.y; lastDragPoint = e.getPoint(); //scroll the x axis if ((scrollBarMask & DRAGABLE_HORIZONTAL_SCROLL_BAR) != 0) { getHorizontalScrollBar().setValue(getHorizontalScrollBar().getValue() - diffx); } //the Scrolling affects mouse locations - offset the last drag point to compensate lastDragPoint.x = lastDragPoint.x - diffx; //scroll the y axis if ((scrollBarMask & DRAGABLE_VERTICAL_SCROLL_BAR) != 0) { getVerticalScrollBar().setValue(getVerticalScrollBar().getValue() - diffy); } //the Scrolling affects mouse locations - offset the last drag point to compensate lastDragPoint.y = lastDragPoint.y - diffy; //add a drag speed dragSpeeds.add(new Point2D.Double((e.getPoint().x - lastDragPoint.x), (e.getPoint().y - lastDragPoint.y))); lastDragTime = System.currentTimeMillis(); } /** * Empty */ public void mouseMoved(MouseEvent e) { } /** * Private inner class which accomplishes the animation. * * @author Greg Cope */ private class ScrollAnimator implements ActionListener { /** * Performs the animation through the setting of the JScrollBar values. */ public void actionPerformed(ActionEvent e) { //damp the scrolling intensity pixelsPerMSX -= pixelsPerMSX * damping; pixelsPerMSY -= pixelsPerMSY * damping; //check to see if timer should stop. if (Math.abs(pixelsPerMSX) < 0.01 && Math.abs(pixelsPerMSY) < 0.01) { animationTimer.stop(); return; } //calculate new X value int nValX = getHorizontalScrollBar().getValue() + (int) (pixelsPerMSX * scrollingIntensity); int nValY = getVerticalScrollBar().getValue() + (int) (pixelsPerMSY * scrollingIntensity); //Deal with out of scroll bounds if (nValX <= 0) { nValX = 0; } else if (nValX >= getHorizontalScrollBar().getMaximum()) { nValX = getHorizontalScrollBar().getMaximum(); } if (nValY <= 0) { nValY = 0; } else if (nValY >= getVerticalScrollBar().getMaximum()) { nValY = getVerticalScrollBar().getMaximum(); } //Check again to see if timer should stop if ((nValX == 0 || nValX == getHorizontalScrollBar().getMaximum()) && Math.abs(pixelsPerMSY) < 1) { animationTimer.stop(); return; } if ((nValY == 0 || nValY == getVerticalScrollBar().getMaximum()) && Math.abs(pixelsPerMSX) < 1) { animationTimer.stop(); return; } //Set new values if ((scrollBarMask & DRAGABLE_HORIZONTAL_SCROLL_BAR) != 0) { getHorizontalScrollBar().setValue(nValX); } if ((scrollBarMask & DRAGABLE_VERTICAL_SCROLL_BAR) != 0) { getVerticalScrollBar().setValue(nValY); } } } /** * Utility to retrieve the Horizontal Scroll Bar. * * @return */ private JScrollBar getHorizontalScrollBar() { return scroller.getHorizontalScrollBar(); } /** * Utility to retrieve the Vertical Scroll Bar * * @return */ private JScrollBar getVerticalScrollBar() { return scroller.getVerticalScrollBar(); } /** * @param c * @return */ private Component getParentScroller(Component c) { Container parent = c.getParent(); if (parent != null && parent instanceof Component) { Component parentC = (Component) parent; if (parentC instanceof JScrollPane) { return parentC; } else { return getParentScroller(parentC); } } return null; } }
11,088
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ThumbnailPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/quicklooks/ThumbnailPanel.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.quicklooks; import com.bc.ceres.core.ProgressMonitor; import net.coobird.thumbnailator.makers.FixedSizeThumbnailMaker; import org.esa.snap.core.datamodel.quicklooks.Thumbnail; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.List; /** * Displays a panel of thumbnails */ public class ThumbnailPanel extends JPanel { private final static int imgWidth = 200; private final static int imgHeight = 200; private final static int margin = 6; private final static BasicStroke thickStroke = new BasicStroke(5); private final static String vkControl = "VK_CONTROL"; private enum SelectionMode {CHECK, RECT} private final boolean multiRow; private SelectionMode selectionMode; private List<ThumbnailDrawing> selection; private boolean ctrlPressed; public ThumbnailPanel(final boolean multiRow) { super(new FlowLayout(FlowLayout.LEADING)); this.multiRow = multiRow; this.selectionMode = SelectionMode.RECT; this.selection = new ArrayList<>(); final DragScrollListener dragScrollListener = new DragScrollListener(this); dragScrollListener.setDraggableElements(DragScrollListener.DRAGABLE_VERTICAL_SCROLL_BAR); addMouseListener(dragScrollListener); addMouseMotionListener(dragScrollListener); setKeyBindings(); } private void setKeyBindings() { final InputMap inputMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_CONTROL, KeyEvent.CTRL_DOWN_MASK), vkControl+"DOWN"); inputMap.put(KeyStroke.getKeyStroke("released CONTROL"), vkControl+"UP"); final ActionMap actionMap = getActionMap(); actionMap.put(vkControl+"DOWN", new KeyAction(vkControl+"DOWN")); actionMap.put(vkControl+"UP", new KeyAction(vkControl+"UP")); } private class KeyAction extends AbstractAction { public KeyAction(String actionCommand) { putValue(ACTION_COMMAND_KEY, actionCommand); } @Override public void actionPerformed(ActionEvent e) { final String cmd = e.getActionCommand(); ctrlPressed = cmd.equals(vkControl+"DOWN"); } } public void update(final Thumbnail[] imageList) { this.removeAll(); final Insets insets = getInsets(); final int width = getWidth() - (insets.left + insets.right); if (imageList.length == 0) { setPreferredSize(new Dimension(width, imgHeight + 2 * margin)); JLabel label = new JLabel(""); this.add(label); } else { if (multiRow) { int numImages = 1; int effectiveImageWidth = imgWidth * numImages + margin; int numCol = Math.max(width / effectiveImageWidth, 1); int numRow = (int)Math.ceil(imageList.length / (double)numCol); int preferredWidth = effectiveImageWidth * numCol + margin; int preferredHeight = (imgHeight + margin) * numRow + margin; setPreferredSize(new Dimension(preferredWidth, preferredHeight)); } for (Thumbnail thumbnail : imageList) { this.add(new ThumbnailDrawing(this, thumbnail)); } } updateUI(); } private void setSelection(final ThumbnailDrawing item) { if(selection.contains(item)) { selection.remove(item); } else { if(ctrlPressed) { selection.add(item); } else { selection.clear(); selection.add(item); } } onSelectionChanged(); } public void onSelectionChanged() { } public void onOpenAction() { } public void selectAll() { selection.clear(); for(Component component : this.getComponents()) { selection.add((ThumbnailDrawing)component); } repaint(); } public void clearSelection() { selection.clear(); repaint(); } public ThumbnailDrawing[] getSelection() { return selection.toArray(new ThumbnailDrawing[selection.size()]); } private boolean isSelected(final ThumbnailDrawing item) { return selection.contains(item); } public class ThumbnailDrawing extends JLabel implements MouseListener, Thumbnail.ThumbnailListener { private final ThumbnailPanel parent; private final Thumbnail thumbnail; public ThumbnailDrawing(final ThumbnailPanel parent, final Thumbnail thumbnail) { this.parent = parent; this.thumbnail = thumbnail; this.thumbnail.addListener(this); setPreferredSize(new Dimension(imgWidth, imgHeight)); setToolTipText(""); addMouseListener(this); } public Thumbnail getThumbnail() { return thumbnail; } public void notifyImageUpdated(Thumbnail thumbnail) { parent.repaint(); } @Override public void paintComponent(Graphics graphics) { super.paintComponent(graphics); final Graphics2D g = (Graphics2D) graphics; g.setColor(Color.BLACK); g.fillRect(0,0, imgWidth, imgHeight); if(thumbnail.hasImage() || thumbnail.hasCachedImage()) { drawIcon(g, thumbnail.getImage(ProgressMonitor.NULL)); } else { drawIcon(g, null); } if (isSelected(this) && selectionMode == SelectionMode.RECT) { drawSelected(g); } } private void drawIcon(Graphics2D g, BufferedImage icon) { if (icon != null) { BufferedImage img = new FixedSizeThumbnailMaker() .size(imgWidth, imgHeight) .keepAspectRatio(true) .fitWithinDimensions(true) .make(icon); int xOff = (imgWidth - img.getWidth())/2; int yOff = (imgHeight - img.getHeight())/2; g.drawImage(img, xOff, yOff, img.getWidth(), img.getHeight(), null); } else { // Draw cross to indicate missing image g.setColor(Color.DARK_GRAY); g.setStroke(thickStroke); g.drawLine(0, 0, 0 + imgWidth, imgHeight); g.drawLine(0 + imgWidth, 0, 0, imgHeight); g.drawRect(0, 0, imgWidth-1, imgHeight-1); } } private void drawSelected(Graphics2D g) { g.setColor(new Color(0,100,255)); g.setStroke(thickStroke); g.drawRect(0, 0, imgWidth, imgHeight); for(int i=0; i <= 20; ++i) { int alpha = 40-(i*2); g.setColor(new Color(0,100,255,alpha)); g.drawRoundRect(i, i, imgWidth-i-i, imgHeight-i-i, 25, 25); } } @Override public Point getToolTipLocation(MouseEvent e) { return new Point(-700, 0); } @Override public JToolTip createToolTip() { if(!thumbnail.hasImage() || !thumbnail.hasCachedImage()) { return super.createToolTip(); } final BufferedImage thumbnailImage = thumbnail.getImage(ProgressMonitor.NULL); BufferedImage img = new FixedSizeThumbnailMaker() .size(imgWidth*3, imgHeight*3) .keepAspectRatio(true) .fitWithinDimensions(true) .make(thumbnailImage); final JToolTip toolTip = new JToolTip() { { setLayout(new BorderLayout()); add(new JLabel(new ImageIcon(img))); } public Dimension getPreferredSize() { return new Dimension(img.getWidth(), img.getHeight()); } }; return toolTip; } @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { if (e.getClickCount() == 2) { onOpenAction(); } else if (e.getButton() == MouseEvent.BUTTON1) { setSelection(this); parent.repaint(); } else if (e.getButton() == MouseEvent.BUTTON3) { } } @Override public void mouseReleased(MouseEvent e) { } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } } }
9,686
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
QuicklookToolView.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/quicklooks/QuicklookToolView.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.quicklooks; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import net.coobird.thumbnailator.makers.FixedSizeThumbnailMaker; 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.core.datamodel.quicklooks.Quicklook; import org.esa.snap.core.datamodel.quicklooks.Thumbnail; import org.esa.snap.core.dataop.downloadable.StatusProgressMonitor; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.window.OpenRGBImageViewAction; import org.esa.snap.rcp.util.SelectionSupport; import org.esa.snap.tango.TangoIcons; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import org.netbeans.api.annotations.common.NullAllowed; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.media.jai.JAI; import javax.swing.BoxLayout; import javax.swing.DefaultComboBoxModel; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JScrollPane; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.util.ArrayList; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; @TopComponent.Description( preferredID = "QuicklookToolView", iconBase = "org/esa/snap/rcp/icons/quicklook.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS ) @TopComponent.Registration( mode = "navigator", openAtStartup = false, position = 1 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.quicklooks.QuicklookToolView") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 50), @ActionReference(path = "Toolbars/Tool Windows") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_QuicklookToolView_Name", preferredID = "QuicklookToolView" ) @NbBundle.Messages({ "CTL_QuicklookToolView_Name=Quicklooks", "CTL_QuicklookToolView_Description=Quicklooks of all bands", }) /** * Tool window to display quicklooks */ public class QuicklookToolView extends TopComponent implements Thumbnail.ThumbnailListener { private Product currentProduct; private final SortedSet<Product> productSet; private final SortedSet<String> quicklookNameSet = new TreeSet<>(); private final JComboBox<String> quicklookNameCombo = new JComboBox<>(); private final JLabel nameLabel = new JLabel(); private final ImagePanel imgPanel = new ImagePanel(); private final BufferedImage noDataImage; private JScrollPane imgScrollPanel; private JButton nextBtn, prevBtn, startBtn, endBtn, openBtn, closeBtn, refreshBtn, viewBtn; private ButtonActionListener actionListener = new ButtonActionListener(); private boolean updateQuicklooks = false; private ProductNode oldNode = null; private int zoom = 1; private static final String DEFAULT_QUICKLOOK = "Default"; private static final ImageIcon openIcon = TangoIcons.actions_document_open(TangoIcons.Res.R22); private static final ImageIcon closeIcon = TangoIcons.actions_list_remove(TangoIcons.Res.R22); private static final ImageIcon firstIcon = TangoIcons.actions_go_first(TangoIcons.Res.R22); private static final ImageIcon lastIcon = TangoIcons.actions_go_last(TangoIcons.Res.R22); private static final ImageIcon nextIcon = TangoIcons.actions_go_next(TangoIcons.Res.R22); private static final ImageIcon previousIcon = TangoIcons.actions_go_previous(TangoIcons.Res.R22); private static final ImageIcon refreshIcon = TangoIcons.actions_view_refresh(TangoIcons.Res.R22); private static final ImageIcon singleViewIcon = UIUtils.loadImageIcon("/org/esa/snap/rcp/icons/view_single24.png", ThumbnailPanel.class); private static final ImageIcon thumbnailViewIcon = UIUtils.loadImageIcon("/org/esa/snap/rcp/icons/view_thumbnails24.png", ThumbnailPanel.class); public QuicklookToolView() { setLayout(new BorderLayout()); setDisplayName(Bundle.CTL_QuicklookToolView_Name()); setToolTipText(Bundle.CTL_QuicklookToolView_Description()); add(createPanel(), BorderLayout.CENTER); noDataImage = createNoDataImage(); final SnapApp snapApp = SnapApp.getDefault(); snapApp.getProductManager().addListener(new ProductManagerListener()); productSet = new TreeSet<>(new Comparator<Product>() { public int compare(Product p1, Product p2) { int ref1 = p1.getRefNo(); int ref2 = p2.getRefNo(); return ref1 < ref2 ? -1 : ref1 == ref2 ? 0 : 1; } }); quicklookNameSet.add(DEFAULT_QUICKLOOK); addProducts(); updateButtons(); quicklookNameCombo.setSelectedItem(DEFAULT_QUICKLOOK); quicklookNameCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showProduct(currentProduct); } }); snapApp.getSelectionSupport(ProductNode.class).addHandler(new SelectionSupport.Handler<ProductNode>() { @Override public void selectionChange(@NullAllowed ProductNode oldValue, @NullAllowed ProductNode newValue) { if (newValue != null && newValue != oldNode) { showProduct(newValue.getProduct()); oldNode = newValue; } } }); } public JComponent createPanel() { final JPanel panel = new JPanel(new BorderLayout()); panel.add(createTopPanel(), BorderLayout.NORTH); panel.add(createSidePanel(), BorderLayout.EAST); panel.add(createImagePanel(), BorderLayout.CENTER); panel.add(createButtonPanel(), BorderLayout.SOUTH); return panel; } private JPanel createTopPanel() { final JPanel topPanel = new JPanel(new BorderLayout()); topPanel.add(nameLabel, BorderLayout.CENTER); topPanel.add(quicklookNameCombo, BorderLayout.EAST); return topPanel; } private JPanel createSidePanel() { final JPanel sidePanel = new JPanel(); sidePanel.setLayout(new BoxLayout(sidePanel, BoxLayout.Y_AXIS)); // viewBtn = createButton("viewButton", "Change View", sidePanel, actionListener, thumbnailViewIcon); // viewBtn.addActionListener(new ActionListener() { // public synchronized void actionPerformed(final ActionEvent e) { // // } // }); // sidePanel.add(viewBtn); openBtn = createButton("Open", "Open RGB", sidePanel, actionListener, openIcon); sidePanel.add(openBtn); // todo why is this here? closeBtn = createButton("Close", "Close Product", sidePanel, actionListener, closeIcon); // sidePanel.add(closeBtn); return sidePanel; } private JScrollPane createImagePanel() { imgScrollPanel = new JScrollPane(imgPanel); imgPanel.setComponentPopupMenu(createImagePopup()); return imgScrollPanel; } private JPanel createButtonPanel() { final JPanel buttonPanel = new JPanel(); startBtn = createButton("Start", "Go to first product", buttonPanel, actionListener, firstIcon); prevBtn = createButton("Prev", "Previous product", buttonPanel, actionListener, previousIcon); nextBtn = createButton("Next", "Next product", buttonPanel, actionListener, nextIcon); endBtn = createButton("End", "Go to last product", buttonPanel, actionListener, lastIcon); refreshBtn = createButton("Refresh", "Update products", buttonPanel, actionListener, refreshIcon); buttonPanel.add(startBtn); buttonPanel.add(prevBtn); buttonPanel.add(nextBtn); buttonPanel.add(endBtn); buttonPanel.add(refreshBtn); return buttonPanel; } private static JButton createButton(final String name, final String text, final JPanel panel, final ButtonActionListener actionListener, final ImageIcon icon) { final JButton btn = (JButton) ToolButtonFactory.createButton(icon, false); btn.setName(name); btn.setIcon(icon); if (panel != null) { btn.setBackground(panel.getBackground()); } btn.setToolTipText(text); btn.setActionCommand(name); btn.addActionListener(actionListener); return btn; } private void updateButtons() { boolean hasProducts = !productSet.isEmpty(); boolean hasPrevProd = getPreviousProduct() != null; boolean hasNextProd = getNextProduct() != null; startBtn.setEnabled(hasPrevProd); prevBtn.setEnabled(hasPrevProd); nextBtn.setEnabled(hasNextProd); endBtn.setEnabled(hasNextProd); refreshBtn.setEnabled(hasProducts); if(!hasProducts) { imgPanel.setImage(null); nameLabel.setText(""); currentProduct = null; } openBtn.setEnabled(currentProduct != null); closeBtn.setEnabled(currentProduct != null); } private static BufferedImage createNoDataImage() { final int w = 100, h = 100; final BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); final Graphics2D g = image.createGraphics(); g.addRenderingHints(new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); g.addRenderingHints(new RenderingHints( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g.addRenderingHints(new RenderingHints( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC)); g.setColor(Color.DARK_GRAY); g.setStroke(new BasicStroke(1)); g.drawLine(0, 0, 0 + w, h); g.drawLine(0 + w, 0, 0, h); g.drawRect(0, 0, w - 1, h - 1); return image; } private synchronized void loadProducts(final String qlName) { try { final List<Thread> threadList = new ArrayList<>(); final int numConsecutiveThreads = Runtime.getRuntime().availableProcessors(); // collect quicklooks that need to load final List<Quicklook> quicklooksToLoad = new ArrayList<>(); for (final Product product : productSet) { if(product.getFileLocation() != null) { final Quicklook quicklook; if (qlName.equals(DEFAULT_QUICKLOOK)) { quicklook = product.getDefaultQuicklook(); } else { quicklook = product.getQuicklook(qlName); } if (quicklook != null && !quicklook.hasImage() && !quicklook.hasCachedImage()) { quicklooksToLoad.add(quicklook); } } } if(quicklooksToLoad.isEmpty()) { updateQuicklooks = true; showProduct(currentProduct); return; } ProgressMonitorSwingWorker<Boolean, Object> worker = new ProgressMonitorSwingWorker<Boolean, Object> (SnapApp.getDefault().getMainFrame(), "Loading quicklooks") { @Override protected Boolean doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception { final int total = productSet.size(); pm.beginTask("Generating quicklooks", total); int cnt = 1; for (final Quicklook quicklook : quicklooksToLoad) { if(pm.isCanceled()) break; final Thread worker = new Thread() { @Override public void run() { try { quicklook.getImage(SubProgressMonitor.create(pm, 1)); } catch (Throwable e) { SystemUtils.LOG.warning("Unable to create quicklook for " + quicklook.getProductFile() + '\n' + e.getMessage()); } } }; threadList.add(worker); worker.start(); if (threadList.size() >= numConsecutiveThreads) { for (Thread t : threadList) { t.join(); } threadList.clear(); } JAI.getDefaultInstance().getTileCache().flush(); JAI.getDefaultInstance().getTileCache().memoryControl(); System.gc(); pm.setTaskName("Generating quicklooks " + cnt + " of " + total); ++cnt; //pm.worked(1); } pm.done(); if (!threadList.isEmpty()) { for (Thread t : threadList) { t.join(); } } return true; } @Override protected void done() { super.done(); updateQuicklooks = true; showProduct(currentProduct); } }; worker.execute(); } catch (Exception e) { SnapApp.getDefault().handleError("Unable to load quicklooks", e); } } public void setSelectedQuicklook(final Quicklook ql) { updateQuicklooks = true; showProduct(ql.getProduct()); quicklookNameCombo.setSelectedItem(ql.getName()); } private synchronized void showProduct(final Product product) { if (product == null) { return; } final String qlName = (String)quicklookNameCombo.getSelectedItem(); if(qlName != null) { final Quicklook quicklook; if (qlName.equals(DEFAULT_QUICKLOOK)) { quicklook = product.getDefaultQuicklook(); } else { quicklook = product.getQuicklook(qlName); } if(quicklook != null) { quicklook.addListener(this); if ((quicklook.hasImage() || quicklook.hasCachedImage())) { setImage(product, quicklook); } else if (quicklook != null && updateQuicklooks) { if (product.getFileLocation() != null) { loadImage(product, quicklook); } } else { setImage(product, null); } } else { setImage(product, null); } } } private static void loadImage(final Product product, final Quicklook quicklook) { final StatusProgressMonitor qlPM = new StatusProgressMonitor(StatusProgressMonitor.TYPE.SUBTASK); qlPM.beginTask("Creating quicklook " + product.getName() + "... ", 100); ProgressMonitorSwingWorker<BufferedImage, Object> loader = new ProgressMonitorSwingWorker<BufferedImage, Object> (SnapApp.getDefault().getMainFrame(), "Loading quicklook image...") { @Override protected BufferedImage doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception { return quicklook.getImage(qlPM); } @Override protected void done() { qlPM.done(); } }; loader.execute(); } private void setImage(final Product product, final Quicklook quicklook) { final BufferedImage img; if(quicklook != null && (quicklook.hasImage() || quicklook.hasCachedImage())) { img = quicklook.getImage(ProgressMonitor.NULL); } else { img = noDataImage; } if(currentProduct == product && imgPanel.getImage() == img) { return; } currentProduct = product; nameLabel.setText(product.getDisplayName()); imgPanel.setImage(img); updateButtons(); } private void addProducts() { final Product[] products = SnapApp.getDefault().getProductManager().getProducts(); for(Product product : products) { addProduct(product); } } private synchronized void addProduct(final Product product) { productSet.add(product); for(int i=0; i < product.getQuicklookGroup().getNodeCount(); ++i) { quicklookNameSet.add(product.getQuicklookGroup().get(i).getName()); } updateQuicklookNameCombo(); } private synchronized void removeProduct(final Product product) { productSet.remove(product); cleanUpQuicklookNameSet(); updateQuicklookNameCombo(); } private void cleanUpQuicklookNameSet() { Set<String> toRemove = new HashSet<>(); for(String name : quicklookNameSet) { if(name.equals(DEFAULT_QUICKLOOK)) continue; boolean exists = false; for(Product product : productSet) { for(int i=0; i < product.getQuicklookGroup().getNodeCount(); ++i) { if(name.equals(product.getQuicklookGroup().get(i).getName())) { exists = true; break; } } } if(!exists) { toRemove.add(name); } } for(String name : toRemove) { quicklookNameSet.remove(name); } } private void updateQuicklookNameCombo() { String selected = (String)quicklookNameCombo.getSelectedItem(); quicklookNameCombo.removeAllItems(); for(String name : quicklookNameSet) { quicklookNameCombo.addItem(name); } // restore selection if(selected != null && ((DefaultComboBoxModel)quicklookNameCombo.getModel()).getIndexOf(selected) != -1 ) { quicklookNameCombo.setSelectedItem(selected); } else { quicklookNameCombo.setSelectedItem(DEFAULT_QUICKLOOK); } } private Product getFirstProduct() { return productSet.isEmpty() ? null : productSet.first(); } private Product getLastProduct() { return productSet.isEmpty() ? null : productSet.last(); } private Product getNextProduct() { final Iterator<Product> itr = productSet.iterator(); while (itr.hasNext()) { Product p = itr.next(); if (p == currentProduct) { if (itr.hasNext()) { return itr.next(); } else { return null; } } } return null; } private Product getPreviousProduct() { final Iterator<Product> itr = productSet.iterator(); Product prev = null; while (itr.hasNext()) { Product p = itr.next(); if (p == currentProduct) { return prev; } prev = p; } return null; } private void openProduct() { if(currentProduct != null) { final OpenRGBImageViewAction rgbAction = new OpenRGBImageViewAction(currentProduct); rgbAction.openProductSceneViewRGB(currentProduct, ""); } } private void closeProduct() { if (currentProduct != null) { Product productToClose = currentProduct; if(productToClose == getLastProduct()) { showProduct(getPreviousProduct()); } else { showProduct(getNextProduct()); } SnapApp.getDefault().getProductManager().removeProduct(productToClose); } } private class ImagePanel extends JLabel implements MouseListener { private BufferedImage img = null; public ImagePanel() { setHorizontalAlignment(JLabel.CENTER); setVerticalAlignment(JLabel.CENTER); addMouseListener(this); } public BufferedImage getImage() { return img; } public void setImage(final BufferedImage img) { this.img = img; if (img == null) { setIcon(null); } repaint(); } @Override public void paintComponent(Graphics g) { if (img != null) { Graphics2D g2 = (Graphics2D)g; g2.addRenderingHints(new RenderingHints( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); g2.addRenderingHints(new RenderingHints( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2.addRenderingHints(new RenderingHints( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC)); int w = imgScrollPanel.getWidth()*zoom - 10; int h = imgScrollPanel.getHeight()*zoom - 10; setIcon(new ImageIcon(new FixedSizeThumbnailMaker() .size(w, h) .keepAspectRatio(true) .fitWithinDimensions(true) .make(img))); } super.paintComponent(g); } public void mouseClicked(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (e.getClickCount() == 2 && currentProduct != null) { openProduct(); } } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } } private class ButtonActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { switch (e.getActionCommand()) { case "Start": showProduct(getFirstProduct()); break; case "Prev": showProduct(getPreviousProduct()); break; case "Next": showProduct(getNextProduct()); break; case "End": showProduct(getLastProduct()); break; case "Refresh": if(!productSet.isEmpty()) { loadProducts((String)quicklookNameCombo.getSelectedItem()); } break; case "Open": openProduct(); break; case "Close": closeProduct(); break; } } } public class ProductManagerListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { addProduct(event.getProduct()); updateButtons(); } @Override public void productRemoved(ProductManager.Event event) { if (event.getProduct() == currentProduct) { getNextProduct(); } removeProduct(event.getProduct()); updateButtons(); } } public JPopupMenu createImagePopup() { final JPopupMenu popup = new JPopupMenu(); final JMenuItem zoomInItem = new JMenuItem("Zoom in"); zoomInItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { if(zoom < 10) { zoom += 2; } } }); popup.add(zoomInItem); final JMenuItem zoomOutItem = new JMenuItem("Zoom out"); zoomOutItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { if(zoom > 2) { zoom -= 2; } } }); popup.add(zoomOutItem); popup.addSeparator(); final JMenuItem closeItem = new JMenuItem("Close Product"); closeItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { closeProduct(); } }); popup.add(closeItem); return popup; } public void notifyImageUpdated(Thumbnail thumbnail) { showProduct(thumbnail.getProduct()); } }
26,455
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
InsertPlacemarkInteractor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/InsertPlacemarkInteractor.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.placemark; import com.bc.ceres.swing.figure.FigureEditorInteractor; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.PlacemarkGroup; import org.esa.snap.core.datamodel.PlacemarkNameFactory; import org.esa.snap.core.datamodel.Product; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.product.ProductSceneView; import org.opengis.referencing.operation.TransformException; import org.openide.awt.UndoRedo; import java.awt.Component; import java.awt.Container; import java.awt.Cursor; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; /** * Interactor fort inserting pins and GCPs. * * @author Norman Fomferra */ public abstract class InsertPlacemarkInteractor extends FigureEditorInteractor { private final PlacemarkDescriptor placemarkDescriptor; private final Cursor cursor; private boolean started; protected InsertPlacemarkInteractor(PlacemarkDescriptor placemarkDescriptor) { this.placemarkDescriptor = placemarkDescriptor; this.cursor = createCursor(); } @Override public Cursor getCursor() { return cursor; } @Override public void mousePressed(MouseEvent event) { started = false; ProductSceneView sceneView = getProductSceneView(event); if (sceneView != null) { started = startInteraction(event); } } @Override public void mouseReleased(MouseEvent event) { if (started) { ProductSceneView sceneView = getProductSceneView(event); if (sceneView != null) { sceneView.selectVectorDataLayer(placemarkDescriptor.getPlacemarkGroup(sceneView.getProduct()).getVectorDataNode()); if (isSingleButton1Click(event)) { insertPlacemark(sceneView); } stopInteraction(event); } } } private void insertPlacemark(ProductSceneView view) { Product product = view.getProduct(); final String[] uniqueNameAndLabel = PlacemarkNameFactory.createUniqueNameAndLabel(placemarkDescriptor, product); final String name = uniqueNameAndLabel[0]; final String label = uniqueNameAndLabel[1]; PixelPos rasterPos = new PixelPos(view.getCurrentPixelX() + 0.5f, view.getCurrentPixelY() + 0.5f); Point2D modelPos = view.getRaster().getImageToModelTransform().transform(rasterPos, new Point2D.Double()); Point2D scenePos = new Point2D.Double(); try { view.getRaster().getModelToSceneTransform().transform(modelPos, scenePos); final AffineTransform sceneToImage = Product.findImageToModelTransform(product.getSceneGeoCoding()).createInverse(); rasterPos = (PixelPos) sceneToImage.transform(modelPos, new PixelPos()); } catch (TransformException | NoninvertibleTransformException e) { Dialogs.showError("Could not place pin in image due to transformation exception: " + e.getMessage()); return; } final Placemark newPlacemark = Placemark.createPointPlacemark(placemarkDescriptor, name, label, "", rasterPos, null, product.getSceneGeoCoding()); PlacemarkGroup placemarkGroup = placemarkDescriptor.getPlacemarkGroup(product); String defaultStyleCss = placemarkGroup.getVectorDataNode().getDefaultStyleCss(); if(newPlacemark.getStyleCss().isEmpty()) { newPlacemark.setStyleCss(defaultStyleCss); } placemarkGroup.add(newPlacemark); UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product); if (undoManager != null) { undoManager.addEdit(UndoablePlacemarkActionFactory.createUndoablePlacemarkInsertion(product, newPlacemark, placemarkDescriptor)); } } private Cursor createCursor() { final Image cursorImage = placemarkDescriptor.getCursorImage(); if (cursorImage == null) { return Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR); } return Toolkit.getDefaultToolkit().createCustomCursor(cursorImage, placemarkDescriptor.getCursorHotSpot(), placemarkDescriptor.getRoleName()); } 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; } }
6,161
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
InsertGcpInteractor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/InsertGcpInteractor.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.placemark; import org.esa.snap.core.datamodel.GcpDescriptor; /** * A tool used to create ground control points (single click), select (single click on a GCP) or * edit (double click on a GCP) the GCPs displayed in product scene view. */ public class InsertGcpInteractor extends InsertPlacemarkInteractor { public InsertGcpInteractor() { super(GcpDescriptor.getInstance()); } }
1,146
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
UndoablePlacemarkActionFactory.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/UndoablePlacemarkActionFactory.java
package org.esa.snap.rcp.placemark; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.PlacemarkGroup; import org.esa.snap.core.datamodel.Product; import javax.swing.undo.AbstractUndoableEdit; import java.util.List; /** * @author Tonio Fincke */ class UndoablePlacemarkActionFactory { static UndoablePlacemarkAction createUndoablePlacemarkRemoval(Product product, List<Placemark> placemarks, PlacemarkDescriptor placemarkDescriptor) { return new UndoablePlacemarkAction(new UndoablePlacemarkRemovalStrategy(product, placemarks, placemarkDescriptor)); } static UndoablePlacemarkAction createUndoablePlacemarkInsertion(Product product, Placemark placemark, PlacemarkDescriptor placemarkDescriptor) { return new UndoablePlacemarkAction(new UndoablePlacemarkInsertionStrategy(product, placemark, placemarkDescriptor)); } static UndoablePlacemarkAction createUndoablePlacemarkCopying(Product product, Placemark placemark, PlacemarkDescriptor placemarkDescriptor) { return new UndoablePlacemarkAction(new UndoablePlacemarkCopyingStrategy(product, placemark, placemarkDescriptor)); } static UndoablePlacemarkAction createUndoablePlacemarkEditing(Product product, Placemark oldPlacemark, Placemark newPlacemark, PlacemarkDescriptor placemarkDescriptor) { return new UndoablePlacemarkAction(new UndoablePlacemarkEditingStrategy(product, oldPlacemark, newPlacemark, placemarkDescriptor)); } private static class UndoablePlacemarkAction extends AbstractUndoableEdit { private UndoablePlacemarkActionStrategy strategy; public UndoablePlacemarkAction(UndoablePlacemarkActionStrategy strategy) { this.strategy = strategy; } @Override public void undo() { super.undo(); strategy.undo(); } @Override public void redo() { super.redo(); strategy.redo(); } @Override public String getPresentationName() { return strategy.getPresentationName(); } @Override public void die() { super.die(); strategy = null; } } private interface UndoablePlacemarkActionStrategy { void undo(); void redo(); String getPresentationName(); } private static class UndoablePlacemarkInsertionStrategy implements UndoablePlacemarkActionStrategy { private Product product; private Placemark newPlacemark; private PlacemarkDescriptor placemarkDescriptor; UndoablePlacemarkInsertionStrategy(Product product, Placemark newPlacemark, PlacemarkDescriptor placemarkDescriptor) { this.product = product; this.newPlacemark = newPlacemark; this.placemarkDescriptor = placemarkDescriptor; } @Override public void undo() { placemarkDescriptor.getPlacemarkGroup(product).remove(newPlacemark); } @Override public void redo() { placemarkDescriptor.getPlacemarkGroup(product).add(newPlacemark); } @Override public String getPresentationName() { return "Insert " + placemarkDescriptor.getRoleLabel(); } } private static class UndoablePlacemarkCopyingStrategy implements UndoablePlacemarkActionStrategy { private Product product; private Placemark newPlacemark; private PlacemarkDescriptor placemarkDescriptor; UndoablePlacemarkCopyingStrategy(Product product, Placemark newPlacemark, PlacemarkDescriptor placemarkDescriptor) { this.product = product; this.newPlacemark = newPlacemark; this.placemarkDescriptor = placemarkDescriptor; } @Override public void undo() { placemarkDescriptor.getPlacemarkGroup(product).remove(newPlacemark); } @Override public void redo() { placemarkDescriptor.getPlacemarkGroup(product).add(newPlacemark); } @Override public String getPresentationName() { return "Copying " + placemarkDescriptor.getRoleLabel(); } } //todo does not work satisfyingly yet -> placemarks are added to the end of the table private static class UndoablePlacemarkEditingStrategy implements UndoablePlacemarkActionStrategy { private final Placemark oldPlacemark; private Product product; private Placemark newPlacemark; private Placemark placemarkInView; private PlacemarkDescriptor placemarkDescriptor; UndoablePlacemarkEditingStrategy(Product product, Placemark oldPlacemark, Placemark newPlacemark, PlacemarkDescriptor placemarkDescriptor) { this.product = product; this.oldPlacemark = oldPlacemark; this.newPlacemark = Placemark.createPointPlacemark(newPlacemark.getDescriptor(), newPlacemark.getName(), newPlacemark.getLabel(), newPlacemark.getDescription(), newPlacemark.getPixelPos(), newPlacemark.getGeoPos(), newPlacemark.getProduct().getSceneGeoCoding()); placemarkInView = newPlacemark; this.placemarkDescriptor = placemarkDescriptor; } @Override public void undo() { placemarkInView.setName(oldPlacemark.getName()); placemarkInView.setLabel(oldPlacemark.getLabel()); placemarkInView.setDescription(oldPlacemark.getDescription()); placemarkInView.setGeoPos(oldPlacemark.getGeoPos()); placemarkInView.setStyleCss(oldPlacemark.getStyleCss()); } @Override public void redo() { placemarkInView.setName(newPlacemark.getName()); placemarkInView.setLabel(newPlacemark.getLabel()); placemarkInView.setDescription(newPlacemark.getDescription()); placemarkInView.setGeoPos(newPlacemark.getGeoPos()); placemarkInView.setStyleCss(newPlacemark.getStyleCss()); } @Override public String getPresentationName() { return "Editing " + placemarkDescriptor.getRoleLabel(); } } private static class UndoablePlacemarkRemovalStrategy implements UndoablePlacemarkActionStrategy { private final List<Placemark> placemarks; private Product product; private PlacemarkDescriptor placemarkDescriptor; UndoablePlacemarkRemovalStrategy(Product product, List<Placemark> placemarks, PlacemarkDescriptor placemarkDescriptor) { this.product = product; this.placemarks = placemarks; this.placemarkDescriptor = placemarkDescriptor; } @Override public void undo() { final PlacemarkGroup placemarkGroup = placemarkDescriptor.getPlacemarkGroup(product); for (Placemark placemark : placemarks) { placemarkGroup.add(placemark); } } @Override public void redo() { final PlacemarkGroup placemarkGroup = placemarkDescriptor.getPlacemarkGroup(product); for (Placemark placemark : placemarks) { placemarkGroup.remove(placemark); } } @Override public String getPresentationName() { return "Removing " + placemarkDescriptor.getRoleLabel(); } } }
8,139
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
InsertPinInteractor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/InsertPinInteractor.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.placemark; import org.esa.snap.core.datamodel.PinDescriptor; /** * A tool used to create (single click), select (single click on a pin) or edit (double click on a pin) the pins * displayed in product scene view. */ public class InsertPinInteractor extends InsertPlacemarkInteractor { public InsertPinInteractor() { super(PinDescriptor.getInstance()); } }
1,123
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PlacemarkManagerButtons.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/PlacemarkManagerButtons.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.placemark; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.help.HelpDisplayer; import org.esa.snap.ui.tool.ToolButtonFactory; import javax.swing.AbstractButton; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; public class PlacemarkManagerButtons extends JPanel { private final AbstractButton newButton; private final AbstractButton copyButton; private final AbstractButton editButton; private final AbstractButton removeButton; private final AbstractButton importButton; private final AbstractButton exportButton; private final AbstractButton filterButton; private final AbstractButton exportTableButton; private final AbstractButton zoomToPlacemarkButton; private final AbstractButton transferPlacemarkButton; public PlacemarkManagerButtons(final PlacemarkManagerTopComponent topComponent) { super(new GridBagLayout()); newButton = createButton("icons/New24.gif"); newButton.setName("newButton"); final String placemarkLabel = topComponent.getPlacemarkDescriptor().getRoleLabel(); newButton.setToolTipText("Create and add new " + placemarkLabel + "."); /*I18N*/ newButton.addActionListener(e -> topComponent.newPin()); copyButton = createButton("icons/Copy24.gif"); copyButton.setName("copyButton"); copyButton.setToolTipText("Copy an existing " + placemarkLabel + "."); /*I18N*/ copyButton.addActionListener(e -> topComponent.copyActivePlacemark()); editButton = createButton("icons/Edit24.gif"); editButton.setName("editButton"); editButton.setToolTipText("Edit selected " + placemarkLabel + "."); /*I18N*/ editButton.addActionListener(e -> topComponent.editActivePin()); removeButton = createButton("icons/Remove24.gif"); removeButton.setName("removeButton"); removeButton.setToolTipText("Remove selected " + placemarkLabel + "."); /*I18N*/ removeButton.addActionListener(e -> topComponent.removeSelectedPins()); importButton = createButton("icons/Import24.gif"); importButton.setName("importButton"); importButton.setToolTipText("Import all " + placemarkLabel + "s from XML or text file."); /*I18N*/ importButton.addActionListener(e -> { topComponent.importPlacemarks(true); topComponent.updateUIState(); }); exportButton = createButton("icons/Export24.gif"); exportButton.setName("exportButton"); exportButton.setToolTipText("Export selected " + placemarkLabel + "s to XML file."); /*I18N*/ exportButton.addActionListener(e -> { topComponent.exportPlacemarks(); topComponent.updateUIState(); }); filterButton = createButton("icons/Filter24.gif"); filterButton.setName("filterButton"); filterButton.setToolTipText("Filter pixel data to be displayed in table."); /*I18N*/ filterButton.addActionListener(e -> { topComponent.applyFilteredGrids(); topComponent.updateUIState(); }); exportTableButton = createButton("icons/ExportTable.gif"); exportTableButton.setName("exportTableButton"); exportTableButton.setToolTipText("Export selected data to flat text file."); /*I18N*/ exportTableButton.addActionListener(e -> { topComponent.exportPlacemarkDataTable(); topComponent.updateUIState(); }); zoomToPlacemarkButton = createButton("icons/ZoomTo24.gif"); zoomToPlacemarkButton.setName("zoomToButton"); zoomToPlacemarkButton.setToolTipText("Zoom to selected " + placemarkLabel + "."); /*I18N*/ zoomToPlacemarkButton.addActionListener(e -> topComponent.zoomToActivePin()); transferPlacemarkButton = createButton("icons/MultiAssignProducts24.gif"); transferPlacemarkButton.setName("transferButton"); transferPlacemarkButton.setToolTipText("Transfer the selected " + placemarkLabel + "s to other products."); transferPlacemarkButton.addActionListener(e -> topComponent.transferPlacemarks()); final AbstractButton helpButton = createButton("icons/Help22.png"); helpButton.setToolTipText("Help."); /*I18N*/ helpButton.setName("helpButton"); helpButton.addActionListener(e -> HelpDisplayer.show(topComponent.getHelpCtx())); final GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 1; gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 0.5; gbc.gridy++; add(newButton, gbc); add(copyButton, gbc); gbc.gridy++; add(editButton, gbc); add(removeButton, gbc); gbc.gridy++; add(importButton, gbc); add(exportButton, gbc); gbc.gridy++; add(filterButton, gbc); add(exportTableButton, gbc); gbc.gridy++; add(zoomToPlacemarkButton, gbc); add(transferPlacemarkButton, gbc); gbc.gridy++; gbc.fill = GridBagConstraints.VERTICAL; gbc.weighty = 1.0; gbc.gridwidth = 2; add(new JLabel(" "), gbc); // filler gbc.fill = GridBagConstraints.NONE; gbc.weighty = 0.0; gbc.gridx = 1; gbc.gridy++; gbc.gridwidth = 1; add(helpButton, gbc); } void updateUIState(final boolean productSelected, int numPins, final int numSelectedPins) { boolean pinsAvailable = numPins > 0; boolean hasSelectedPins = numSelectedPins > 0; boolean hasActivePin = numSelectedPins == 1; newButton.setEnabled(productSelected); copyButton.setEnabled(hasActivePin); editButton.setEnabled(hasActivePin); removeButton.setEnabled(hasSelectedPins); zoomToPlacemarkButton.setEnabled(hasActivePin); transferPlacemarkButton.setEnabled(pinsAvailable && SnapApp.getDefault().getProductManager().getProductCount() > 1); importButton.setEnabled(productSelected); exportButton.setEnabled(pinsAvailable); exportTableButton.setEnabled(pinsAvailable); filterButton.setEnabled(productSelected); } private static AbstractButton createButton(String path) { return ToolButtonFactory.createButton(UIUtils.loadImageIcon(path), false); } }
7,209
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PlacemarkViewTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/PlacemarkViewTopComponent.java
package org.esa.snap.rcp.placemark; import eu.esa.snap.netbeans.docwin.DocumentTopComponent; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.ui.product.ProductPlacemarkView; import java.awt.*; public class PlacemarkViewTopComponent extends DocumentTopComponent<VectorDataNode, ProductPlacemarkView> { private final ProductPlacemarkView placemarkView; public PlacemarkViewTopComponent(VectorDataNode document) { super(document); updateDisplayName(); setName(getDisplayName()); placemarkView = new ProductPlacemarkView(document); setLayout(new BorderLayout()); add(placemarkView, BorderLayout.CENTER); } @Override public ProductPlacemarkView getView() { return placemarkView; } private void updateDisplayName() { setDisplayName(WindowUtilities.getUniqueTitle(getDocument().getDisplayName(), PlacemarkViewTopComponent.class)); } }
1,023
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PlacemarkDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/PlacemarkDialog.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.placemark; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyPane; 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.PinDescriptor; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.util.Guardian; import org.esa.snap.core.util.StringUtils; import org.esa.snap.ui.ModalDialog; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.operation.TransformException; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Window; import java.beans.PropertyChangeListener; /** * A dialog used to create new placemarks or edit existing placemarks. */ public class PlacemarkDialog extends ModalDialog { private final static String PROPERTY_NAME_NAME = "name"; private final static String PROPERTY_NAME_LABEL = "label"; private final static String PROPERTY_NAME_DESCRIPTION = "description"; private final static String PROPERTY_NAME_STYLE_CSS = "styleCss"; private final static String PROPERTY_NAME_LAT = "lat"; private final static String PROPERTY_NAME_LON = "lon"; private final static String PROPERTY_NAME_PIXEL_X = "pixelX"; private final static String PROPERTY_NAME_PIXEL_Y = "pixelY"; private final static String PROPERTY_NAME_USE_PIXEL_POS = "usePixelPos"; private final Product product; private final boolean canGetPixelPos; private final boolean canGetGeoPos; private final PlacemarkDescriptor placemarkDescriptor; private final BindingContext bindingContext; private boolean adjusting; public PlacemarkDialog(final Window parent, final Product product, final PlacemarkDescriptor placemarkDescriptor, boolean switchGeoAndPixelPositionsEditable) { super(parent, "New " + placemarkDescriptor.getRoleLabel(), ModalDialog.ID_OK_CANCEL, null); /*I18N*/ Guardian.assertNotNull("product", product); this.product = product; this.placemarkDescriptor = placemarkDescriptor; bindingContext = new BindingContext(); final GeoCoding geoCoding = this.product.getSceneGeoCoding(); final boolean hasGeoCoding = geoCoding != null; canGetPixelPos = hasGeoCoding && geoCoding.canGetPixelPos(); canGetGeoPos = hasGeoCoding && geoCoding.canGetGeoPos(); boolean usePixelPos = !hasGeoCoding && switchGeoAndPixelPositionsEditable; PropertySet propertySet = bindingContext.getPropertySet(); propertySet.addProperties(Property.create(PROPERTY_NAME_NAME, ""), Property.create(PROPERTY_NAME_LABEL, ""), Property.create(PROPERTY_NAME_DESCRIPTION, ""), Property.create(PROPERTY_NAME_STYLE_CSS, ""), Property.create(PROPERTY_NAME_LAT, 0.0), Property.create(PROPERTY_NAME_LON, 0.0), Property.create(PROPERTY_NAME_PIXEL_X, 0.0), Property.create(PROPERTY_NAME_PIXEL_Y, 0.0), Property.create(PROPERTY_NAME_USE_PIXEL_POS, usePixelPos) ); propertySet.getProperty(PROPERTY_NAME_USE_PIXEL_POS).getDescriptor().setAttribute("enabled", hasGeoCoding && switchGeoAndPixelPositionsEditable); propertySet.getProperty(PROPERTY_NAME_LAT).getDescriptor().setDisplayName("Latitude"); propertySet.getProperty(PROPERTY_NAME_LAT).getDescriptor().setUnit("deg"); propertySet.getProperty(PROPERTY_NAME_LON).getDescriptor().setDisplayName("Longitude"); propertySet.getProperty(PROPERTY_NAME_LON).getDescriptor().setUnit("deg"); propertySet.getProperty(PROPERTY_NAME_PIXEL_X).getDescriptor().setDisplayName("Pixel X"); propertySet.getProperty(PROPERTY_NAME_PIXEL_X).getDescriptor().setUnit("pixels"); propertySet.getProperty(PROPERTY_NAME_PIXEL_Y).getDescriptor().setDisplayName("Pixel Y"); propertySet.getProperty(PROPERTY_NAME_PIXEL_Y).getDescriptor().setUnit("pixels"); PropertyChangeListener geoChangeListener = evt -> updatePixelPos(); propertySet.getProperty(PROPERTY_NAME_LAT).addPropertyChangeListener(geoChangeListener); propertySet.getProperty(PROPERTY_NAME_LON).addPropertyChangeListener(geoChangeListener); PropertyChangeListener pixelChangeListener = evt -> updateGeoPos(); propertySet.getProperty(PROPERTY_NAME_PIXEL_X).addPropertyChangeListener(pixelChangeListener); propertySet.getProperty(PROPERTY_NAME_PIXEL_Y).addPropertyChangeListener(pixelChangeListener); /* symbolLabel = new JLabel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); if (g instanceof Graphics2D) { Graphics2D g2d = (Graphics2D) g; final PixelPos refPoint = symbol.getRefPoint(); Rectangle2D bounds = symbol.getBounds(); double tx = refPoint.getX() - bounds.getX() / 2; double ty = refPoint.getY() - bounds.getY() / 2; g2d.translate(tx, ty); symbol.draw(g2d); g2d.translate(-tx, -ty); } } }; symbolLabel.setPreferredSize(new Dimension(40, 40)); */ final JPanel panel = new PropertyPane(bindingContext).createPanel(); final JPanel content = new JPanel(new BorderLayout()); content.add(panel, BorderLayout.CENTER); content.add(new JLabel("Pixel position is given in product raster coordinates"), BorderLayout.SOUTH); setContent(content); if (switchGeoAndPixelPositionsEditable) { bindingContext.bindEnabledState(PROPERTY_NAME_LAT, false, PROPERTY_NAME_USE_PIXEL_POS, true); bindingContext.bindEnabledState(PROPERTY_NAME_LON, false, PROPERTY_NAME_USE_PIXEL_POS, true); bindingContext.bindEnabledState(PROPERTY_NAME_PIXEL_X, true, PROPERTY_NAME_USE_PIXEL_POS, true); bindingContext.bindEnabledState(PROPERTY_NAME_PIXEL_Y, true, PROPERTY_NAME_USE_PIXEL_POS, true); } } public Product getProduct() { return product; } @Override protected void onOK() { if (ProductNode.isValidNodeName(getName())) { super.onOK(); } else { showInformationDialog("'" + getName() + "' is not a valid " + placemarkDescriptor.getRoleLabel() + " name."); /*I18N*/ } } public String getName() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_NAME); } public void setName(String name) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_NAME, name); } public String getLabel() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_LABEL); } public void setLabel(String label) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_LABEL, label); } public String getDescription() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_DESCRIPTION); } public void setDescription(String description) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_DESCRIPTION, description); } public String getStyleCss() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_STYLE_CSS); } private void setStyleCss(String styleCss) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_STYLE_CSS, styleCss); } public double getPixelX() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_PIXEL_X); } public void setPixelX(double pixelX) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_PIXEL_X, pixelX); } public double getPixelY() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_PIXEL_Y); } public void setPixelY(double pixelY) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_PIXEL_Y, pixelY); } public double getLat() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_LAT); } public void setLat(double lat) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_LAT, lat); } public double getLon() { return bindingContext.getPropertySet().getValue(PROPERTY_NAME_LON); } public void setLon(double lon) { bindingContext.getPropertySet().setValue(PROPERTY_NAME_LON, lon); } public GeoPos getGeoPos() { return new GeoPos(getLat(), getLon()); } public void setGeoPos(GeoPos geoPos) { if (geoPos != null) { setLat(geoPos.lat); setLon(geoPos.lon); } else { setLat(0.0F); setLon(0.0F); } } public PixelPos getPixelPos() { return new PixelPos(getPixelX(), getPixelY()); } public void setPixelPos(PixelPos pixelPos) { if (pixelPos != null) { setPixelX(pixelPos.x); setPixelY(pixelPos.y); } else { setPixelX(0.0F); setPixelY(0.0F); } } private void updatePixelPos() { if (canGetPixelPos && !adjusting) { adjusting = true; PixelPos pixelPos = placemarkDescriptor.updatePixelPos(product.getSceneGeoCoding(), getGeoPos(), getPixelPos()); setPixelPos(pixelPos); adjusting = false; } } private void updateGeoPos() { if (canGetGeoPos && !adjusting) { adjusting = true; GeoPos geoPos = placemarkDescriptor.updateGeoPos(product.getSceneGeoCoding(), getPixelPos(), getGeoPos()); setGeoPos(geoPos); adjusting = false; } } /** * Shows a dialog to edit the properties of an placemark. * If the placemark does not belong to a product it will be added after editing. * * @param parent the parent window fo the dialog * @param product the product where the placemark is already contained or where it will be added * @param placemark the placemark to edit * @param placemarkDescriptor the descriptor of the placemark * @return <code>true</code> if editing was successful, otherwise <code>false</code>. */ public static boolean showEditPlacemarkDialog(Window parent, Product product, Placemark placemark, PlacemarkDescriptor placemarkDescriptor) { final PlacemarkDialog dialog = new PlacemarkDialog(parent, product, placemarkDescriptor, placemarkDescriptor instanceof PinDescriptor); boolean belongsToProduct = placemark.getProduct() != null; String titlePrefix = belongsToProduct ? "Edit" : "New"; String roleLabel = StringUtils.firstLetterUp(placemarkDescriptor.getRoleLabel()); dialog.getJDialog().setTitle(titlePrefix + " " + roleLabel); dialog.getJDialog().setName(titlePrefix + "_" + roleLabel); dialog.setName(placemark.getName()); dialog.setLabel(placemark.getLabel()); dialog.setDescription(placemark.getDescription() != null ? placemark.getDescription() : ""); // prevent that geoPos change updates pixelPos and vice versa during dialog creation dialog.adjusting = true; dialog.setPixelPos(placemark.getPixelPos()); GeoPos geoPos = placemark.getGeoPos(); dialog.setGeoPos(geoPos != null ? geoPos : new GeoPos(Float.NaN, Float.NaN)); dialog.adjusting = false; dialog.setStyleCss(placemark.getStyleCss()); boolean ok = (dialog.show() == ID_OK); if (ok) { placemark.setName(dialog.getName()); placemark.setLabel(dialog.getLabel()); placemark.setDescription(dialog.getDescription()); placemark.setStyleCss(dialog.getStyleCss()); if (!belongsToProduct) { // must add to product, otherwise setting the pixel position basied on geo position wil fail placemarkDescriptor.getPlacemarkGroup(product).add(placemark); } placemark.setGeoPos(dialog.getGeoPos()); } return ok; } public static void main(String[] args) throws TransformException, FactoryException { Product product1 = new Product("A", "B", 360, 180); product1.setSceneGeoCoding(new CrsGeoCoding(DefaultGeographicCRS.WGS84, 360, 180, -180.0, 90.0, 1.0, 1.0, 0.0, 0.0)); PinDescriptor descriptor = PinDescriptor.getInstance(); Placemark pin1 = Placemark.createPointPlacemark(descriptor, "pin_1", "Pin 1", "Schnatter!", new PixelPos(0, 0), new GeoPos(), product1.getSceneGeoCoding()); product1.getPinGroup().add(pin1); showEditPlacemarkDialog(null, product1, pin1, descriptor); } }
14,342
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PlacemarkUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/PlacemarkUtils.java
package org.esa.snap.rcp.placemark; import com.bc.ceres.swing.figure.Figure; import com.bc.ceres.swing.figure.FigureCollection; import com.bc.ceres.swing.figure.support.DefaultFigureStyle; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.ui.product.SimpleFeaturePointFigure; import org.opengis.feature.simple.SimpleFeature; import java.awt.Color; public class PlacemarkUtils { public static Color getPlacemarkColor(Placemark placemark) { return getPlacemarkColor(placemark, SnapApp.getDefault().getSelectedProductSceneView()); } public static Color getPlacemarkColor(Placemark placemark, ProductSceneView view) { final String styleCss = placemark.getStyleCss(); if (styleCss.contains(DefaultFigureStyle.FILL_COLOR.getName())) { return DefaultFigureStyle.createFromCss(styleCss).getFillColor(); } final Figure[] figures = getFigures(view); for (Figure figure : figures) { if (figure instanceof SimpleFeaturePointFigure) { final SimpleFeature simpleFeature = ((SimpleFeaturePointFigure) figure).getSimpleFeature(); if (simpleFeature.getID().equals(placemark.getName())) { return figure.getNormalStyle().getFillColor(); } } } return Color.BLUE; } private static Figure[] getFigures(ProductSceneView view) { if (view == null) { return new Figure[0]; } final FigureCollection figureCollection = view.getFigureEditor().getFigureCollection(); return figureCollection.getFigures(); } }
1,721
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TableModelFactory.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/TableModelFactory.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.placemark; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.ui.product.AbstractPlacemarkTableModel; public interface TableModelFactory { AbstractPlacemarkTableModel createTableModel(PlacemarkDescriptor placemarkDescriptor, Product product, Band[] selectedBands, TiePointGrid[] selectedGrids); }
1,258
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductChooser.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/ProductChooser.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.placemark; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.Guardian; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; public class ProductChooser extends ModalDialog { private static final Font SMALL_PLAIN_FONT = new Font("SansSerif", Font.PLAIN, 10); private static final Font SMALL_ITALIC_FONT = SMALL_PLAIN_FONT.deriveFont(Font.ITALIC); private final Product[] allProducts; private Product[] selectedProducts; private int numSelected; private JCheckBox[] checkBoxes; private JCheckBox selectAllCheckBox; private JCheckBox selectNoneCheckBox; private final boolean selectAtLeastOneProduct; private boolean multipleProducts; public ProductChooser(Window parent, String title, String helpID, Product[] allProducts, Product[] selectedProducts) { super(parent, title, ModalDialog.ID_OK_CANCEL, helpID); Guardian.assertNotNull("allProducts", allProducts); this.allProducts = allProducts; this.selectedProducts = selectedProducts; selectAtLeastOneProduct = true; if (this.selectedProducts == null) { this.selectedProducts = new Product[0]; } multipleProducts = allProducts.length > 1; initUI(); } @Override public int show() { updateUI(); return super.show(); } private void initUI() { JPanel checkersPane = createCheckersPane(); selectAllCheckBox = new JCheckBox("Select all"); /*I18N*/ selectAllCheckBox.setMnemonic('a'); selectAllCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { select(true); } }); selectNoneCheckBox = new JCheckBox("Select none"); /*I18N*/ selectNoneCheckBox.setMnemonic('n'); selectNoneCheckBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { select(false); } }); final JPanel checkPane = new JPanel(new BorderLayout()); checkPane.add(selectAllCheckBox, BorderLayout.WEST); checkPane.add(selectNoneCheckBox, BorderLayout.CENTER); JScrollPane scrollPane = new JScrollPane(checkersPane); final Dimension preferredSize = checkersPane.getPreferredSize(); scrollPane.setPreferredSize(new Dimension(Math.min(preferredSize.width + 20, 400), Math.min(preferredSize.height + 40, 300))); final JLabel label = new JLabel("Target product(s):"); /*I18N*/ final JPanel content = GridBagUtils.createPanel(); final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints(); gbc.gridy = 1; gbc.fill = GridBagConstraints.BOTH; gbc.weighty = 0; content.add(label, gbc); gbc.gridy++; gbc.weighty = 1; gbc.weightx = 1; content.add(scrollPane, gbc); gbc.gridy++; gbc.weighty = 0; gbc.weightx = 0; content.add(checkPane, gbc); gbc.gridy++; gbc.insets.top = 20; setContent(content); } private JPanel createCheckersPane() { checkBoxes = new JCheckBox[allProducts.length]; final JPanel checkersPane = GridBagUtils.createPanel(); final GridBagConstraints gbc = GridBagUtils.createConstraints("insets.left=4,anchor=WEST,fill=HORIZONTAL"); final StringBuffer description = new StringBuffer(); addProductCheckers(description, checkersPane, gbc); return checkersPane; } private void addProductCheckers(final StringBuffer description, final JPanel checkersPane, final GridBagConstraints gbc) { final ActionListener checkListener = createActionListener(); for (int i = 0; i < allProducts.length; i++) { Product product = allProducts[i]; boolean checked = false; for (Product selectedProduct : selectedProducts) { if (product == selectedProduct) { checked = true; numSelected++; break; } } description.setLength(0); description.append(product.getDescription() == null ? "" : product.getDescription()); final JCheckBox check = new JCheckBox(getDisplayName(product), checked); check.setFont(SMALL_PLAIN_FONT); check.addActionListener(checkListener); final JLabel label = new JLabel(description.toString()); label.setFont(SMALL_ITALIC_FONT); gbc.gridy++; GridBagUtils.addToPanel(checkersPane, check, gbc, "weightx=0,gridx=0"); GridBagUtils.addToPanel(checkersPane, label, gbc, "weightx=1,gridx=1"); checkBoxes[i] = check; } } private String getDisplayName(Product rasterDataNode) { return multipleProducts ? rasterDataNode.getDisplayName() : rasterDataNode.getName(); } private ActionListener createActionListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { final JCheckBox check = (JCheckBox) e.getSource(); if (check.isSelected()) { numSelected++; } else { numSelected--; } updateUI(); } }; } private void select(boolean b) { for (JCheckBox checkBox : checkBoxes) { if (b && !checkBox.isSelected()) { numSelected++; } if (!b && checkBox.isSelected()) { numSelected--; } checkBox.setSelected(b); } updateUI(); } private void updateUI() { selectAllCheckBox.setSelected(numSelected == checkBoxes.length); selectAllCheckBox.setEnabled(numSelected < checkBoxes.length); selectAllCheckBox.updateUI(); selectNoneCheckBox.setSelected(numSelected == 0); selectNoneCheckBox.setEnabled(numSelected > 0); selectNoneCheckBox.updateUI(); } @Override protected boolean verifyUserInput() { final List<Product> products = new ArrayList<>(); for (int i = 0; i < checkBoxes.length; i++) { JCheckBox checkBox = checkBoxes[i]; if (checkBox.isSelected()) { products.add(allProducts[i]); } } selectedProducts = products.toArray(new Product[products.size()]); if (selectAtLeastOneProduct) { boolean result = selectedProducts.length > 0; if (!result) { showInformationDialog("No products selected.\n" + "Please select at least one product."); /*I18N*/ } return result; } return true; } public Product[] getSelectedProducts() { return selectedProducts; } }
8,230
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PlacemarkManagerTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/PlacemarkManagerTopComponent.java
package org.esa.snap.rcp.placemark; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.glayer.Layer; import com.bc.ceres.swing.selection.SelectionChangeEvent; import com.bc.ceres.swing.selection.SelectionChangeListener; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.dataio.placemark.PlacemarkData; import org.esa.snap.core.dataio.placemark.PlacemarkIO; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.Guardian; 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.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.rcp.util.SelectionSupport; import org.esa.snap.rcp.windows.ProductSceneViewTopComponent; import org.esa.snap.runtime.Config; import org.esa.snap.ui.*; import org.esa.snap.ui.color.ColorTableCellEditor; import org.esa.snap.ui.color.ColorTableCellRenderer; import org.esa.snap.ui.product.AbstractPlacemarkTableModel; import org.esa.snap.ui.product.BandChooser; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.ui.product.VectorDataLayer; import org.locationtech.jts.geom.Coordinate; import org.openide.awt.UndoRedo; import org.openide.util.HelpCtx; import org.openide.windows.TopComponent; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableColumnModel; import javax.swing.table.TableRowSorter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.io.*; import java.text.DecimalFormat; import java.text.MessageFormat; import java.util.List; import java.util.*; import java.util.prefs.Preferences; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.VIEW; /** * @author Tonio Fincke */ public class PlacemarkManagerTopComponent extends TopComponent implements UndoRedo.Provider, HelpCtx.Provider { public static final String PREFERENCE_KEY_PIN_IO_DIR = "pin.io.dir"; private static final String PREFERENCE_KEY_ADJUST_PIN_GEO_POS = Placemark.PREFERENCE_KEY_ADJUST_PIN_GEO_POS; private final PlacemarkDescriptor placemarkDescriptor; private final Preferences preferences; private SnapApp snapApp; private final HashMap<Product, Band[]> productToSelectedBands; private final HashMap<Product, TiePointGrid[]> productToSelectedGrids; private Product product; private JTable placemarkTable; private PlacemarkListener placemarkListener; private Band[] selectedBands; private TiePointGrid[] selectedGrids; private boolean synchronizingPlacemarkSelectedState; private AbstractPlacemarkTableModel placemarkTableModel; private PlacemarkManagerButtons buttonPane; private ProductSceneView currentView; private final SelectionChangeListener selectionChangeHandler; private final List<List<Placemark>> relatedPlacemarks; private final boolean adjustPinGeoPos; public PlacemarkManagerTopComponent(PlacemarkDescriptor placemarkDescriptor, TableModelFactory modelFactory) { this.placemarkDescriptor = placemarkDescriptor; snapApp = SnapApp.getDefault(); preferences = snapApp.getPreferences(); productToSelectedBands = new HashMap<>(50); productToSelectedGrids = new HashMap<>(50); placemarkTableModel = modelFactory.createTableModel(placemarkDescriptor, product, null, null); selectionChangeHandler = new ViewSelectionChangeHandler(); relatedPlacemarks = new ArrayList<>(); adjustPinGeoPos = Config.instance().preferences().getBoolean(PREFERENCE_KEY_ADJUST_PIN_GEO_POS, true); initUI(); setDisplayName(getTitle()); } public void initUI() { setLayout(new BorderLayout()); placemarkTable = new JTable(placemarkTableModel); placemarkTable.setRowSorter(new TableRowSorter<>(placemarkTableModel)); placemarkTable.setName("placemarkTable"); placemarkTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); placemarkTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); placemarkTable.setRowSelectionAllowed(true); // IMPORTANT: We set ReorderingAllowed=false, because we export the // table model AS IS to a flat text file. placemarkTable.getTableHeader().setReorderingAllowed(false); ToolTipSetter toolTipSetter = new ToolTipSetter(); placemarkTable.addMouseMotionListener(toolTipSetter); placemarkTable.addMouseListener(toolTipSetter); placemarkTable.addMouseListener(new PopupListener()); placemarkTable.getSelectionModel().addListSelectionListener(new PlacemarkTableSelectionHandler()); updateTableModel(); final TableColumnModel columnModel = placemarkTable.getColumnModel(); columnModel.addColumnModelListener(new ColumnModelListener()); JScrollPane tableScrollPane = new JScrollPane(placemarkTable); JPanel mainPane = new JPanel(new BorderLayout(4, 4)); mainPane.add(tableScrollPane, BorderLayout.CENTER); buttonPane = new PlacemarkManagerButtons(this); JPanel content = new JPanel(new BorderLayout(4, 4)); content.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); content.add(BorderLayout.CENTER, mainPane); content.add(BorderLayout.EAST, buttonPane); Component southExtension = getSouthExtension(); if (southExtension != null) { content.add(BorderLayout.SOUTH, southExtension); } content.setPreferredSize(new Dimension(420, 200)); setCurrentView(snapApp.getSelectedProductSceneView()); setProduct(snapApp.getSelectedProduct(VIEW)); snapApp.getSelectionSupport(ProductSceneView.class).addHandler(new ProductSceneViewSelectionChangeHandler()); snapApp.getProductManager().addListener(new ProductRemovedListener()); updateUIState(); add(content, BorderLayout.CENTER); } void applyFilteredGrids() { if (product != null) { Band[] allBands = product.getBands(); TiePointGrid[] allGrids = product.getTiePointGrids(); BandChooser bandChooser = new BandChooser(SwingUtilities.getWindowAncestor(this), "Available Bands And Tie Point Grids", getHelpId(), false, allBands, selectedBands, allGrids, selectedGrids, true); if (bandChooser.show() == ModalDialog.ID_OK) { selectedBands = bandChooser.getSelectedBands(); selectedGrids = bandChooser.getSelectedTiePointGrids(); productToSelectedBands.put(product, selectedBands); productToSelectedGrids.put(product, selectedGrids); updateTableModel(); } } } PlacemarkDescriptor getPlacemarkDescriptor() { return placemarkDescriptor; } private void setCurrentView(ProductSceneView sceneView) { if (sceneView != currentView) { if (currentView != null) { currentView.getSelectionContext().removeSelectionChangeListener(selectionChangeHandler); } currentView = sceneView; if (currentView != null) { currentView.getSelectionContext().addSelectionChangeListener(selectionChangeHandler); setProduct(currentView.getProduct()); } else { setProduct(null); } } } protected final Product getProduct() { return product; } public void setProduct(Product product) { if (this.product == product) { return; } Product oldProduct = this.product; if (oldProduct != null) { oldProduct.removeProductNodeListener(placemarkListener); } this.product = product; selectedBands = productToSelectedBands.get(this.product); selectedGrids = productToSelectedGrids.get(this.product); if (this.product != null) { if (placemarkListener == null) { placemarkListener = new PlacemarkListener(); } this.product.addProductNodeListener(placemarkListener); } updateTableModel(); updatePlacemarkTableSelectionFromView(); updateUIState(); } protected String getTitle() { return ""; } protected String getHelpId() { return null; } protected Component getSouthExtension() { return null; } private void updateTableModel() { placemarkTableModel.setProduct(product); placemarkTableModel.setSelectedBands(selectedBands); placemarkTableModel.setSelectedGrids(selectedGrids); addCellRenderer(placemarkTable.getColumnModel()); addCellEditor(placemarkTable.getColumnModel()); } protected void addCellRenderer(TableColumnModel columnModel) { columnModel.getColumn(0).setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("0.000"))); columnModel.getColumn(1).setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("0.000"))); columnModel.getColumn(2).setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("0.000000"))); columnModel.getColumn(3).setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("0.000000"))); columnModel.getColumn(4).setCellRenderer(new ColorTableCellRenderer()); columnModel.getColumn(5).setCellRenderer(new RightAlignmentTableCellRenderer()); } protected void addCellEditor(TableColumnModel columnModel) { final DecimalCellEditor pixelCellEditor = new DecimalCellEditor(); columnModel.getColumn(0).setCellEditor(pixelCellEditor); columnModel.getColumn(1).setCellEditor(pixelCellEditor); columnModel.getColumn(2).setCellEditor(new DecimalCellEditor(-180, 180)); columnModel.getColumn(3).setCellEditor(new DecimalCellEditor(-90, 90)); columnModel.getColumn(4).setCellEditor(new ColorTableCellEditor()); } private ProductSceneView getSceneView() { final ProductSceneView selectedProductSceneView = snapApp.getSelectedProductSceneView(); if (selectedProductSceneView == null && product != null) { final Band[] bands = product.getBands(); for (Band band : bands) { ProductSceneViewTopComponent productSceneViewTopComponent = getProductSceneViewTopComponent(band); if (productSceneViewTopComponent != null) { return productSceneViewTopComponent.getView(); } } final TiePointGrid[] tiePointGrids = product.getTiePointGrids(); for (TiePointGrid tiePointGrid : tiePointGrids) { ProductSceneViewTopComponent productSceneViewTopComponent = getProductSceneViewTopComponent(tiePointGrid); if (productSceneViewTopComponent != null) { return productSceneViewTopComponent.getView(); } } } return selectedProductSceneView; } //copied from TimeSeriesManagerForm private ProductSceneViewTopComponent getProductSceneViewTopComponent(RasterDataNode raster) { return WindowUtilities.getOpened(ProductSceneViewTopComponent.class) .filter(topComponent -> raster == topComponent.getView().getRaster()) .findFirst() .orElse(null); } private Placemark getPlacemarkAt(final int selectedRow) { Placemark placemark = null; if (product != null) { if (selectedRow > -1 && selectedRow < getPlacemarkGroup(product).getNodeCount()) { placemark = getPlacemarkGroup(product).get(selectedRow); } } return placemark; } void newPin() { Guardian.assertNotNull("product", product); String[] uniquePinNameAndLabel = PlacemarkNameFactory.createUniqueNameAndLabel(placemarkDescriptor, product); Placemark newPlacemark = Placemark.createPointPlacemark(placemarkDescriptor, uniquePinNameAndLabel[0], uniquePinNameAndLabel[1], "", new PixelPos(0, 0), null, product.getSceneGeoCoding()); if (PlacemarkDialog.showEditPlacemarkDialog( SwingUtilities.getWindowAncestor(this), product, newPlacemark, placemarkDescriptor)) { makePlacemarkNameUnique(newPlacemark); UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product); if (undoManager != null) { undoManager.addEdit(UndoablePlacemarkActionFactory.createUndoablePlacemarkInsertion(product, newPlacemark, placemarkDescriptor)); } updateUIState(); } } void copyActivePlacemark() { Guardian.assertNotNull("product", product); Placemark activePlacemark = getSelectedPlacemark(); Guardian.assertNotNull("activePlacemark", activePlacemark); Placemark newPlacemark = Placemark.createPointPlacemark(activePlacemark.getDescriptor(), "copy_of_" + activePlacemark.getName(), activePlacemark.getLabel(), activePlacemark.getDescription(), activePlacemark.getPixelPos(), activePlacemark.getGeoPos(), activePlacemark.getProduct().getSceneGeoCoding()); newPlacemark.setStyleCss(activePlacemark.getStyleCss()); if (PlacemarkDialog.showEditPlacemarkDialog( SwingUtilities.getWindowAncestor(this), product, newPlacemark, placemarkDescriptor)) { makePlacemarkNameUnique(newPlacemark); UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product); if (undoManager != null) { undoManager.addEdit(UndoablePlacemarkActionFactory.createUndoablePlacemarkCopying(product, newPlacemark, placemarkDescriptor)); } updateUIState(); } } private ProductNodeGroup<Placemark> getPlacemarkGroup(Product product) { return placemarkDescriptor.getPlacemarkGroup(product); } void editActivePin() { Guardian.assertNotNull("product", product); Placemark activePlacemark = getSelectedPlacemark(); Placemark originalPlacemark = Placemark.createPointPlacemark(activePlacemark.getDescriptor(), activePlacemark.getName(), activePlacemark.getLabel(), activePlacemark.getDescription(), activePlacemark.getPixelPos(), activePlacemark.getGeoPos(), activePlacemark.getProduct().getSceneGeoCoding()); Guardian.assertNotNull("activePlacemark", activePlacemark); if (PlacemarkDialog.showEditPlacemarkDialog(SwingUtilities.getWindowAncestor(this), product, activePlacemark, placemarkDescriptor)) { makePlacemarkNameUnique(activePlacemark); UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product); if (undoManager != null) { undoManager.addEdit(UndoablePlacemarkActionFactory.createUndoablePlacemarkEditing(product, originalPlacemark, activePlacemark, placemarkDescriptor)); } updateUIState(); } } void removeSelectedPins() { final List<Placemark> placemarks = getSelectedPlacemarks(); for (Placemark placemark : placemarks) { getPlacemarkGroup(product).remove(placemark); } int selectedRow = placemarkTable.getSelectedRow(); if (selectedRow >= getPlacemarkGroup(product).getNodeCount()) { selectedRow = getPlacemarkGroup(product).getNodeCount() - 1; } if (selectedRow >= 0) { placemarkTable.getSelectionModel().setSelectionInterval(selectedRow, selectedRow); } UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(product); if (undoManager != null) { undoManager.addEdit(UndoablePlacemarkActionFactory.createUndoablePlacemarkRemoval(product, placemarks, placemarkDescriptor)); } updateUIState(); } private int getNumSelectedPlacemarks() { int[] rowIndexes = placemarkTable.getSelectedRows(); return rowIndexes != null ? rowIndexes.length : 0; } private Placemark getSelectedPlacemark() { int rowIndex = placemarkTable.getSelectedRow(); if (rowIndex >= 0) { final int modelIndex = placemarkTable.convertRowIndexToModel(rowIndex); return placemarkTableModel.getPlacemarkAt(modelIndex); } return null; } private List<Placemark> getSelectedPlacemarks() { List<Placemark> placemarkList = new ArrayList<>(); int[] sortedRowIndexes = placemarkTable.getSelectedRows(); if (sortedRowIndexes != null) { for (int rowIndex : sortedRowIndexes) { int modelRowIndex = placemarkTable.convertRowIndexToModel(rowIndex); placemarkList.add(placemarkTableModel.getPlacemarkAt(modelRowIndex)); } } return placemarkList; } void zoomToActivePin() { Guardian.assertNotNull("product", product); Placemark activePlacemark = getSelectedPlacemark(); Guardian.assertNotNull("activePlacemark", activePlacemark); final ProductSceneView view = getSceneView(); //todo [Multisize_products] use scene raster transform here final Object placemarkGeometry = activePlacemark.getFeature().getDefaultGeometry(); if (placemarkGeometry != null && placemarkGeometry instanceof org.locationtech.jts.geom.Point) { final Coordinate coordinate = ((org.locationtech.jts.geom.Point) placemarkGeometry).getCoordinate(); final Point2D modelPos = new Point2D.Double(coordinate.x, coordinate.y); view.zoom(modelPos.getX(), modelPos.getY(), view.getZoomFactor()); updateUIState(); } } // }} Actions ///////////////////////////////////////////////////////////////////////////////////////////////// private void makePlacemarkNameUnique(Placemark newPlacemark) { if (makePlacemarkNameUnique0(newPlacemark, product)) { Dialogs.showWarning(MessageFormat.format("{0} has been renamed to ''{1}'',\n" + "because a {2} with the former name already exists.", StringUtils.firstLetterUp(placemarkDescriptor.getRoleLabel()), newPlacemark.getName(), placemarkDescriptor.getRoleLabel())); } } protected void updateUIState() { boolean productSelected = product != null; int numSelectedPins = 0; if (productSelected) { updatePlacemarkTableSelectionFromView(); numSelectedPins = getNumSelectedPlacemarks(); } placemarkTable.setEnabled(productSelected); buttonPane.updateUIState(productSelected, placemarkTable.getRowCount(), numSelectedPins); } private void updatePlacemarkTableSelectionFromView() { if (!synchronizingPlacemarkSelectedState) { try { synchronizingPlacemarkSelectedState = true; if (product != null) { Placemark[] placemarks = placemarkTableModel.getPlacemarks(); for (int i = 0; i < placemarks.length; i++) { if (i < placemarkTable.getRowCount()) { Placemark placemark = placemarks[i]; int sortedRowAt = placemarkTable.convertRowIndexToView(i); boolean selected = isPlacemarkSelectedInView(placemark); if (selected != placemarkTable.isRowSelected(sortedRowAt)) { if (selected) { placemarkTable.getSelectionModel().addSelectionInterval(sortedRowAt, sortedRowAt); } else { placemarkTable.getSelectionModel().removeSelectionInterval(sortedRowAt, sortedRowAt); } } } } } placemarkTable.revalidate(); placemarkTable.repaint(); } finally { synchronizingPlacemarkSelectedState = false; } } } void importPlacemarks(boolean allPlacemarks) { List<Placemark> placemarks; try { placemarks = loadPlacemarksFromFile(); } catch (IOException e) { e.printStackTrace(); Dialogs.showError(MessageFormat.format("I/O error, failed to import {0}s:\n{1}", /*I18N*/ placemarkDescriptor.getRoleLabel(), e.getMessage())); return; } if (placemarks.isEmpty()) { return; } addPlacemarksToProduct(placemarks, product, allPlacemarks); } void addPlacemarksToProduct(List<Placemark> placemarks, Product targetProduct, boolean allPlacemarks) { final GeoCoding geoCoding = targetProduct.getSceneGeoCoding(); final boolean canGetPixelPos = geoCoding != null && geoCoding.canGetPixelPos(); final boolean isPin = placemarkDescriptor instanceof PinDescriptor; int numPinsOutOfBounds = 0; int numPinsRenamed = 0; int numInvalids = 0; for (Placemark placemark : placemarks) { if (makePlacemarkNameUnique0(placemark, targetProduct)) { numPinsRenamed++; placemark = createTransferrablePlacemark(placemark, targetProduct); } PixelPos pixelPos = placemark.getPixelPos(); boolean productContainsPixelPos = targetProduct.containsPixel(pixelPos); if (!canGetPixelPos && isPin && !productContainsPixelPos) { numInvalids++; continue; } // from here on we only handle GCPs and valid Pins if (canGetPixelPos && adjustPinGeoPos) { pixelPos = placemarkDescriptor.updatePixelPos(geoCoding, placemark.getGeoPos(), pixelPos); } if (!productContainsPixelPos && isPin) { numPinsOutOfBounds++; } else { getPlacemarkGroup(targetProduct).add(placemark); if (adjustPinGeoPos) { placemark.setPixelPos(pixelPos); } else { placemark.setGeoPos(placemark.getGeoPos()); } } if (!allPlacemarks) { break; // import only the first one } } String intoProductMessage = ""; if (targetProduct != product) { intoProductMessage = "into product " + targetProduct.getDisplayName() + "\n"; } if (numInvalids > 0) { Dialogs.showWarning(MessageFormat.format( "One or more {0}s have not been imported,\n{1}because they can not be assigned to a product without a geo-coding.", placemarkDescriptor.getRoleLabel(), intoProductMessage)); } if (numPinsRenamed > 0) { Dialogs.showWarning(MessageFormat.format( "One or more {0}s have been renamed,\n{1}because their former names are already existing.", placemarkDescriptor.getRoleLabel(), intoProductMessage)); } if (numPinsOutOfBounds > 0) { if (numPinsOutOfBounds == placemarks.size()) { Dialogs.showError( MessageFormat.format( "No {0}s have been imported,\n{1}because their pixel positions\nare outside the product''s bounds.", placemarkDescriptor.getRoleLabel(), intoProductMessage) ); } else { Dialogs.showError( MessageFormat.format( "{0} {1}s have not been imported,\n{2}because their pixel positions\nare outside the product''s bounds.", numPinsOutOfBounds, placemarkDescriptor.getRoleLabel(), intoProductMessage) ); } } } private boolean isPlacemarkSelectedInView(Placemark placemark) { boolean selected = false; final ProductSceneView sceneView = getSceneView(); if (sceneView != null) { if (getPlacemarkDescriptor() instanceof PinDescriptor) { selected = sceneView.isPinSelected(placemark); } else { selected = sceneView.isGcpSelected(placemark); } } return selected; } private boolean makePlacemarkNameUnique0(Placemark placemark, Product targetProduct) { ProductNodeGroup<Placemark> placemarkGroup = getPlacemarkGroup(targetProduct); if (placemarkGroup.get(placemark.getName()) == placemark) { return false; } String name0 = placemark.getName(); String name = name0; String label0 = placemark.getLabel(); String label = label0; int id = 1; while (placemarkGroup.contains(name)) { if (placemarkGroup.get(name).getLabel().equals(label)) { label = label0 + "_" + id; } name = name0 + "_" + id; id++; } if (!name0.equals(name)) { placemark.setName(name); if (!label0.equals(label)) { placemark.setLabel(label); } return true; } return false; } private List<Placemark> loadPlacemarksFromFile() throws IOException { final SnapFileChooser fileChooser = new SnapFileChooser(); String roleLabel = StringUtils.firstLetterUp(placemarkDescriptor.getRoleLabel()); fileChooser.setDialogTitle("Import " + roleLabel + "s"); /*I18N*/ setComponentName(fileChooser, "Import"); fileChooser.addChoosableFileFilter(PlacemarkIO.createTextFileFilter()); fileChooser.setFileFilter(PlacemarkIO.createPlacemarkFileFilter()); fileChooser.setCurrentDirectory(getIODir()); int result = fileChooser.showOpenDialog(SwingUtilities.getWindowAncestor(this)); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (file != null) { setIODir(file.getAbsoluteFile().getParentFile()); GeoCoding geoCoding = null; if (product != null) { geoCoding = product.getSceneGeoCoding(); } return PlacemarkIO.readPlacemarks(new FileReader(file), geoCoding, placemarkDescriptor); } } return Collections.emptyList(); } void exportPlacemarks() { final SnapFileChooser fileChooser = new SnapFileChooser(); fileChooser.setDialogTitle(MessageFormat.format("Export {0}(s)", StringUtils.firstLetterUp(placemarkDescriptor.getRoleLabel()))); setComponentName(fileChooser, "Export_Selected"); fileChooser.addChoosableFileFilter(PlacemarkIO.createTextFileFilter()); fileChooser.addChoosableFileFilter(PlacemarkIO.createKmzFileFilter()); fileChooser.setFileFilter(PlacemarkIO.createPlacemarkFileFilter()); final File ioDir = getIODir(); fileChooser.setCurrentDirectory(ioDir); fileChooser.setSelectedFile(new File(ioDir, placemarkDescriptor.getRoleName())); int result = fileChooser.showSaveDialog(SwingUtilities.getWindowAncestor(this)); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (file != null) { if (Boolean.TRUE.equals(Dialogs.requestOverwriteDecision(getTitle(), file))) { setIODir(file.getAbsoluteFile().getParentFile()); SnapFileFilter snapFileFilter = fileChooser.getSnapFileFilter(); String fileExtension = FileUtils.getExtension(file); if (fileExtension == null || !StringUtils.contains(snapFileFilter.getExtensions(), fileExtension)) { file = FileUtils.ensureExtension(file, snapFileFilter.getDefaultExtension()); } try { String formatName = snapFileFilter.getFormatName(); if (formatName.equals(PlacemarkIO.createPlacemarkFileFilter().getFormatName())) { try (FileWriter writer = new FileWriter(file)) { final List<Placemark> placemarkList = getPlacemarksForExport(); PlacemarkIO.writePlacemarksFile(writer, placemarkList); } } else if (formatName.equals(PlacemarkIO.createTextFileFilter().getFormatName())) { try (Writer writer = new FileWriter(file)) { writePlacemarkDataTableText(writer); } } else if (formatName.equals(PlacemarkIO.createKmzFileFilter().getFormatName())) { try (OutputStream outStream = new FileOutputStream(file)) { final List<Placemark> placemarkList = getPlacemarksForExport(); List<PlacemarkData> placemarkData = getExtraDataFromTable(placemarkList); PlacemarkIO.writePlacemarkKmzFile(outStream, placemarkData, ProgressMonitor.NULL); } } else { Dialogs.showError(String.format("Unknown export format '%s'. Nothing has been exported.", formatName)); } } catch (IOException ioe) { Dialogs.showError(String.format("I/O Error.\n Failed to export %ss.\n%s", placemarkDescriptor.getRoleLabel(), ioe.getMessage())); ioe.printStackTrace(); } } } } } private List<PlacemarkData> getExtraDataFromTable(List<Placemark> placemarkList) { List<PlacemarkData> list = new ArrayList<>(); String[] additionalColumnNames = placemarkTableModel.getAdditionalColumnNames(); for (int rowIndex = 0; rowIndex < placemarkTableModel.getRowCount(); rowIndex++) { Placemark placemark = placemarkTableModel.getPlacemarkAt(rowIndex); if (placemarkList.contains(placemark)) { Map<String, Object> extraData = new LinkedHashMap<>(); for (String additionalColumnName : additionalColumnNames) { int columnIndex = placemarkTableModel.getColumnIndex(additionalColumnName); if (columnIndex >= 0) { Object valueAt = placemarkTableModel.getValueAt(rowIndex, columnIndex); extraData.put(additionalColumnName, valueAt); } } list.add(new PlacemarkData(placemark, extraData.isEmpty() ? null : extraData)); } } return list; } private List<Placemark> getPlacemarksForExport() { boolean noPlacemarksSelected = placemarkTable.getSelectionModel().isSelectionEmpty(); final List<Placemark> placemarkList; if (noPlacemarksSelected) { placemarkList = Arrays.asList(placemarkTableModel.getPlacemarks()); } else { placemarkList = getSelectedPlacemarks(); } return placemarkList; } void transferPlacemarks() { // ask for destination product Product thisProduct = getProduct(); Product[] allProducts = snapApp.getProductManager().getProducts(); if (allProducts.length < 2 || thisProduct == null) { return; } Product[] allOtherProducts = new Product[allProducts.length - 1]; int allOtherProductsIndex = 0; for (Product product : allProducts) { if (product != thisProduct) { allOtherProducts[allOtherProductsIndex++] = product; } } ProductChooser productChooser = new ProductChooser( snapApp.getMainFrame(), getTitle(), getHelpId(), allOtherProducts, null); int buttonID = productChooser.show(); System.out.println("buttonID = " + buttonID); if (buttonID == AbstractDialog.ID_OK) { // copy placemarks List<Placemark> placemarks = getPlacemarksForExport(); Product[] selectedProducts = productChooser.getSelectedProducts(); boolean notAlreadyAsked = true; boolean updateExistingPins = true; for (Product selectedProduct : selectedProducts) { List<Placemark> placemarksCopy = new ArrayList<>(placemarks.size()); for (Placemark placemark : placemarks) { Placemark[] existingPlacemarks = getExistingPlacemarks(placemark, selectedProduct); if (existingPlacemarks.length > 0) { if (notAlreadyAsked) { notAlreadyAsked = false; Dialogs.Answer decision = Dialogs.requestDecision("Transfer placemarks", "Do you want to update existing placemarks?", false, null); updateExistingPins = decision == Dialogs.Answer.YES; } if (updateExistingPins) { for (Placemark existingPlacemark : existingPlacemarks) { existingPlacemark.setName(placemark.getName()); existingPlacemark.setLabel(placemark.getLabel()); existingPlacemark.setDescription(placemark.getDescription()); existingPlacemark.setPixelPos(placemark.getPixelPos()); existingPlacemark.setGeoPos(placemark.getGeoPos()); existingPlacemark.setStyleCss(placemark.getStyleCss()); } } else { Placemark placemarkToTransfer = createTransferrablePlacemark(placemark, selectedProduct); placemarksCopy.add(placemarkToTransfer); setRelatedPlacemark(placemark, placemarkToTransfer); } } else { Placemark placemarkToTransfer = createTransferrablePlacemark(placemark, selectedProduct); placemarksCopy.add(placemarkToTransfer); setRelatedPlacemark(placemark, placemarkToTransfer); } } addPlacemarksToProduct(placemarksCopy, selectedProduct, true); } } } private Placemark createTransferrablePlacemark(Placemark placemark, Product product) { Placemark newPlacemark = Placemark.createPointPlacemark(placemark.getDescriptor(), placemark.getName(), placemark.getLabel(), placemark.getDescription(), placemark.getPixelPos(), placemark.getGeoPos(), product.getSceneGeoCoding()); newPlacemark.setStyleCss(placemark.getStyleCss()); return newPlacemark; } private Placemark[] getExistingPlacemarks(Placemark referencePlacemark, Product product) { List<Placemark> associatedPlacemarksList = new ArrayList<>(); for (List<Placemark> relatedPlacemarkList : relatedPlacemarks) { for (Placemark placemark : relatedPlacemarkList) { if (placemark == referencePlacemark) { for (Placemark placemarkCandidate : relatedPlacemarkList) { if (placemarkCandidate.getProduct() == product) { associatedPlacemarksList.add(placemarkCandidate); } } } } } return associatedPlacemarksList.toArray(new Placemark[associatedPlacemarksList.size()]); } private void setRelatedPlacemark(Placemark originalPlacemark, Placemark newPlacemark) { boolean added = false; for (List<Placemark> relatedPlacemarkList : relatedPlacemarks) { for (int j = 0; j < relatedPlacemarkList.size(); j++) { Placemark placemark = relatedPlacemarkList.get(j); if (placemark == originalPlacemark) { added = relatedPlacemarkList.add(newPlacemark); break; } } } if (!added) { ArrayList<Placemark> relatedPlacemarkList = new ArrayList<>(); relatedPlacemarkList.add(originalPlacemark); relatedPlacemarkList.add(newPlacemark); relatedPlacemarks.add(relatedPlacemarkList); } } private void removePlacemarksFromRelatedPlacemarks(Placemark placemark) { for (List<Placemark> placemarks : relatedPlacemarks) { placemarks.removeIf(p -> p == placemark); } relatedPlacemarks.removeIf(placemarks -> placemarks.size() == 1); } private void setComponentName(JComponent component, String name) { component.setName(getClass().getName() + "." + name); } void exportPlacemarkDataTable() { final SnapFileChooser fileChooser = new SnapFileChooser(); fileChooser.setDialogTitle(MessageFormat.format("Export {0} Data Table", /*I18N*/ StringUtils.firstLetterUp(placemarkDescriptor.getRoleLabel()))); setComponentName(fileChooser, "Export_Data_Table"); fileChooser.setFileFilter(PlacemarkIO.createTextFileFilter()); final File ioDir = getIODir(); fileChooser.setCurrentDirectory(ioDir); fileChooser.setSelectedFile(new File(ioDir, "Data")); int result = fileChooser.showSaveDialog(SwingUtilities.getWindowAncestor(this)); if (result == JFileChooser.APPROVE_OPTION) { File file = fileChooser.getSelectedFile(); if (file != null) { if (Boolean.TRUE.equals(Dialogs.requestOverwriteDecision(getTitle(), file))) { setIODir(file.getAbsoluteFile().getParentFile()); file = FileUtils.ensureExtension(file, PlacemarkIO.FILE_EXTENSION_FLAT_TEXT); try { try (Writer writer = new FileWriter(file)) { writePlacemarkDataTableText(writer); } } catch (IOException ignored) { Dialogs.showError(MessageFormat.format("I/O Error.\nFailed to export {0} data table.", /*I18N*/ placemarkDescriptor.getRoleLabel())); } } } } } private void writePlacemarkDataTableText(final Writer writer) { String[] additionalColumnNames = placemarkTableModel.getAdditionalColumnNames(); String[] standardColumnNames = placemarkTableModel.getStandardColumnNames(); int columnCount = placemarkTableModel.getColumnCount(); List<Placemark> placemarkList = new ArrayList<>(); List<Object[]> valueList = new ArrayList<>(); for (int sortedRow = 0; sortedRow < placemarkTable.getRowCount(); ++sortedRow) { ListSelectionModel selectionModel = placemarkTable.getSelectionModel(); if (selectionModel.isSelectionEmpty() || selectionModel.isSelectedIndex(sortedRow)) { final int modelRow = placemarkTable.convertRowIndexToModel(sortedRow); placemarkList.add(placemarkTableModel.getPlacemarkAt(modelRow)); Object[] values = new Object[columnCount]; for (int col = 0; col < columnCount; col++) { values[col] = placemarkTableModel.getValueAt(modelRow, col); } valueList.add(values); } } PlacemarkIO.writePlacemarksWithAdditionalData(writer, placemarkDescriptor.getRoleLabel(), product.getName(), placemarkList, valueList, standardColumnNames, additionalColumnNames); } private void setIODir(File dir) { if (preferences != null && dir != null) { preferences.put(PREFERENCE_KEY_PIN_IO_DIR, dir.getPath()); } } private File getIODir() { File dir = SystemUtils.getUserHomeDir(); if (preferences != null) { dir = new File(preferences.get(PREFERENCE_KEY_PIN_IO_DIR, dir.getPath())); } return dir; } @Override public UndoRedo getUndoRedo() { if (product != null) { return snapApp.getUndoManager(getProduct()); } return UndoRedo.NONE; } private class PlacemarkListener implements ProductNodeListener { @Override public void nodeChanged(ProductNodeEvent event) { ProductNode sourceNode = event.getSourceNode(); if (sourceNode instanceof Placemark && sourceNode.getOwner() == placemarkDescriptor.getPlacemarkGroup( product)) { updateUIState(); } } @Override public void nodeDataChanged(ProductNodeEvent event) { ProductNode sourceNode = event.getSourceNode(); if (sourceNode instanceof Placemark && sourceNode.getOwner() == placemarkDescriptor.getPlacemarkGroup( product)) { updateUIState(); } } @Override public void nodeAdded(ProductNodeEvent event) { ProductNode sourceNode = event.getSourceNode(); if (sourceNode instanceof Placemark && sourceNode.getOwner() == placemarkDescriptor.getPlacemarkGroup( product)) { placemarkTableModel.addPlacemark((Placemark) sourceNode); updateUIState(); } } @Override public void nodeRemoved(ProductNodeEvent event) { ProductNode sourceNode = event.getSourceNode(); if (sourceNode instanceof Placemark) { final Placemark placemark = (Placemark) sourceNode; removePlacemarksFromRelatedPlacemarks(placemark); if (sourceNode.getOwner() == placemarkDescriptor.getPlacemarkGroup(product)) { placemarkTableModel.removePlacemark(placemark); int selectedRow = placemarkTable.getSelectedRow(); if (selectedRow >= getPlacemarkGroup(product).getNodeCount()) { selectedRow = getPlacemarkGroup(product).getNodeCount() - 1; } if (selectedRow >= 0) { placemarkTable.getSelectionModel().setSelectionInterval(selectedRow, selectedRow); } updateUIState(); } } } } private class ToolTipSetter extends MouseInputAdapter { private int _rowIndex; private ToolTipSetter() { _rowIndex = -1; } @Override public void mouseExited(MouseEvent e) { _rowIndex = -1; } @Override public void mouseMoved(MouseEvent e) { int rowIndex = placemarkTable.rowAtPoint(e.getPoint()); if (rowIndex != _rowIndex) { _rowIndex = rowIndex; if (_rowIndex >= 0 && _rowIndex < placemarkTable.getRowCount()) { GeoPos geoPos = getPlacemarkAt(placemarkTable.convertRowIndexToModel(_rowIndex)).getGeoPos(); if (geoPos != null) { placemarkTable.setToolTipText(geoPos.getLonString() + " / " + geoPos.getLatString()); } } } } } private static class ColumnModelListener implements TableColumnModelListener { @Override public void columnAdded(TableColumnModelEvent e) { int minWidth; final int index = e.getToIndex(); switch (index) { case 0: case 1: minWidth = 60; break; default: minWidth = 80; } TableColumnModel columnModel = (TableColumnModel) e.getSource(); columnModel.getColumn(index).setPreferredWidth(minWidth); columnModel.getColumn(index).setCellRenderer(new RightAlignmentTableCellRenderer()); } @Override public void columnRemoved(TableColumnModelEvent e) { } @Override public void columnMoved(TableColumnModelEvent e) { } @Override public void columnMarginChanged(ChangeEvent e) { } @Override public void columnSelectionChanged(ListSelectionEvent e) { } } private class PopupListener extends MouseAdapter { @Override public void mousePressed(MouseEvent e) { action(e); } @Override public void mouseReleased(MouseEvent e) { action(e); } @Override public void mouseClicked(MouseEvent e) { action(e); } private void action(MouseEvent e) { if (e.isPopupTrigger()) { if (getNumSelectedPlacemarks() > 0) { final JPopupMenu popupMenu = new JPopupMenu(); final JMenuItem menuItem; menuItem = new JMenuItem("Copy selected data to clipboard"); menuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent actionEvent) { final StringWriter stringWriter = new StringWriter(); writePlacemarkDataTableText(stringWriter); String text = stringWriter.toString(); text = text.replaceAll("\r\n", "\n"); text = text.replaceAll("\r", "\n"); SystemUtils.copyToClipboard(text); } }); popupMenu.add(menuItem); final Point point = SwingUtilities.convertPoint(e.getComponent(), e.getPoint(), placemarkTable); popupMenu.show(placemarkTable, point.x, point.y); } } } } private class ProductSceneViewSelectionChangeHandler implements SelectionSupport.Handler<ProductSceneView> { @Override public void selectionChange(ProductSceneView oldValue, ProductSceneView newValue) { if (oldValue == currentView) { setCurrentView(null); } setCurrentView(newValue); } } private class ProductRemovedListener implements ProductManager.Listener { @Override public void productAdded(ProductManager.Event event) { //do nothing } @Override public void productRemoved(ProductManager.Event event) { productToSelectedBands.remove(product); productToSelectedGrids.remove(product); // removePlacemarksFromRemovedProducts(product); } } private class PlacemarkTableSelectionHandler implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { if (e.getValueIsAdjusting() || e.getFirstIndex() == -1 || synchronizingPlacemarkSelectedState) { return; } try { synchronizingPlacemarkSelectedState = true; Placemark[] placemarks = placemarkTableModel.getPlacemarks(); ArrayList<Placemark> selectedPlacemarks = new ArrayList<>(); for (int i = 0; i < placemarks.length; i++) { Placemark placemark = placemarks[i]; int sortedIndex = placemarkTable.convertRowIndexToView(i); if (placemarkTable.isRowSelected(sortedIndex)) { selectedPlacemarks.add(placemark); } } ProductSceneView sceneView = getSceneView(); if (sceneView != null) { Placemark[] placemarkArray = selectedPlacemarks.toArray(new Placemark[selectedPlacemarks.size()]); //todo remove code smell - tf 20151118 if (getPlacemarkDescriptor() instanceof PinDescriptor) { sceneView.selectPins(placemarkArray); } else { sceneView.selectGcps(placemarkArray); } } } finally { updateUIState(); synchronizingPlacemarkSelectedState = false; } } } private class ViewSelectionChangeHandler implements SelectionChangeListener { @Override public void selectionChanged(SelectionChangeEvent event) { if (synchronizingPlacemarkSelectedState) { return; } final ProductSceneView sceneView = getSceneView(); if (sceneView != null) { Layer layer = sceneView.getSelectedLayer(); if (layer instanceof VectorDataLayer) { VectorDataLayer vectorDataLayer = (VectorDataLayer) layer; if (vectorDataLayer.getVectorDataNode() == getProduct().getPinGroup().getVectorDataNode() || vectorDataLayer.getVectorDataNode() == getProduct().getGcpGroup().getVectorDataNode()) { updateUIState(); } } } } @Override public void selectionContextChanged(SelectionChangeEvent event) { } } private static class RightAlignmentTableCellRenderer extends DefaultTableCellRenderer { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { final JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); label.setHorizontalAlignment(JLabel.RIGHT); return label; } } }
51,535
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PinManagerTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/pin/PinManagerTopComponent.java
package org.esa.snap.rcp.placemark.pin; import org.esa.snap.core.datamodel.PinDescriptor; import org.esa.snap.rcp.placemark.PlacemarkManagerTopComponent; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; @TopComponent.Description( preferredID = "PinManagerTopComponent", iconBase = "org/esa/snap/rcp/icons/PinManager.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "output", openAtStartup = false, position = 10 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.placemark.pin.PinManagerTopComponent") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 30), @ActionReference(path = "Toolbars/Tool Windows") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_PinManagerTopComponent_Name", preferredID = "PinManagerTopComponent" ) @NbBundle.Messages({ "CTL_PinManagerTopComponent_Name=Pin Manager", "CTL_PinManagerTopComponent_HelpId=showPinManagerWnd" }) public class PinManagerTopComponent extends PlacemarkManagerTopComponent { public PinManagerTopComponent() { super(PinDescriptor.getInstance(), PinTableModel::new); } @Override protected String getTitle() { return Bundle.CTL_PinManagerTopComponent_Name(); } @Override protected String getHelpId() { return Bundle.CTL_PinManagerTopComponent_HelpId(); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_PinManagerTopComponent_HelpId()); } }
1,768
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PinTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/pin/PinTableModel.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.placemark.pin; import com.bc.ceres.core.Assert; import com.bc.ceres.swing.figure.FigureStyle; import com.bc.ceres.swing.figure.support.DefaultFigureStyle; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.rcp.placemark.PlacemarkUtils; import org.esa.snap.ui.product.AbstractPlacemarkTableModel; import java.awt.Color; public class PinTableModel extends AbstractPlacemarkTableModel { private final int xIndex = 0; private final int yIndex = 1; private final int lonIndex = 2; private final int latIndex = 3; private final int colorIndex = 4; private final int labelIndex = 5; public PinTableModel(PlacemarkDescriptor placemarkDescriptor, Product product, Band[] selectedBands, TiePointGrid[] selectedGrids) { super(placemarkDescriptor, product, selectedBands, selectedGrids); } @Override public String[] getStandardColumnNames() { return new String[]{"X", "Y", "Lon", "Lat", "Color", "Label"}; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { if (getProduct().getSceneGeoCoding() == null && (columnIndex == lonIndex || columnIndex == latIndex)) { return false; } return columnIndex < getStandardColumnNames().length; } @Override protected Object getStandardColumnValueAt(int rowIndex, int columnIndex) { Assert.notNull(getProduct()); final Placemark placemark = getPlacemarkDescriptor().getPlacemarkGroup(getProduct()).get(rowIndex); double x = Double.NaN; double y = Double.NaN; final PixelPos pixelPos = placemark.getPixelPos(); if (pixelPos != null) { x = pixelPos.x; y = pixelPos.y; } double lon = Double.NaN; double lat = Double.NaN; final GeoPos geoPos = placemark.getGeoPos(); if (geoPos != null) { lon = geoPos.lon; lat = geoPos.lat; } switch (columnIndex) { case xIndex: return x; case yIndex: return y; case lonIndex: return lon; case latIndex: return lat; case colorIndex: return PlacemarkUtils.getPlacemarkColor(placemark); case labelIndex: return placemark.getLabel(); default: return ""; } } @Override public Class getColumnClass(int columnIndex) { switch (columnIndex) { case xIndex: return Double.class; case yIndex: return Double.class; case lonIndex: return Double.class; case latIndex: return Double.class; case colorIndex: return Color.class; case labelIndex: return String.class; } return Object.class; } @Override public void setValueAt(Object value, int rowIndex, int columnIndex) { if (columnIndex == colorIndex) { final String colorName = DefaultFigureStyle.FILL_COLOR.getName(); final Placemark pin = getPlacemarkAt(rowIndex); final String styleCss = pin.getStyleCss(); FigureStyle style = new DefaultFigureStyle(); style.fromCssString(styleCss); style.setValue(colorName, value); pin.setStyleCss(style.toCssString()); } else { super.setValueAt(value, rowIndex, columnIndex); } } }
4,625
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GcpGeoCodingForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/gcp/GcpGeoCodingForm.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.placemark.gcp; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.datamodel.GcpGeoCoding; 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.Placemark; import org.esa.snap.core.datamodel.PlacemarkGroup; 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.ProductNodeGroup; import org.esa.snap.core.datamodel.ProductNodeListener; import org.esa.snap.core.dataop.maptransf.Datum; import org.esa.snap.core.util.Debug; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JToggleButton; import javax.swing.SwingWorker; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DecimalFormat; import java.text.FieldPosition; import java.text.Format; import java.text.NumberFormat; import java.text.ParsePosition; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; /** * GCP geo-coding form. * * @author Marco Peters * @version $Revision$ $Date$ */ class GcpGeoCodingForm extends JPanel { private JTextField methodTextField; private JTextField rmseLatTextField; private JTextField rmseLonTextField; private JComboBox methodComboBox; private JToggleButton attachButton; private JTextField warningLabel; private Product currentProduct; private Format rmseNumberFormat; private GcpGroupListener currentGcpGroupListener; public GcpGeoCodingForm() { rmseNumberFormat = new RmseNumberFormat(); currentGcpGroupListener = new GcpGroupListener(); initComponents(); } private void initComponents() { TableLayout layout = new TableLayout(2); this.setLayout(layout); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableWeightY(1.0); layout.setTableFill(TableLayout.Fill.BOTH); layout.setTablePadding(2, 2); layout.setColumnWeightX(0, 0.5); layout.setColumnWeightX(1, 0.5); add(createInfoPanel()); add(createAttachDetachPanel()); updateUIState(); } private JPanel createInfoPanel() { TableLayout layout = new TableLayout(2); layout.setTablePadding(2, 4); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 1.0); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.BOTH); JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Current GCP Geo-Coding")); panel.add(new JLabel("Method:")); methodTextField = new JTextField(); setComponentName(methodTextField, "methodTextField"); methodTextField.setEditable(false); methodTextField.setHorizontalAlignment(JLabel.TRAILING); panel.add(methodTextField); rmseLatTextField = new JTextField(); setComponentName(rmseLatTextField, "rmseLatTextField"); rmseLatTextField.setEditable(false); rmseLatTextField.setHorizontalAlignment(JLabel.TRAILING); panel.add(new JLabel("RMSE Lat:")); panel.add(rmseLatTextField); rmseLonTextField = new JTextField(); setComponentName(rmseLonTextField, "rmseLonTextField"); rmseLonTextField.setEditable(false); rmseLonTextField.setHorizontalAlignment(JLabel.TRAILING); panel.add(new JLabel("RMSE Lon:")); panel.add(rmseLonTextField); return panel; } private JPanel createAttachDetachPanel() { methodComboBox = new JComboBox(GcpGeoCoding.Method.values()); setComponentName(methodComboBox, "methodComboBox"); methodComboBox.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateUIState(); } }); attachButton = new JToggleButton(); setComponentName(attachButton, "attachButton"); attachButton.setName("attachButton"); AbstractAction attachDetachAction = new AbstractAction() { public void actionPerformed(ActionEvent e) { if (!(currentProduct.getSceneGeoCoding() instanceof GcpGeoCoding)) { attachGeoCoding(currentProduct); } else { detachGeoCoding(currentProduct); } } }; attachButton.setAction(attachDetachAction); attachButton.setHideActionText(true); warningLabel = new JTextField(); warningLabel.setEditable(false); TableLayout layout = new TableLayout(2); layout.setTablePadding(2, 4); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 1.0); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableFill(TableLayout.Fill.BOTH); layout.setCellColspan(2, 0, 2); layout.setCellFill(2, 0, TableLayout.Fill.VERTICAL); layout.setCellAnchor(2, 0, TableLayout.Anchor.CENTER); JPanel panel = new JPanel(layout); panel.setBorder(BorderFactory.createTitledBorder("Attach / Detach GCP Geo-Coding")); panel.add(new JLabel("Method:")); panel.add(methodComboBox); panel.add(new JLabel("Status:")); panel.add(warningLabel); panel.add(attachButton); return panel; } void updateUIState() { if (currentProduct != null && currentProduct.getSceneGeoCoding() instanceof GcpGeoCoding) { final GcpGeoCoding gcpGeoCoding = (GcpGeoCoding) currentProduct.getSceneGeoCoding(); rmseLatTextField.setText(rmseNumberFormat.format(gcpGeoCoding.getRmseLat())); rmseLonTextField.setText(rmseNumberFormat.format(gcpGeoCoding.getRmseLon())); methodTextField.setText(gcpGeoCoding.getMethod().getName()); methodComboBox.setSelectedItem(gcpGeoCoding.getMethod()); methodComboBox.setEnabled(false); attachButton.setText("Detach"); attachButton.setSelected(true); attachButton.setEnabled(true); warningLabel.setText("GCP geo-coding attached"); warningLabel.setForeground(Color.BLACK); } else { methodComboBox.setEnabled(true); methodTextField.setText("n/a"); rmseLatTextField.setText(rmseNumberFormat.format(Double.NaN)); rmseLonTextField.setText(rmseNumberFormat.format(Double.NaN)); attachButton.setText("Attach"); attachButton.setSelected(false); updateAttachButtonAndStatus(); } } private void updateAttachButtonAndStatus() { final GcpGeoCoding.Method method = (GcpGeoCoding.Method) methodComboBox.getSelectedItem(); if (currentProduct != null && getValidGcpCount(currentProduct.getGcpGroup()) >= method.getTermCountP()) { attachButton.setEnabled(true); warningLabel.setText("OK, enough GCPs for selected method"); warningLabel.setForeground(Color.GREEN.darker()); } else { attachButton.setEnabled(false); warningLabel.setText("Not enough (valid) GCPs for selected method"); warningLabel.setForeground(Color.RED.darker()); } } private void detachGeoCoding(Product product) { if (product.getSceneGeoCoding() instanceof GcpGeoCoding) { GeoCoding gc = ((GcpGeoCoding) product.getSceneGeoCoding()).getOriginalGeoCoding(); product.setSceneGeoCoding(gc); } updateUIState(); } private void attachGeoCoding(final Product product) { final GcpGeoCoding.Method method = (GcpGeoCoding.Method) methodComboBox.getSelectedItem(); final Placemark[] gcps = getValidGcps(product.getGcpGroup()); final GeoCoding geoCoding = product.getSceneGeoCoding(); final Datum datum; if (geoCoding == null) { datum = Datum.WGS_84; } else { datum = geoCoding.getDatum(); } SwingWorker sw = new SwingWorker<GcpGeoCoding, GcpGeoCoding>() { @Override protected GcpGeoCoding doInBackground() throws Exception { GcpGeoCoding gcpGeoCoding = new GcpGeoCoding(method, gcps, product.getSceneRasterWidth(), product.getSceneRasterHeight(), datum); gcpGeoCoding.setOriginalGeoCoding(product.getSceneGeoCoding()); return gcpGeoCoding; } @Override protected void done() { final GcpGeoCoding gcpGeoCoding; try { gcpGeoCoding = get(); product.setSceneGeoCoding(gcpGeoCoding); updateUIState(); } catch (InterruptedException e) { Debug.trace(e); } catch (ExecutionException e) { Debug.trace(e.getCause()); } } }; sw.execute(); } public void setProduct(Product product) { if (product == currentProduct) { return; } if (currentProduct != null) { currentProduct.removeProductNodeListener(currentGcpGroupListener); } currentProduct = product; if (currentProduct != null) { currentProduct.addProductNodeListener(currentGcpGroupListener); } } private void setComponentName(JComponent component, String name) { component.setName(getClass().getName() + name); } private static Placemark[] getValidGcps(ProductNodeGroup<Placemark> gcpGroup) { final List<Placemark> gcpList = new ArrayList<Placemark>(gcpGroup.getNodeCount()); for (int i = 0; i < gcpGroup.getNodeCount(); i++) { final Placemark p = gcpGroup.get(i); final PixelPos pixelPos = p.getPixelPos(); final GeoPos geoPos = p.getGeoPos(); if (pixelPos != null && pixelPos.isValid() && geoPos != null && geoPos.isValid()) { gcpList.add(p); } } return gcpList.toArray(new Placemark[gcpList.size()]); } private static int getValidGcpCount(PlacemarkGroup gcpGroup) { int count = 0; for (int i = 0; i < gcpGroup.getNodeCount(); i++) { final Placemark p = gcpGroup.get(i); if (isValid(p)) { count++; } } return count; } private static boolean isValid(Placemark p) { final PixelPos pixelPos = p.getPixelPos(); final GeoPos geoPos = p.getGeoPos(); return pixelPos != null && pixelPos.isValid() && geoPos != null && geoPos.isValid(); } private static class RmseNumberFormat extends NumberFormat { DecimalFormat format = new DecimalFormat("0.0####"); @Override public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) { if (Double.isNaN(number)) { return toAppendTo.append("n/a"); } else { return format.format(number, toAppendTo, pos); } } @Override public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos) { return format.format(number, toAppendTo, pos); } @Override public Number parse(String source, ParsePosition parsePosition) { return format.parse(source, parsePosition); } } private class GcpGroupListener implements ProductNodeListener { @Override public void nodeChanged(ProductNodeEvent event) { // exclude geo-coding changes to prevent recursion if (Product.PROPERTY_NAME_SCENE_GEO_CODING.equals(event.getPropertyName())) { return; } final ProductNode sourceNode = event.getSourceNode(); if (sourceNode instanceof Placemark) { if (currentProduct.getGcpGroup().contains((Placemark) sourceNode)) { updateGcpGeoCoding(); } } } @Override public void nodeDataChanged(ProductNodeEvent event) { nodeChanged(event); } @Override public void nodeAdded(ProductNodeEvent event) { if (event.getGroup() == currentProduct.getGcpGroup()) { updateGcpGeoCoding(); } } @Override public void nodeRemoved(ProductNodeEvent event) { if (event.getGroup() == currentProduct.getGcpGroup()) { updateGcpGeoCoding(); } } private void updateGcpGeoCoding() { final GeoCoding geoCoding = currentProduct.getSceneGeoCoding(); if (geoCoding instanceof GcpGeoCoding) { final GcpGeoCoding gcpGeoCoding = ((GcpGeoCoding) geoCoding); final PlacemarkGroup gcpGroup = currentProduct.getGcpGroup(); final int gcpCount = gcpGroup.getNodeCount(); if (gcpCount < gcpGeoCoding.getMethod().getTermCountP()) { detachGeoCoding(currentProduct); } else { gcpGeoCoding.setGcps(gcpGroup.toArray(new Placemark[gcpCount])); currentProduct.fireProductNodeChanged(Product.PROPERTY_NAME_SCENE_GEO_CODING); updateUIState(); } } } } }
14,721
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
InsertGcpInteractor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/gcp/InsertGcpInteractor.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.placemark.gcp; import org.esa.snap.core.datamodel.GcpDescriptor; import org.esa.snap.rcp.placemark.InsertPlacemarkInteractor; /** * A tool used to create ground control points (single click), select (single click on a GCP) or * edit (double click on a GCP) the GCPs displayed in product scene view. */ public class InsertGcpInteractor extends InsertPlacemarkInteractor { public InsertGcpInteractor() { super(GcpDescriptor.getInstance()); } }
1,211
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GcpTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/gcp/GcpTableModel.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.placemark.gcp; import com.bc.ceres.core.Assert; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.GcpGeoCoding; 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.Placemark; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.ui.product.AbstractPlacemarkTableModel; public class GcpTableModel extends AbstractPlacemarkTableModel { public GcpTableModel(PlacemarkDescriptor placemarkDescriptor, Product product, Band[] selectedBands, TiePointGrid[] selectedGrids) { super(placemarkDescriptor, product, selectedBands, selectedGrids); } @Override public String[] getStandardColumnNames() { return new String[]{"X", "Y", "Lon", "Lat", "Delta Lon", "Delta Lat", "Label"}; } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex < getStandardColumnNames().length && columnIndex != 4 && columnIndex != 5; } @Override protected Object getStandardColumnValueAt(int rowIndex, int columnIndex) { Assert.notNull(getProduct()); final Placemark placemark = getPlacemarkDescriptor().getPlacemarkGroup(getProduct()).get(rowIndex); double x = Double.NaN; double y = Double.NaN; final PixelPos pixelPos = placemark.getPixelPos(); if (pixelPos != null) { x = pixelPos.x; y = pixelPos.y; } double lon = Double.NaN; double lat = Double.NaN; final GeoPos geoPos = placemark.getGeoPos(); if (geoPos != null) { lon = geoPos.lon; lat = geoPos.lat; } double dLon = Double.NaN; double dLat = Double.NaN; final GeoCoding geoCoding = getProduct().getSceneGeoCoding(); if (geoCoding instanceof GcpGeoCoding && pixelPos != null) { final GeoPos expectedGeoPos = geoCoding.getGeoPos(pixelPos, new GeoPos()); if (expectedGeoPos != null) { dLon = Math.abs(lon - expectedGeoPos.lon); dLat = Math.abs(lat - expectedGeoPos.lat); } } switch (columnIndex) { case 0: return x; case 1: return y; case 2: return lon; case 3: return lat; case 4: return dLon; case 5: return dLat; case 6: return placemark.getLabel(); default: return ""; } } }
3,479
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GcpManagerTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/placemark/gcp/GcpManagerTopComponent.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.placemark.gcp; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.GcpDescriptor; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeListenerAdapter; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.rcp.placemark.PlacemarkManagerTopComponent; import org.esa.snap.rcp.placemark.TableModelFactory; import org.esa.snap.ui.DecimalTableCellRenderer; import org.esa.snap.ui.product.AbstractPlacemarkTableModel; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.table.TableColumnModel; import java.awt.Component; import java.text.DecimalFormat; @TopComponent.Description( preferredID = "GcpManagerTopComponent", iconBase = "org/esa/snap/rcp/icons/GcpManager.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS //todo define ) @TopComponent.Registration( mode = "output", openAtStartup = false, position = 20 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.placemark.gcp.GcpManagerTopComponent") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 31), @ActionReference(path = "Toolbars/Tool Windows") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_GcpManagerTopComponent_Name", preferredID = "GcpManagerTopComponent" ) @NbBundle.Messages({ "CTL_GcpManagerTopComponent_Name=GCP Manager", "CTL_GcpManagerTopComponent_HelpId=showGcpManagerWnd" }) /** * A dialog used to manage the list of pins associated with a selected product. */ public class GcpManagerTopComponent extends PlacemarkManagerTopComponent { public static final String ID = GcpManagerTopComponent.class.getName(); private GcpGeoCodingForm geoCodingForm; private final ProductNodeListenerAdapter geoCodinglistener; public GcpManagerTopComponent() { super(GcpDescriptor.getInstance(), new TableModelFactory() { @Override public AbstractPlacemarkTableModel createTableModel(PlacemarkDescriptor placemarkDescriptor, Product product, Band[] selectedBands, TiePointGrid[] selectedGrids) { return new GcpTableModel(placemarkDescriptor, product, selectedBands, selectedGrids); } }); geoCodinglistener = new ProductNodeListenerAdapter() { @Override public void nodeChanged(ProductNodeEvent event) { if (Product.PROPERTY_NAME_SCENE_GEO_CODING.equals(event.getPropertyName())) { updateUIState(); } } }; } @Override protected Component getSouthExtension() { geoCodingForm = new GcpGeoCodingForm(); return geoCodingForm; } @Override public void setProduct(Product product) { final Product oldProduct = getProduct(); if (oldProduct != product) { if (oldProduct != null) { oldProduct.removeProductNodeListener(geoCodinglistener); } if (product != null) { product.addProductNodeListener(geoCodinglistener); } } super.setProduct(product); } @Override protected void addCellRenderer(TableColumnModel columnModel) { super.addCellRenderer(columnModel); columnModel.getColumn(4).setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("0.000000"))); columnModel.getColumn(5).setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("0.000000"))); } @Override protected void updateUIState() { super.updateUIState(); geoCodingForm.setProduct(getProduct()); geoCodingForm.updateUIState(); } @Override protected String getTitle() { return Bundle.CTL_GcpManagerTopComponent_Name(); } @Override protected String getHelpId() { return Bundle.CTL_GcpManagerTopComponent_HelpId(); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_GcpManagerTopComponent_HelpId()); } }
5,230
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AbstractSnapAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/AbstractSnapAction.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; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AppContext; import org.openide.util.HelpCtx; import javax.swing.AbstractAction; public abstract class AbstractSnapAction extends AbstractAction implements HelpCtx.Provider { public static final String HELP_ID = "helpId"; private AppContext appContext; public AppContext getAppContext() { if (appContext == null) { appContext = SnapApp.getDefault().getAppContext(); } return appContext; } public String getHelpId() { Object value = getValue(HELP_ID); if (value instanceof String) { return (String) value; } return null; } public void setHelpId(String helpId) { putValue(HELP_ID, helpId); } @Override public HelpCtx getHelpCtx() { String helpId = getHelpId(); if (helpId != null) { return new HelpCtx(helpId); } return null; } }
1,725
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
NewWorkspaceAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/window/NewWorkspaceAction.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.window; import com.bc.ceres.core.Assert; import eu.esa.snap.netbeans.docwin.WindowUtilities; import eu.esa.snap.netbeans.docwin.WorkspaceTopComponent; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; 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.Messages; import org.openide.windows.Mode; import org.openide.windows.WindowManager; import javax.swing.*; import java.awt.event.ActionEvent; @ActionID( category = "Window", id = "org.esa.snap.rcp.action.window.NewWorkspaceAction" ) @ActionRegistration( key = "", displayName = "#CTL_NewWorkspaceActionName", menuText = "#CTL_NewWorkspaceActionMenuText", popupText = "#CTL_NewWorkspaceActionMenuText" ) @ActionReferences({ @ActionReference(path = "Menu/Window", position = 20050, separatorAfter = 20075), @ActionReference(path = "Shortcuts", name = "D-W") }) @Messages({ "CTL_NewWorkspaceActionName=New Workspace", "CTL_NewWorkspaceActionMenuText=New Workspace...", "LBL_NewWorkspaceActionName=Name:", "VAL_NewWorkspaceActionValue=Workspace" }) public final class NewWorkspaceAction extends AbstractAction implements HelpCtx.Provider { public NewWorkspaceAction() { putValue(NAME, Bundle.CTL_NewWorkspaceActionName()); } @Override public void actionPerformed(ActionEvent e) { String defaultName = WindowUtilities.getUniqueTitle(Bundle.VAL_NewWorkspaceActionValue(), WorkspaceTopComponent.class); NotifyDescriptor.InputLine d = new NotifyDescriptor.InputLine(Bundle.LBL_NewWorkspaceActionName(), Bundle.CTL_NewWorkspaceActionName()); d.setInputText(defaultName); Object result = DialogDisplayer.getDefault().notify(d); if (NotifyDescriptor.OK_OPTION.equals(result)) { WorkspaceTopComponent workspaceTopComponent = new WorkspaceTopComponent(d.getInputText()); Mode editor = WindowManager.getDefault().findMode("editor"); Assert.notNull(editor, "editor"); editor.dockInto(workspaceTopComponent); workspaceTopComponent.open(); workspaceTopComponent.requestActive(); } } @Override public HelpCtx getHelpCtx() { // TODO: Make sure help page is available for ID return new HelpCtx("newWorkspace"); } }
2,770
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OpenImageViewAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/window/OpenImageViewAction.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.SubProgressMonitor; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import eu.esa.snap.netbeans.docwin.DocumentWindowManager; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.util.Debug; import org.esa.snap.core.util.PreferencesPropertyMap; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.windows.ProductSceneViewTopComponent; 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.*; import javax.swing.*; import java.awt.event.ActionEvent; import java.text.MessageFormat; import java.util.Collection; import java.util.List; import java.util.Objects; import java.util.prefs.Preferences; import java.util.stream.Collectors; /** * This action opens an image view of the currently selected raster. * * @author Marco Peters * @author Norman Fomferra */ @ActionID(category = "View", id = "OpenImageViewAction") @ActionRegistration( displayName = "#CTL_OpenImageViewActionName", iconBase = "org/esa/snap/rcp/icons/RsBandAsSwath.gif") @ActionReferences({ @ActionReference(path = "Menu/Window", position = 100), @ActionReference(path = "Context/Product/RasterDataNode", position = 100),}) @NbBundle.Messages("CTL_OpenImageViewActionName=Open Image Window") public class OpenImageViewAction extends AbstractAction implements ContextAwareAction, LookupListener { private RasterDataNode rasterDataNode; private Lookup lookup; public OpenImageViewAction() { this(Utilities.actionsGlobalContext()); } public OpenImageViewAction(Lookup lookup) { putValue(Action.NAME, Bundle.CTL_OpenImageViewActionName()); this.lookup = lookup; Lookup.Result<RasterDataNode> rasterDataNodeResult = lookup.lookupResult(RasterDataNode.class); rasterDataNodeResult.addLookupListener(WeakListeners.create(LookupListener.class, this, rasterDataNodeResult)); setEnabledState(); setActionName(); } public OpenImageViewAction(RasterDataNode rasterDataNode) { putValue(Action.NAME, Bundle.CTL_OpenImageViewActionName()); this.rasterDataNode = rasterDataNode; } public static OpenImageViewAction create(RasterDataNode rasterDataNode) { return new OpenImageViewAction(rasterDataNode); } public static void openImageView(RasterDataNode rasterDataNode) { new OpenImageViewAction().openRasterDataNode(rasterDataNode); } public static ProductSceneViewTopComponent getProductSceneViewTopComponent(RasterDataNode raster) { return WindowUtilities.getOpened(ProductSceneViewTopComponent.class) .filter(topComponent -> topComponent.getView().getNumRasters() == 1 && raster == topComponent.getView().getRaster()) .findFirst() .orElse(null); } public static ProductSceneView getProductSceneView(RasterDataNode raster) { ProductSceneViewTopComponent component = getProductSceneViewTopComponent(raster); return component != null ? component.getView() : null; } public static void updateProductSceneViewImages(final RasterDataNode[] rasters, ProductSceneViewImageUpdater updateMethod) { List<ProductSceneView> views = WindowUtilities.getOpened(ProductSceneViewTopComponent.class).map(ProductSceneViewTopComponent::getView).collect(Collectors.toList()); for (ProductSceneView view : views) { boolean updateView = false; for (int j = 0; j < rasters.length && !updateView; j++) { final RasterDataNode raster = rasters[j]; for (int k = 0; k < view.getNumRasters() && !updateView; k++) { if (view.getRaster(k) == raster) { updateView = true; } } } if (updateView) { SwingUtilities.invokeLater(() -> updateMethod.updateView(view)); } } } @Override public void actionPerformed(ActionEvent e) { execute(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ProductSceneView helper methods public void execute() { Collection<? extends RasterDataNode> selectedRasterD = getSelectedRasterDataNodes(); if (Objects.nonNull(selectedRasterD)) { for (RasterDataNode rasterDataNode : selectedRasterD) { openRasterDataNode(rasterDataNode); } } else if (Objects.nonNull(rasterDataNode)) { openRasterDataNode(rasterDataNode); } } @Override public Action createContextAwareInstance(Lookup actionContext) { return new OpenImageViewAction(actionContext); } @Override public void resultChanged(LookupEvent ev) { setEnabledState(); setActionName(); } private void openRasterDataNode(RasterDataNode rasterDataNode) { ProductSceneViewTopComponent tc = getProductSceneViewTopComponent(rasterDataNode); if (tc != null) { tc.requestSelected(); } else { openProductSceneView(rasterDataNode); } } private Collection<? extends RasterDataNode> getSelectedRasterDataNodes() { return lookup.lookupAll(RasterDataNode.class); } private void setActionName() { Collection<? extends RasterDataNode> selectedRasterDataNode = getSelectedRasterDataNodes(); int size = selectedRasterDataNode.size(); if (size > 1) { this.putValue(Action.NAME, String.format("Open %d Image Window", size)); } else { this.putValue(Action.NAME, Bundle.CTL_OpenImageViewActionName()); } } private void setEnabledState() { if (Objects.nonNull(lookup)) { setEnabled(lookup.lookup(RasterDataNode.class) != null); } } private void openProductSceneView(RasterDataNode rasterDataNode) { SnapApp snapApp = SnapApp.getDefault(); snapApp.setStatusBarMessage("Opening image view..."); UIUtils.setRootFrameWaitCursor(snapApp.getMainFrame()); String progressMonitorTitle = MessageFormat.format("Creating image for ''{0}''", rasterDataNode.getName()); ProductSceneView existingView = getProductSceneView(rasterDataNode); SwingWorker<ProductSceneImage, Object> worker = new ProgressMonitorSwingWorker<ProductSceneImage, Object>(snapApp.getMainFrame(), progressMonitorTitle) { @Override public void done() { UIUtils.setRootFrameDefaultCursor(snapApp.getMainFrame()); snapApp.setStatusBarMessage(""); try { ProductSceneImage sceneImage = get(); UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(sceneImage.getProduct()); ProductSceneView view = new ProductSceneView(sceneImage, undoManager); openDocumentWindow(view); } catch (Exception e) { snapApp.handleError(MessageFormat.format("Failed to open image view.\n\n{0}", e.getMessage()), e); } } @Override protected ProductSceneImage doInBackground(com.bc.ceres.core.ProgressMonitor pm) { try { return createProductSceneImage(rasterDataNode, existingView, pm); } finally { if (pm.isCanceled()) { rasterDataNode.unloadRasterData(); } } } }; worker.execute(); } private void openDocumentWindow(final ProductSceneView view) { UndoRedo.Manager undoManager = SnapApp.getDefault().getUndoManager(view.getProduct()); ProductSceneViewTopComponent productSceneViewWindow = new ProductSceneViewTopComponent(view, undoManager); DocumentWindowManager.getDefault().openWindow(productSceneViewWindow); productSceneViewWindow.requestSelected(); } private ProductSceneImage createProductSceneImage(final RasterDataNode raster, ProductSceneView existingView, com.bc.ceres.core.ProgressMonitor pm) { Debug.assertNotNull(raster); Debug.assertNotNull(pm); try { pm.beginTask("Creating image...", 1); ProductSceneImage sceneImage; if (existingView != null) { sceneImage = new ProductSceneImage(raster, existingView); } else { final Preferences preferences = SnapApp.getDefault().getPreferences(); final PreferencesPropertyMap configuration = new PreferencesPropertyMap(preferences); sceneImage = new ProductSceneImage(raster, configuration, SubProgressMonitor.create(pm, 1)); } sceneImage.initVectorDataCollectionLayer(); sceneImage.initMaskCollectionLayer(); return sceneImage; } finally { pm.done(); } } /** * A method used to update a <code>ProductSceneView</code>. */ public interface ProductSceneViewImageUpdater { ProductSceneViewImageUpdater DEFAULT = ProductSceneView::updateImage; void updateView(ProductSceneView view); } }
10,309
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OpenMetadataViewAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/window/OpenMetadataViewAction.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.window; import eu.esa.snap.netbeans.docwin.DocumentWindowManager; import org.esa.snap.core.datamodel.MetadataElement; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.rcp.metadata.MetadataViewTopComponent; 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.util.Collection; /** * This action opens an Metadata View of the currently selected Metadata Node */ @ActionID(category = "File", id = "OpenMetadataViewAction") @ActionRegistration(displayName = "#CTL_OpenMetadataViewAction_MenuText") @ActionReferences({ @ActionReference(path = "Context/Product/MetadataElement", position = 100), @ActionReference(path = "Menu/Window", position = 120) }) @NbBundle.Messages("CTL_OpenMetadataViewAction_MenuText=Open Metadata Window") public class OpenMetadataViewAction extends AbstractAction implements ContextAwareAction, LookupListener { private Lookup lookup; private final Lookup.Result<ProductNode> result; public OpenMetadataViewAction() { this(Utilities.actionsGlobalContext()); } public OpenMetadataViewAction(Lookup lookup) { this.lookup = lookup; result = lookup.lookupResult(ProductNode.class); result.addLookupListener( WeakListeners.create(LookupListener.class, this, result)); setActionName(); setEnableState(); } private void setActionName() { int size = getSelectedMetadataView().size(); if (size > 1) { putValue(Action.NAME, String.format("Open %d Metadata Window", size)); } else { putValue(Action.NAME, Bundle.CTL_OpenMetadataViewAction_MenuText()); } } @Override public Action createContextAwareInstance(Lookup lookup) { return new OpenMetadataViewAction(lookup); } @Override public void resultChanged(LookupEvent lookupEvent) { setEnableState(); setActionName(); } private void setEnableState() { ProductNode productNode = lookup.lookup(ProductNode.class); setEnabled(productNode instanceof MetadataElement); } private Collection<? extends ProductNode> getSelectedMetadataView() { return lookup.lookupAll(ProductNode.class); } @Override public void actionPerformed(ActionEvent e) { getSelectedMetadataView().forEach(productNode -> openMetadataView((MetadataElement) productNode)); } public void openMetadataView(final MetadataElement element) { openDocumentWindow(element); } private void openDocumentWindow(final MetadataElement element) { final MetadataViewTopComponent metadataViewTopComponent = new MetadataViewTopComponent(element); DocumentWindowManager.getDefault().openWindow(metadataViewTopComponent); metadataViewTopComponent.requestSelected(); } }
3,788
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OpenPlacemarkViewAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/actions/window/OpenPlacemarkViewAction.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.window; import eu.esa.snap.netbeans.docwin.DocumentWindowManager; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.datamodel.VectorDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.placemark.PlacemarkViewTopComponent; 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; @ActionID(category = "View", id = "OpenPlacemarkViewAction") @ActionRegistration( displayName = "#CTL_OpenPlacemarkViewAction_MenuText", iconBase = "org/esa/snap/rcp/icons/RsVector16.gif" ) @ActionReferences({ @ActionReference(path = "Menu/Window", position = 125), @ActionReference(path = "Context/Product/VectorDataNode", position = 100), }) @NbBundle.Messages("CTL_OpenPlacemarkViewAction_MenuText=Open Placemark Window") public class OpenPlacemarkViewAction extends AbstractAction implements ContextAwareAction, LookupListener { private Lookup lookup; private final Lookup.Result<VectorDataNode> result; public OpenPlacemarkViewAction() { this(Utilities.actionsGlobalContext()); } public OpenPlacemarkViewAction(Lookup lookup) { this.lookup = lookup; result = lookup.lookupResult(VectorDataNode.class); result.addLookupListener( WeakListeners.create(LookupListener.class, this, result)); setEnableState(); putValue(Action.NAME, Bundle.CTL_OpenPlacemarkViewAction_MenuText()); } @Override public Action createContextAwareInstance(Lookup lookup) { return new OpenPlacemarkViewAction(lookup); } @Override public void resultChanged(LookupEvent lookupEvent) { setEnableState(); } private void setEnableState() { setEnabled(lookup.lookup(VectorDataNode.class) != null); } @Override public void actionPerformed(ActionEvent e) { ProductNode selectedProductNode = SnapApp.getDefault().getSelectedProductNode(EXPLORER); if (selectedProductNode instanceof VectorDataNode) { VectorDataNode vectorDataNode = (VectorDataNode) selectedProductNode; openView(vectorDataNode); } } public void openView(final VectorDataNode vectorDataNode) { final PlacemarkViewTopComponent placemarkViewTopComponent = new PlacemarkViewTopComponent(vectorDataNode); DocumentWindowManager.getDefault().openWindow(placemarkViewTopComponent); placemarkViewTopComponent.requestSelected(); } }
3,460
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z