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
FilePathListCellRenderer.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/FilePathListCellRenderer.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc; import org.esa.snap.core.util.io.FileUtils; import javax.swing.DefaultListCellRenderer; import javax.swing.JList; import java.awt.Component; import java.io.File; /** * A {@link javax.swing.ListCellRenderer} which replaces the beginning of the file path * by "..." to ensure the given maximum length.. * It shows also the complete path as a tool tip. * <p> * <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i> */ public class FilePathListCellRenderer extends DefaultListCellRenderer { private int maxLength; /** * Creates an instance of {@link javax.swing.ListCellRenderer}. * * @param maxLength The maximum length of the file path */ public FilePathListCellRenderer(int maxLength) { this.maxLength = maxLength; } @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); final String filePath = (String) value; if (filePath != null) { setToolTipText(filePath); setText(FileUtils.getDisplayText(new File(filePath), maxLength)); } return this; } }
2,119
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SelectLayerSourceAssistantPage.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/SelectLayerSourceAssistantPage.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSource; import org.esa.snap.ui.layer.LayerSourceDescriptor; import org.esa.snap.ui.layer.LayerSourcePageContext; import javax.swing.DefaultListCellRenderer; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; /** * <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i> */ public class SelectLayerSourceAssistantPage extends AbstractLayerSourceAssistantPage { private JList list; private Map<LayerSourceDescriptor, LayerSource> layerSourceMap; public SelectLayerSourceAssistantPage(LayerSourceDescriptor[] sourceDescriptors) { super("Select Layer Source"); layerSourceMap = new HashMap<LayerSourceDescriptor, LayerSource>(); for (LayerSourceDescriptor sourceDescriptor : sourceDescriptors) { layerSourceMap.put(sourceDescriptor, sourceDescriptor.createLayerSource()); } } @Override public boolean validatePage() { return list.getSelectedIndex() >= 0; } @Override public boolean hasNextPage() { LayerSourceDescriptor selected = (LayerSourceDescriptor) list.getSelectedValue(); if (selected == null) { return false; } return layerSourceMap.get(selected).hasFirstPage(); } @Override public AbstractLayerSourceAssistantPage getNextPage() { LayerSourceDescriptor selected = (LayerSourceDescriptor) list.getSelectedValue(); if (selected == null) { return null; } LayerSource layerSource = layerSourceMap.get(selected); LayerSourcePageContext pageContext = getContext(); pageContext.setLayerSource(layerSource); return layerSource.getFirstPage(pageContext); } @Override public boolean canFinish() { LayerSourceDescriptor selected = (LayerSourceDescriptor) list.getSelectedValue(); if (selected == null) { return false; } return layerSourceMap.get(selected).canFinish(getContext()); } @Override public boolean performFinish() { LayerSourceDescriptor selected = (LayerSourceDescriptor) list.getSelectedValue(); if (selected == null) { return false; } return layerSourceMap.get(selected).performFinish(getContext()); } @Override public Component createPageComponent() { LayerSourcePageContext context = getContext(); Set<LayerSourceDescriptor> descriptorSet = layerSourceMap.keySet(); List<LayerSourceDescriptor> descriptorList = new ArrayList<LayerSourceDescriptor>(descriptorSet.size()); for (LayerSourceDescriptor lsd : descriptorSet) { LayerSource lsc = layerSourceMap.get(lsd); if (lsc.isApplicable(context)) { descriptorList.add(lsd); } } Collections.sort(descriptorList, new Comparator<LayerSourceDescriptor>() { @Override public int compare(LayerSourceDescriptor o1, LayerSourceDescriptor o2) { return o1.getName().compareTo(o2.getName()); } }); list = new JList(descriptorList.toArray(new LayerSourceDescriptor[descriptorList.size()])); list.getSelectionModel().addListSelectionListener(new LayerSourceSelectionListener()); list.setCellRenderer(new LayerSourceCellRenderer()); GridBagConstraints gbc = new GridBagConstraints(); final JPanel panel = new JPanel(new GridBagLayout()); gbc.anchor = GridBagConstraints.WEST; gbc.gridx = 0; gbc.gridy = 0; gbc.fill = GridBagConstraints.HORIZONTAL; panel.add(new JLabel("Available layer sources:"), gbc); gbc.weightx = 1; gbc.weighty = 1; gbc.gridy++; gbc.fill = GridBagConstraints.BOTH; panel.add(new JScrollPane(list), gbc); return panel; } private class LayerSourceSelectionListener implements ListSelectionListener { @Override public void valueChanged(ListSelectionEvent e) { getContext().updateState(); } } private static class LayerSourceCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { final JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); if (value instanceof LayerSourceDescriptor) { LayerSourceDescriptor layerSourceDescriptor = (LayerSourceDescriptor) value; label.setText("<html><b>" + layerSourceDescriptor.getName() + "</b>"); label.setToolTipText(layerSourceDescriptor.getDescription()); } else { label.setText("Invalid"); } return label; } } }
6,322
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
HistoryComboBoxModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/HistoryComboBoxModel.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc; import org.esa.snap.ui.UserInputHistory; import javax.swing.ComboBoxModel; import javax.swing.event.EventListenerList; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; /** * <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i> */ public class HistoryComboBoxModel implements ComboBoxModel { private final UserInputHistory history; private EventListenerList listenerList; private String selectedItem; public HistoryComboBoxModel(UserInputHistory history) { this.history = history; listenerList = new EventListenerList(); } public UserInputHistory getHistory() { return history; } @Override public void setSelectedItem(Object anObject) { if (anObject instanceof String) { selectedItem = (String) anObject; history.push(selectedItem); fireContentChanged(); } } @Override public Object getSelectedItem() { return selectedItem; } @Override public int getSize() { return history.getNumEntries(); } @Override public Object getElementAt(int index) { return history.getEntries()[index]; } @Override public void addListDataListener(ListDataListener listener) { listenerList.add(ListDataListener.class, listener); } @Override public void removeListDataListener(ListDataListener listener) { listenerList.remove(ListDataListener.class, listener); } private void fireContentChanged() { final ListDataListener[] listDataListeners = listenerList.getListeners(ListDataListener.class); for (ListDataListener listener : listDataListeners) { listener.contentsChanged(new ListDataEvent(this, ListDataEvent.CONTENTS_CHANGED, 0, 0)); } } }
2,654
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WmsWorker.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsWorker.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.wms; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.geotools.ows.wms.CRSEnvelope; import org.geotools.ows.wms.Layer; import org.geotools.ows.wms.StyleImpl; import org.geotools.ows.wms.WebMapServer; import java.awt.Dimension; import java.net.URL; import java.util.List; abstract class WmsWorker extends ProgressMonitorSwingWorker<com.bc.ceres.glayer.Layer, Object> { private final LayerSourcePageContext context; private final Dimension mapImageSize; protected WmsWorker(LayerSourcePageContext context, Dimension mapImageSize) { super(context.getWindow(), "WMS Access"); this.context = context; this.mapImageSize = mapImageSize; } public LayerSourcePageContext getContext() { return context; } @Override protected com.bc.ceres.glayer.Layer doInBackground(ProgressMonitor pm) throws Exception { try { pm.beginTask("Loading layer from WMS", ProgressMonitor.UNKNOWN); final LayerType wmsType = LayerTypeRegistry.getLayerType(WmsLayerType.class.getName()); final PropertySet template = wmsType.createLayerConfig(getContext().getLayerContext()); final RasterDataNode raster = SnapApp.getDefault().getSelectedProductSceneView().getRaster(); template.setValue(WmsLayerType.PROPERTY_NAME_RASTER, raster); template.setValue(WmsLayerType.PROPERTY_NAME_IMAGE_SIZE, mapImageSize); URL wmsUrl = (URL) context.getPropertyValue(WmsLayerSource.PROPERTY_NAME_WMS_URL); template.setValue(WmsLayerType.PROPERTY_NAME_URL, wmsUrl); StyleImpl selectedStyle = (StyleImpl) context.getPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_STYLE); String styleName = null; if (selectedStyle != null) { styleName = selectedStyle.getName(); } template.setValue(WmsLayerType.PROPERTY_NAME_STYLE_NAME, styleName); WebMapServer wms = (WebMapServer) context.getPropertyValue(WmsLayerSource.PROPERTY_NAME_WMS); final List<Layer> layerList = wms.getCapabilities().getLayerList(); Layer selectedLayer = (Layer) context.getPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_LAYER); template.setValue(WmsLayerType.PROPERTY_NAME_LAYER_INDEX, layerList.indexOf(selectedLayer)); CRSEnvelope crsEnvelope = (CRSEnvelope) context.getPropertyValue(WmsLayerSource.PROPERTY_NAME_CRS_ENVELOPE); template.setValue(WmsLayerType.PROPERTY_NAME_CRS_ENVELOPE, crsEnvelope); final com.bc.ceres.glayer.Layer layer = wmsType.createLayer(getContext().getLayerContext(), template); layer.setName(selectedLayer.getName()); return layer; } finally { pm.done(); } } }
3,897
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WmsLayerWorker.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsLayerWorker.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.wms; import com.bc.ceres.glayer.Layer; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.esa.snap.ui.product.ProductSceneView; import java.awt.Dimension; import java.util.concurrent.ExecutionException; class WmsLayerWorker extends WmsWorker { private final Layer rootLayer; WmsLayerWorker(LayerSourcePageContext pageContext, RasterDataNode raster) { super(pageContext, getFinalImageSize(raster)); this.rootLayer = pageContext.getLayerContext().getRootLayer(); } @Override protected void done() { try { Layer layer = get(); try { ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); rootLayer.getChildren().add(sceneView.getFirstImageLayerIndex(), layer); } catch (Exception e) { getContext().showErrorDialog(e.getMessage()); } } catch (ExecutionException e) { getContext().showErrorDialog( String.format("Error while expecting WMS response:\n%s", e.getCause().getMessage())); } catch (InterruptedException ignored) { // ok } } private static Dimension getFinalImageSize(RasterDataNode raster) { int width; int height; double ratio = raster.getRasterWidth() / (double) raster.getRasterHeight(); if (ratio >= 1.0) { width = Math.min(1280, raster.getRasterWidth()); height = (int) Math.round(width / ratio); } else { height = Math.min(1280, raster.getRasterHeight()); width = (int) Math.round(height * ratio); } return new Dimension(width, height); } }
2,577
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WmsLayerSource.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsLayerSource.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.wms; import org.esa.snap.core.datamodel.CrsGeoCoding; import org.esa.snap.core.datamodel.MapGeoCoding; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSource; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.esa.snap.ui.product.ProductSceneView; public class WmsLayerSource implements LayerSource { static final String PROPERTY_NAME_WMS = "wms"; static final String PROPERTY_NAME_WMS_URL = "wmsUrl"; static final String PROPERTY_NAME_WMS_CAPABILITIES = "wmsCapabilities"; static final String PROPERTY_NAME_SELECTED_LAYER = "selectedLayer"; static final String PROPERTY_NAME_SELECTED_STYLE = "selectedStyle"; static final String PROPERTY_NAME_CRS_ENVELOPE = "crsEnvelope"; @Override public boolean isApplicable(LayerSourcePageContext pageContext) { ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); RasterDataNode raster = view.getRaster(); return raster.getGeoCoding() instanceof MapGeoCoding || raster.getGeoCoding() instanceof CrsGeoCoding; } @Override public boolean hasFirstPage() { return true; } @Override public AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext) { return new WmsAssistantPage1(); } @Override public boolean canFinish(LayerSourcePageContext pageContext) { return false; } @Override public boolean performFinish(LayerSourcePageContext pageContext) { return false; } @Override public void cancel(LayerSourcePageContext pageContext) { } static void insertWmsLayer(LayerSourcePageContext pageContext) { ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); RasterDataNode raster = view.getRaster(); WmsLayerWorker layerWorker = new WmsLayerWorker(pageContext, raster); layerWorker.execute(); // todo - don't close dialog before image is downloaded! (nf) } }
2,877
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WmsLayerType.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsLayerType.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.wms; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.dom.DomConverter; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerContext; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.glayer.annotations.LayerTypeMetadata; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.glevel.MultiLevelSource; import com.bc.ceres.glevel.support.DefaultMultiLevelModel; import com.bc.ceres.glevel.support.DefaultMultiLevelSource; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.RasterDataNode; import org.geotools.ows.ServiceException; import org.geotools.ows.wms.CRSEnvelope; import org.geotools.ows.wms.StyleImpl; import org.geotools.ows.wms.WebMapServer; import org.geotools.ows.wms.request.GetMapRequest; import org.geotools.ows.wms.response.GetMapResponse; import javax.imageio.ImageIO; import javax.media.jai.PlanarImage; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; /** * Layer type for layer that displays images coming from an OGC WMS. * * @author Marco Peters * @since BEAM 4.6 */ @LayerTypeMetadata(name = "WmsLayerType", aliasNames = {"org.esa.snap.rcp.layermanager.layersrc.wms.WmsLayerType"}) public class WmsLayerType extends ImageLayer.Type { public static final String PROPERTY_NAME_RASTER = "raster"; public static final String PROPERTY_NAME_URL = "serverUrl"; public static final String PROPERTY_NAME_LAYER_INDEX = "layerIndex"; public static final String PROPERTY_NAME_CRS_ENVELOPE = "crsEnvelope"; public static final String PROPERTY_NAME_STYLE_NAME = "styleName"; public static final String PROPERTY_NAME_IMAGE_SIZE = "imageSize"; @Override public Layer createLayer(LayerContext ctx, PropertySet configuration) { final WebMapServer mapServer; try { mapServer = getWmsServer(configuration); } catch (Exception e) { final String message = String.format("Not able to access Web Mapping Server: %s", configuration.<URL>getValue(WmsLayerType.PROPERTY_NAME_URL)); throw new RuntimeException(message, e); } final int layerIndex = configuration.getValue(WmsLayerType.PROPERTY_NAME_LAYER_INDEX); final org.geotools.ows.wms.Layer wmsLayer = getLayer(mapServer, layerIndex); final MultiLevelSource multiLevelSource = createMultiLevelSource(configuration, mapServer, wmsLayer); final ImageLayer.Type imageLayerType = LayerTypeRegistry.getLayerType(ImageLayer.Type.class); final PropertySet config = imageLayerType.createLayerConfig(ctx); config.setValue(ImageLayer.PROPERTY_NAME_MULTI_LEVEL_SOURCE, multiLevelSource); config.setValue(ImageLayer.PROPERTY_NAME_BORDER_SHOWN, false); config.setValue(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_SHOWN, false); final ImageLayer wmsImageLayer = new ImageLayer(this, multiLevelSource, config); wmsImageLayer.setName(wmsLayer.getName()); return wmsImageLayer; } @Override public PropertySet createLayerConfig(LayerContext ctx) { final PropertyContainer template = new PropertyContainer(); template.addProperty(Property.create(PROPERTY_NAME_RASTER, RasterDataNode.class)); template.addProperty(Property.create(PROPERTY_NAME_URL, URL.class)); template.addProperty(Property.create(PROPERTY_NAME_LAYER_INDEX, Integer.class)); template.addProperty(Property.create(PROPERTY_NAME_STYLE_NAME, String.class)); template.addProperty(Property.create(PROPERTY_NAME_IMAGE_SIZE, Dimension.class)); template.addProperty(Property.create(PROPERTY_NAME_CRS_ENVELOPE, CRSEnvelope.class)); template.getDescriptor(PROPERTY_NAME_CRS_ENVELOPE).setDomConverter(new CRSEnvelopeDomConverter()); return template; } private static DefaultMultiLevelSource createMultiLevelSource(PropertySet configuration, WebMapServer wmsServer, org.geotools.ows.wms.Layer layer) { DefaultMultiLevelSource multiLevelSource; final String styleName = configuration.getValue(WmsLayerType.PROPERTY_NAME_STYLE_NAME); final Dimension size = configuration.getValue(WmsLayerType.PROPERTY_NAME_IMAGE_SIZE); try { List<StyleImpl> styleList = layer.getStyles(); StyleImpl style = null; if (!styleList.isEmpty()) { style = styleList.get(0); for (StyleImpl currentstyle : styleList) { if (currentstyle.getName().equals(styleName)) { style = currentstyle; } } } CRSEnvelope crsEnvelope = configuration.getValue(WmsLayerType.PROPERTY_NAME_CRS_ENVELOPE); GetMapRequest mapRequest = wmsServer.createGetMapRequest(); mapRequest.addLayer(layer, style); mapRequest.setTransparent(true); mapRequest.setDimensions(size.width, size.height); mapRequest.setSRS(crsEnvelope.getEPSGCode()); // e.g. "EPSG:4326" = Geographic CRS mapRequest.setBBox(crsEnvelope); mapRequest.setFormat("image/png"); BufferedImage renderedImage = downloadWmsImage(mapRequest, wmsServer); final PlanarImage image = PlanarImage.wrapRenderedImage(renderedImage); RasterDataNode raster = configuration.getValue(WmsLayerType.PROPERTY_NAME_RASTER); final int sceneWidth = raster.getRasterWidth(); final int sceneHeight = raster.getRasterHeight(); AffineTransform i2mTransform = Product.findImageToModelTransform(raster.getGeoCoding()); i2mTransform.scale((double) sceneWidth / image.getWidth(), (double) sceneHeight / image.getHeight()); final Rectangle2D bounds = DefaultMultiLevelModel.getModelBounds(i2mTransform, image); final DefaultMultiLevelModel multiLevelModel = new DefaultMultiLevelModel(1, i2mTransform, bounds); multiLevelSource = new DefaultMultiLevelSource(image, multiLevelModel); } catch (Exception e) { throw new IllegalStateException(String.format("Failed to access WMS: %s", configuration.<URL>getValue(WmsLayerType.PROPERTY_NAME_URL)), e); } return multiLevelSource; } private static org.geotools.ows.wms.Layer getLayer(WebMapServer server, int layerIndex) { return server.getCapabilities().getLayerList().get(layerIndex); } private static WebMapServer getWmsServer(PropertySet configuration) throws IOException, ServiceException { return new WebMapServer(configuration.<URL>getValue(WmsLayerType.PROPERTY_NAME_URL)); } private static BufferedImage downloadWmsImage(GetMapRequest mapRequest, WebMapServer wms) throws IOException, ServiceException { GetMapResponse mapResponse = wms.issueRequest(mapRequest); try (InputStream inputStream = mapResponse.getInputStream()) { return ImageIO.read(inputStream); } } private static class CRSEnvelopeDomConverter implements DomConverter { private static final String SRS_NAME = "srsName"; private static final String MIN_X = "minX"; private static final String MIN_Y = "minY"; private static final String MAX_X = "maxX"; private static final String MAX_Y = "maxY"; @Override public Class<?> getValueType() { return CRSEnvelope.class; } @Override public Object convertDomToValue(DomElement parentElement, Object value) { try { String srsName = parentElement.getChild(SRS_NAME).getValue(); double minX = Double.parseDouble(parentElement.getChild(MIN_X).getValue()); double minY = Double.parseDouble(parentElement.getChild(MIN_Y).getValue()); double maxX = Double.parseDouble(parentElement.getChild(MAX_X).getValue()); double maxY = Double.parseDouble(parentElement.getChild(MAX_Y).getValue()); value = new CRSEnvelope(srsName, minX, minY, maxX, maxY); } catch (Exception e) { throw new IllegalArgumentException(e); } return value; } @Override public void convertValueToDom(Object value, DomElement parentElement) { CRSEnvelope crsEnvelope = (CRSEnvelope) value; DomElement srsName = parentElement.createChild(SRS_NAME); srsName.setValue(crsEnvelope.getSRSName()); DomElement minX = parentElement.createChild(MIN_X); minX.setValue(Double.toString(crsEnvelope.getMinX())); DomElement minY = parentElement.createChild(MIN_Y); minY.setValue(Double.toString(crsEnvelope.getMinY())); DomElement maxX = parentElement.createChild(MAX_X); maxX.setValue(Double.toString(crsEnvelope.getMaxX())); DomElement maxY = parentElement.createChild(MAX_Y); maxY.setValue(Double.toString(crsEnvelope.getMaxY())); } } }
10,294
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WmsAssistantPage1.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsAssistantPage1.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.wms; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.layermanager.layersrc.HistoryComboBoxModel; import org.esa.snap.ui.UserInputHistory; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.geotools.ows.wms.WMSCapabilities; import org.geotools.ows.wms.WebMapServer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.Component; import java.awt.Cursor; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Window; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.net.URL; class WmsAssistantPage1 extends AbstractLayerSourceAssistantPage { private JComboBox wmsUrlBox; private static final String PROPERTY_WMS_HISTORY = "WmsAssistant.wms.history"; private UserInputHistory history; WmsAssistantPage1() { super("Select WMS"); } @Override public boolean validatePage() { if (wmsUrlBox.getSelectedItem() != null) { String wmsUrl = wmsUrlBox.getSelectedItem().toString(); return wmsUrl != null && !wmsUrl.trim().isEmpty(); } return false; } @Override public boolean hasNextPage() { return true; } @Override public AbstractLayerSourceAssistantPage getNextPage() { LayerSourcePageContext pageContext = getContext(); WebMapServer wms = null; WMSCapabilities wmsCapabilities = null; String wmsUrl = wmsUrlBox.getSelectedItem().toString(); if (wmsUrl != null && !wmsUrl.isEmpty()) { try { wms = getWms(pageContext.getWindow(), wmsUrl); wmsCapabilities = wms.getCapabilities(); } catch (Exception e) { e.printStackTrace(); pageContext.showErrorDialog("Failed to access WMS:\n" + e.getMessage()); } } history.copyInto(SnapApp.getDefault().getPreferences()); if (wms != null && wmsCapabilities != null) { pageContext.setPropertyValue(WmsLayerSource.PROPERTY_NAME_WMS, wms); pageContext.setPropertyValue(WmsLayerSource.PROPERTY_NAME_WMS_CAPABILITIES, wmsCapabilities); return new WmsAssistantPage2(); } else { return null; } } @Override public boolean canFinish() { return false; } @Override public Component createPageComponent() { GridBagConstraints gbc = new GridBagConstraints(); final JPanel panel = new JPanel(new GridBagLayout()); gbc.anchor = GridBagConstraints.WEST; gbc.gridy = 0; gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; panel.add(new JLabel("URL for WMS (e.g. http://<host>/<server>):"), gbc); gbc.weightx = 1; gbc.weighty = 0; gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 1; history = new UserInputHistory(8, PROPERTY_WMS_HISTORY); history.initBy(SnapApp.getDefault().getPreferences()); if (history.getNumEntries() == 0) { history.push("http://geoservice.dlr.de/basemap/wms"); history.push("https://www.geoseaportal.de/wss/service/StaticInformation_Background/guest"); } wmsUrlBox = new JComboBox(new HistoryComboBoxModel(history)); wmsUrlBox.setEditable(true); panel.add(wmsUrlBox, gbc); wmsUrlBox.addItemListener(new MyItemListener()); return panel; } private WebMapServer getWms(Window window, String wmsUrl) throws Exception { WebMapServer wms; try { window.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); URL url = new URL(wmsUrl); wms = new WebMapServer(url); getContext().setPropertyValue(WmsLayerSource.PROPERTY_NAME_WMS_URL, url); } finally { window.setCursor(Cursor.getDefaultCursor()); } return wms; } private class MyItemListener implements ItemListener { @Override public void itemStateChanged(ItemEvent e) { getContext().updateState(); } } }
5,088
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WmsAssistantPage2.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsAssistantPage2.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.wms; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.geotools.ows.wms.CRSEnvelope; import org.geotools.ows.wms.Layer; import org.geotools.ows.wms.StyleImpl; import org.geotools.ows.wms.WMSCapabilities; import org.geotools.referencing.CRS; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.ListSelectionModel; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.WeakHashMap; class WmsAssistantPage2 extends AbstractLayerSourceAssistantPage { private JLabel infoLabel; private JTree layerTree; private CoordinateReferenceSystem modelCRS; WmsAssistantPage2() { super("Select Layer"); } @Override public boolean performFinish() { WmsLayerSource.insertWmsLayer(getContext()); return true; } @Override public AbstractLayerSourceAssistantPage getNextPage() { return new WmsAssistantPage3(); } @Override public boolean hasNextPage() { return true; } @Override public boolean validatePage() { return getContext().getPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_LAYER) != null; } @Override public Component createPageComponent() { JPanel panel = new JPanel(new BorderLayout(4, 4)); panel.setBorder(new EmptyBorder(4, 4, 4, 4)); panel.add(new JLabel("Available layers:"), BorderLayout.NORTH); LayerSourcePageContext context = getContext(); modelCRS = (CoordinateReferenceSystem) context.getLayerContext().getCoordinateReferenceSystem(); WMSCapabilities wmsCapabilities = (WMSCapabilities) context.getPropertyValue( WmsLayerSource.PROPERTY_NAME_WMS_CAPABILITIES); layerTree = new JTree(new WmsTreeModel(wmsCapabilities.getLayer())); layerTree.setRootVisible(false); layerTree.setShowsRootHandles(true); layerTree.setExpandsSelectedPaths(true); layerTree.setCellRenderer(new MyDefaultTreeCellRenderer()); layerTree.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); layerTree.getSelectionModel().addTreeSelectionListener(new LayerTreeSelectionListener()); panel.add(new JScrollPane(layerTree), BorderLayout.CENTER); infoLabel = new JLabel(" "); panel.add(infoLabel, BorderLayout.SOUTH); getContext().setPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_LAYER, null); return panel; } @SuppressWarnings({"unchecked"}) private String getMatchingCRSCode(Layer layer) { Set<String> srsSet = layer.getSrs(); String modelSRS = CRS.toSRS(modelCRS); if (modelSRS != null) { for (String srs : srsSet) { try { final CoordinateReferenceSystem crs = CRS.decode(srs,true); if (CRS.equalsIgnoreMetadata(crs, modelCRS)) { return srs; } } catch (FactoryException ignore) { } } } return null; } static String getLatLonBoundingBoxText(CRSEnvelope bbox) { if (bbox == null) { return "Lon = ?° ... ?°, Lat = ?° ... ?°"; } return String.format("Lon = %.3f° ... %.3f°, Lat = %.3f° ... %.3f°", bbox.getMinX(), bbox.getMaxX(), bbox.getMinY(), bbox.getMaxY()); } private static class MyDefaultTreeCellRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); String text; if (value instanceof Layer) { String title; Layer layer = (Layer) value; title = layer.getTitle(); if (title == null) { title = layer.getName(); } if (title == null) { title = layer.toString(); } StringBuilder sb = new StringBuilder(String.format("<html><b>%s</b>", title)); Layer[] children = layer.getChildren(); if (children.length > 1) { sb.append(String.format(" (%d children)", children.length)); } else if (children.length == 1) { sb.append(" (1 child)"); } text = sb.append("</html>").toString(); } else if (value instanceof WMSCapabilities) { WMSCapabilities capabilities = (WMSCapabilities) value; text = String.format("<html><b>%s</b></html>", capabilities.getService().getName()); } else { text = String.format("<html><b>%s</b></html>", value); } label.setText(text); return label; } } private class LayerTreeSelectionListener implements TreeSelectionListener { @Override public void valueChanged(TreeSelectionEvent e) { LayerSourcePageContext context = getContext(); TreePath selectedLayerPath = layerTree.getSelectionModel().getSelectionPath(); Layer selectedLayer = (Layer) selectedLayerPath.getLastPathComponent(); if (selectedLayer != null) { String crsCode = getMatchingCRSCode(selectedLayer); if (crsCode == null) { infoLabel.setForeground(Color.RED.darker()); infoLabel.setText("Coordinate system not supported."); } else { RasterDataNode raster = SnapApp.getDefault().getSelectedProductSceneView().getRaster(); AffineTransform g2mTransform = Product.findImageToModelTransform(raster.getGeoCoding()); Rectangle2D bounds = g2mTransform.createTransformedShape( new Rectangle(0, 0, raster.getRasterWidth(), raster.getRasterHeight())).getBounds2D(); CRSEnvelope crsEnvelope = new CRSEnvelope(crsCode, bounds.getMinX(), bounds.getMinY(), bounds.getMaxX(), bounds.getMaxY()); context.setPropertyValue(WmsLayerSource.PROPERTY_NAME_CRS_ENVELOPE, crsEnvelope); List<StyleImpl> styles = selectedLayer.getStyles(); if (!styles.isEmpty()) { context.setPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_STYLE, styles.get(0)); } else { context.setPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_STYLE, null); } context.setPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_LAYER, selectedLayer); infoLabel.setForeground(Color.DARK_GRAY); infoLabel.setText(getLatLonBoundingBoxText(selectedLayer.getLatLonBoundingBox())); } } else { infoLabel.setForeground(Color.DARK_GRAY); infoLabel.setText(""); } context.updateState(); } } private static class WmsTreeModel implements TreeModel { private final WeakHashMap<TreeModelListener, Object> treeModelListeners; private Layer rootLayer; private WmsTreeModel(Layer rootLayer) { this.rootLayer = rootLayer; treeModelListeners = new WeakHashMap<>(); } @Override public Object getRoot() { return rootLayer; } @Override public Object getChild(Object parent, int index) { Layer layer = (Layer) parent; return layer.getChildren()[index]; } @Override public int getChildCount(Object parent) { Layer layer = (Layer) parent; return layer.getChildren().length; } @Override public boolean isLeaf(Object node) { Layer layer = (Layer) node; return layer.getChildren() != null && layer.getChildren().length == 0; } @Override public int getIndexOfChild(Object parent, Object child) { Layer layer = (Layer) parent; int index = Arrays.binarySearch(layer.getChildren(), child); return index < 0 ? -1 : index; } @Override public void valueForPathChanged(TreePath path, Object newValue) { fireTreeNodeChanged(path); } @Override public void addTreeModelListener(TreeModelListener l) { treeModelListeners.put(l, ""); } @Override public void removeTreeModelListener(TreeModelListener l) { treeModelListeners.remove(l); } protected void fireTreeNodeChanged(TreePath treePath) { TreeModelEvent event = new TreeModelEvent(this, treePath); for (TreeModelListener treeModelListener : treeModelListeners.keySet()) { treeModelListener.treeNodesChanged(event); } } } }
11,109
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WmsAssistantPage3.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/wms/WmsAssistantPage3.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.wms; import com.bc.ceres.glayer.swing.LayerCanvas; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.geotools.ows.wms.CRSEnvelope; import org.geotools.ows.wms.Layer; import org.geotools.ows.wms.StyleImpl; import org.opengis.util.InternationalString; import javax.swing.DefaultListCellRenderer; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.List; import java.util.concurrent.ExecutionException; class WmsAssistantPage3 extends AbstractLayerSourceAssistantPage { private JComboBox styleList; private JLabel messageLabel; private WmsWorker previewWorker; private Throwable error; private JPanel mapPanel; WmsAssistantPage3() { super("Layer Preview"); } @Override public boolean validatePage() { return error == null; } @Override public Component createPageComponent() { final LayerSourcePageContext context = getContext(); Layer selectedLayer = (Layer) context.getPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_LAYER); JLabel infoLabel = new JLabel(WmsAssistantPage2.getLatLonBoundingBoxText(selectedLayer.getLatLonBoundingBox())); List<StyleImpl> styles = selectedLayer.getStyles(); styleList = new JComboBox(styles.toArray(new StyleImpl[styles.size()])); styleList.setSelectedItem(context.getPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_STYLE)); styleList.setRenderer(new StyleListCellRenderer()); styleList.addItemListener(new StyleItemListener()); JPanel panel2 = new JPanel(new BorderLayout(4, 4)); panel2.setBorder(new EmptyBorder(4, 4, 4, 4)); panel2.add(new JLabel("Style:"), BorderLayout.WEST); panel2.add(styleList, BorderLayout.EAST); JPanel panel3 = new JPanel(new BorderLayout(4, 4)); panel3.setBorder(new EmptyBorder(4, 4, 4, 4)); panel3.add(new JLabel(String.format("<html><b>%s</b></html>", selectedLayer.getTitle())), BorderLayout.CENTER); panel3.add(panel2, BorderLayout.EAST); mapPanel = new JPanel(new BorderLayout()); messageLabel = new JLabel(); messageLabel.setHorizontalTextPosition(SwingConstants.CENTER); messageLabel.setVerticalTextPosition(SwingConstants.CENTER); mapPanel.add(messageLabel, BorderLayout.CENTER); JPanel panel = new JPanel(new BorderLayout(4, 4)); panel.setBorder(new EmptyBorder(4, 4, 4, 4)); panel.add(panel3, BorderLayout.NORTH); panel.add(mapPanel, BorderLayout.CENTER); panel.add(infoLabel, BorderLayout.SOUTH); panel.addAncestorListener(new AncestorListener() { @Override public void ancestorAdded(AncestorEvent event) { if (mapPanel.getComponent(0) instanceof JLabel) { updatePreview(); } } @Override public void ancestorMoved(AncestorEvent event) { } @Override public void ancestorRemoved(AncestorEvent event) { cancelPreviewWorker(); } } ); return panel; } @Override public boolean performFinish() { WmsLayerSource.insertWmsLayer(getContext()); return true; } @Override public void performCancel() { cancelPreviewWorker(); super.performCancel(); } private void updatePreview() { cancelPreviewWorker(); showMessage("<html><i>Loading map...</i></html>"); CRSEnvelope crsEnvelope = (CRSEnvelope) getContext().getPropertyValue(WmsLayerSource.PROPERTY_NAME_CRS_ENVELOPE); previewWorker = new WmsPreviewWorker(getContext(), getPreviewSize(crsEnvelope)); previewWorker.execute(); // todo - AppContext.addWorker(previewWorker); (nf) } private void cancelPreviewWorker() { if (previewWorker != null && !previewWorker.isDone()) { try { previewWorker.cancel(true); } catch (Throwable ignore) { // ok } } } private Dimension getPreviewSize(CRSEnvelope crsEnvelope) { Dimension preferredSize = messageLabel.getSize(); if (preferredSize.width == 0 || preferredSize.height == 0) { preferredSize = new Dimension(400, 200); } return getPreviewImageSize(preferredSize, crsEnvelope); } private Dimension getPreviewImageSize(Dimension preferredSize, CRSEnvelope crsEnvelope) { int width; int height; double ratio = (crsEnvelope.getMaxX() - crsEnvelope.getMinX()) / (crsEnvelope.getMaxY() - crsEnvelope.getMinY()); if (ratio >= 1.0) { width = preferredSize.width; height = (int) Math.round(preferredSize.width / ratio); } else { width = (int) Math.round(preferredSize.height * ratio); height = preferredSize.height; } return new Dimension(width, height); } private void showMessage(String message) { messageLabel.setIcon(null); messageLabel.setText(message); mapPanel.removeAll(); mapPanel.add(messageLabel, BorderLayout.CENTER); mapPanel.repaint(); } private void addLayerCanvas(LayerCanvas canvas) { mapPanel.removeAll(); mapPanel.add(canvas, BorderLayout.CENTER); mapPanel.validate(); } private class StyleItemListener implements ItemListener { @Override public void itemStateChanged(ItemEvent e) { getContext().setPropertyValue(WmsLayerSource.PROPERTY_NAME_SELECTED_STYLE, styleList.getSelectedItem()); getContext().updateState(); updatePreview(); } } private static class StyleListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); String text = null; if (value != null) { StyleImpl style = (StyleImpl) value; InternationalString title = style.getTitle(); text = title.toString(); } label.setText(text); return label; } } private class WmsPreviewWorker extends WmsWorker { private WmsPreviewWorker(LayerSourcePageContext pageContext, Dimension mapImageSize) { super(pageContext, mapImageSize); } @Override protected void done() { try { error = null; final com.bc.ceres.glayer.Layer layer = get(); final LayerCanvas layerCanvas = new LayerCanvas(layer); layerCanvas.getViewport().setModelYAxisDown(false); addLayerCanvas(layerCanvas); } catch (ExecutionException e) { error = e.getCause(); showMessage(String.format("<html><b>Error:</b> <i>%s</i></html>", error.getMessage())); e.printStackTrace(); } catch (InterruptedException ignored) { // ok } finally { getContext().updateState(); } } } }
8,641
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SLDUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/SLDUtils.java
package org.esa.snap.rcp.layermanager.layersrc.shapefile; import com.bc.ceres.swing.figure.FigureStyle; import com.bc.ceres.swing.figure.support.DefaultFigureStyle; import org.esa.snap.core.datamodel.PlainFeatureFactory; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.DefaultFeatureCollection; import org.geotools.feature.FeatureIterator; import org.geotools.feature.FeatureTypes; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.simple.SimpleFeatureTypeBuilder; import org.geotools.styling.Stroke; import org.geotools.styling.*; import org.geotools.xml.styling.SLDParser; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.Name; import org.opengis.filter.Filter; import java.awt.*; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Set; public class SLDUtils { private static final StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null); public static File getSLDFile(File shapeFile) { String filename = shapeFile.getAbsolutePath(); if (filename.endsWith(".shp") || filename.endsWith(".dbf") || filename.endsWith(".shx")) { filename = filename.substring(0, filename.length() - 4); filename += ".sld"; } else if (filename.endsWith(".SHP") || filename.endsWith(".DBF") || filename.endsWith(".SHX")) { filename = filename.substring(0, filename.length() - 4); filename += ".SLD"; } return new File(filename); } public static Style[] loadSLD(File shapeFile) { File sld = getSLDFile(shapeFile); if (sld.exists()) { return createFromSLD(sld); } else { return new Style[0]; } } public static Style[] createFromSLD(File sld) { try { SLDParser stylereader = new SLDParser(styleFactory, sld.toURI().toURL()); return stylereader.readXML(); } catch (IOException e) { e.printStackTrace(); } return new Style[0]; } /** * Converts the styling information in the style into CSS styles for all given features in the collection. * * @param style The style. * @param defaultCss The CSS default value. * @param featureCollection The collection that should be styled. * @param styledCollection the collection that will contain the styled features. */ public static void applyStyle(Style style, String defaultCss, DefaultFeatureCollection featureCollection, DefaultFeatureCollection styledCollection) { List<FeatureTypeStyle> featureTypeStyles = style.featureTypeStyles(); SimpleFeatureType featureType = featureCollection.getSchema(); SimpleFeatureType styledFeatureType = styledCollection.getSchema(); List<SimpleFeature> featuresToStyle = new ArrayList<>(featureCollection.size()); try (FeatureIterator<SimpleFeature> iterator = featureCollection.features()) { while (iterator.hasNext()) { featuresToStyle.add(iterator.next()); } } for (FeatureTypeStyle fts : featureTypeStyles) { if (isFeatureTypeStyleActive(featureType, fts)) { List<Rule> ruleList = new ArrayList<>(); List<Rule> elseRuleList = new ArrayList<>(); for (Rule rule : fts.rules()) { if (rule.isElseFilter()) { elseRuleList.add(rule); } else { ruleList.add(rule); } } Iterator<SimpleFeature> featureIterator = featuresToStyle.iterator(); while (featureIterator.hasNext()) { SimpleFeature simpleFeature = featureIterator.next(); SimpleFeature styledFeature = processRules(simpleFeature, styledFeatureType, ruleList, elseRuleList); if (styledFeature != null) { styledCollection.add(styledFeature); featureIterator.remove(); } } } } for (SimpleFeature simpleFeature : featuresToStyle) { styledCollection.add(createStyledFeature(styledFeatureType, simpleFeature, defaultCss)); } } public static SimpleFeature processRules(SimpleFeature sf, SimpleFeatureType styledSFT, List<Rule> ruleList, List<Rule> elseRuleList) { Filter filter; boolean doElse = true; Symbolizer[] symbolizers; for (Rule rule : ruleList) { filter = rule.getFilter(); if ((filter == null) || filter.evaluate(sf)) { doElse = false; symbolizers = rule.getSymbolizers(); SimpleFeature styledFeature = processSymbolizers(styledSFT, sf, symbolizers); if (styledFeature != null) { return styledFeature; } } } if (doElse) { for (Rule rule : elseRuleList) { symbolizers = rule.getSymbolizers(); SimpleFeature styledFeature = processSymbolizers(styledSFT, sf, symbolizers); if (styledFeature != null) { return styledFeature; } } } return null; } public static SimpleFeature processSymbolizers(SimpleFeatureType sft, SimpleFeature feature, Symbolizer[] symbolizers) { for (Symbolizer symbolizer : symbolizers) { if (symbolizer instanceof LineSymbolizer) { LineSymbolizer lineSymbolizer = (LineSymbolizer) symbolizer; Stroke stroke = lineSymbolizer.getStroke(); Color strokeColor = SLD.color(stroke); int width = SLD.width(stroke); FigureStyle figureStyle = DefaultFigureStyle.createLineStyle(strokeColor, new BasicStroke(width)); String cssStyle = figureStyle.toCssString(); return createStyledFeature(sft, feature, cssStyle); } else if (symbolizer instanceof PolygonSymbolizer) { PolygonSymbolizer polygonSymbolizer = (PolygonSymbolizer) symbolizer; Color fillColor = SLD.color(polygonSymbolizer.getFill()); Stroke stroke = polygonSymbolizer.getStroke(); Color strokeColor = SLD.color(stroke); int width = SLD.width(stroke); FigureStyle figureStyle = DefaultFigureStyle.createPolygonStyle(fillColor, strokeColor, new BasicStroke(width)); String cssStyle = figureStyle.toCssString(); return createStyledFeature(sft, feature, cssStyle); } } return null; } public static boolean isFeatureTypeStyleActive(SimpleFeatureType ftype, FeatureTypeStyle fts) { if (ftype.getTypeName() == null) { return false; } Set<Name> ftNames = fts.featureTypeNames(); for (Name ftName : ftNames) { if (ftype.getTypeName().equalsIgnoreCase(ftName.toString()) || FeatureTypes.isDecendedFrom(ftype, null, ftName.toString())) { return true; } } return false; } public static SimpleFeatureType createStyledFeatureType(SimpleFeatureType type) { SimpleFeatureTypeBuilder sftb = new SimpleFeatureTypeBuilder(); sftb.init(type); sftb.add(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, String.class); return sftb.buildFeatureType(); } public static SimpleFeature createStyledFeature(SimpleFeatureType type, SimpleFeature feature, String styleCSS) { SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(type); sfb.init(feature); sfb.set(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, styleCSS); return sfb.buildFeature(feature.getID()); } }
8,363
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FeatureLayer.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/FeatureLayer.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.grender.Rendering; import org.geotools.feature.FeatureCollection; import org.geotools.geometry.jts.ReferencedEnvelope; import org.geotools.map.MapContent; import org.geotools.map.MapViewport; import org.geotools.map.StyleLayer; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.renderer.label.LabelCacheImpl; import org.geotools.renderer.lite.LabelCache; import org.geotools.renderer.lite.StreamingRenderer; import org.geotools.styling.Fill; import org.geotools.styling.PolygonSymbolizer; import org.geotools.styling.Stroke; import org.geotools.styling.Style; import org.geotools.styling.StyleBuilder; import org.geotools.styling.TextSymbolizer; import org.geotools.styling.visitor.DuplicatingStyleVisitor; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.filter.expression.Expression; import org.opengis.referencing.crs.CoordinateReferenceSystem; import java.awt.Color; import java.awt.Rectangle; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.util.HashMap; import java.util.Map; /** * A layer that renders a feature collection using a given style. * <p> * Unstable API. Use at own risk. * * @author Marco Peters * @author Marco Zühlke * @version $Revision: $ $Date: $ * @since BEAM 4.6 */ public class FeatureLayer extends Layer { private final MapContent mapContent; //private MapContext mapContext; private CoordinateReferenceSystem crs; private StreamingRenderer renderer; private LabelCache labelCache; private double polyFillOpacity = 1.0; private double polyStrokeOpacity = 1.0; private double textOpacity = 1.0; private Rectangle2D modelBounds; public FeatureLayer(LayerType layerType, final FeatureCollection<SimpleFeatureType, SimpleFeature> fc, PropertySet configuration) { super(layerType, configuration); crs = fc.getSchema().getGeometryDescriptor().getCoordinateReferenceSystem(); if (crs == null) { // todo - check me! Why can this happen??? (nf) crs = DefaultGeographicCRS.WGS84; } final ReferencedEnvelope envelope = new ReferencedEnvelope(fc.getBounds(), crs); modelBounds = new Rectangle2D.Double(envelope.getMinX(), envelope.getMinY(), envelope.getWidth(), envelope.getHeight()); final MapViewport viewport = new MapViewport(); viewport.setBounds(envelope); viewport.setCoordinateReferenceSystem(crs); //viewport.setScreenArea((Rectangle) modelBounds); // @todo 1 tb/tb is this correct? 2023-04-24 // the renderer should know this and clip correctly mapContent = new MapContent(); mapContent.setViewport(viewport); final Style style = configuration.getValue(FeatureLayerType.PROPERTY_NAME_SLD_STYLE); org.geotools.map.FeatureLayer featureLayer = new org.geotools.map.FeatureLayer(fc, style); mapContent.addLayer(featureLayer); // @todo 1 tb/tb this is the old geoTools code // for the new one we're missing the CRS her -> check how this works tb 2023-04-24 //mapContext = new DefaultMapContext(crs); //mapContext.addLayer(fc, style); renderer = new StreamingRenderer(); workaroundLabelCacheBug(); style.accept(new RetrievingStyleVisitor()); // @todo 1 tb/tb this is the old geoTools code //renderer.setContext(mapContext); renderer.setMapContent(mapContent); } @Override protected Rectangle2D getLayerModelBounds() { return modelBounds; } public double getPolyFillOpacity() { return polyFillOpacity; } public double getPolyStrokeOpacity() { return polyStrokeOpacity; } public double getTextOpacity() { return textOpacity; } public void setPolyFillOpacity(double opacity) { if (opacity != polyFillOpacity) { polyFillOpacity = opacity; applyOpacity(); fireLayerDataChanged(null); } } public void setPolyStrokeOpacity(double opacity) { if (opacity != polyStrokeOpacity) { polyStrokeOpacity = opacity; applyOpacity(); fireLayerDataChanged(null); } } public void setTextOpacity(double opacity) { if (opacity != textOpacity) { textOpacity = opacity; applyOpacity(); fireLayerDataChanged(null); } } @Override protected void fireLayerPropertyChanged(PropertyChangeEvent event) { if ("transparency".equals(event.getPropertyName())) { applyOpacity(); } super.fireLayerPropertyChanged(event); } private void workaroundLabelCacheBug() { Map<Object, Object> hints = (Map<Object, Object>) renderer.getRendererHints(); if (hints == null) { hints = new HashMap<Object, Object>(); } if (hints.containsKey(StreamingRenderer.LABEL_CACHE_KEY)) { labelCache = (LabelCache) hints.get(StreamingRenderer.LABEL_CACHE_KEY); } else { labelCache = new LabelCacheImpl(); hints.put(StreamingRenderer.LABEL_CACHE_KEY, labelCache); } renderer.setRendererHints(hints); } @Override protected void renderLayer(final Rendering rendering) { Rectangle bounds = rendering.getViewport().getViewBounds(); final AffineTransform v2mTransform = rendering.getViewport().getViewToModelTransform(); Rectangle2D bounds2D = v2mTransform.createTransformedShape(bounds).getBounds2D(); ReferencedEnvelope mapArea = new ReferencedEnvelope(bounds2D, crs); //mapContext.setAreaOfInterest(mapArea); mapContent.getViewport().setBounds(mapArea); labelCache.clear(); // workaround for labelCache bug final AffineTransform modelToViewTransform = rendering.getViewport().getModelToViewTransform(); renderer.paint(rendering.getGraphics(), bounds, mapArea, modelToViewTransform); } private void applyOpacity() { final StyleLayer layer = (StyleLayer) mapContent.layers().get(0); if (layer != null) { Style style = layer.getStyle(); DuplicatingStyleVisitor copyStyle = new ApplyingStyleVisitor(); style.accept(copyStyle); layer.setStyle((Style) copyStyle.getCopy()); } } private class ApplyingStyleVisitor extends DuplicatingStyleVisitor { private final Expression polyFillExp; private final Expression polyStrokeExp; private final Expression textExp; private final Fill defaultTextFill; private ApplyingStyleVisitor() { StyleBuilder sb = new StyleBuilder(); final double layerOpacity = 1.0 - getTransparency(); polyFillExp = sb.literalExpression(polyFillOpacity * layerOpacity); polyStrokeExp = sb.literalExpression(polyStrokeOpacity * layerOpacity); textExp = sb.literalExpression(textOpacity * layerOpacity); defaultTextFill = sb.createFill(Color.BLACK, textOpacity * layerOpacity); } @Override public void visit(PolygonSymbolizer poly) { super.visit(poly); PolygonSymbolizer polyCopy = (PolygonSymbolizer) pages.peek(); Fill polyFill = polyCopy.getFill(); if (polyFill != null) { polyFill.setOpacity(polyFillExp); } Stroke polyStroke = polyCopy.getStroke(); if (polyStroke != null) { polyStroke.setOpacity(polyStrokeExp); } } @Override public void visit(TextSymbolizer text) { super.visit(text); TextSymbolizer textCopy = (TextSymbolizer) pages.peek(); Fill textFill = textCopy.getFill(); if (textFill != null) { textFill.setOpacity(textExp); } else { textCopy.setFill(defaultTextFill); } } } private class RetrievingStyleVisitor extends DuplicatingStyleVisitor { @Override public void visit(PolygonSymbolizer poly) { super.visit(poly); PolygonSymbolizer polyCopy = (PolygonSymbolizer) pages.peek(); Fill polyFill = polyCopy.getFill(); if (polyFill != null) { Expression opacityExpression = polyFill.getOpacity(); if (opacityExpression != null) { polyFillOpacity = (opacityExpression.evaluate(opacityExpression, Double.class)); } } Stroke polyStroke = polyCopy.getStroke(); if (polyStroke != null) { Expression opacityExpression = polyStroke.getOpacity(); if (opacityExpression != null) { polyStrokeOpacity = opacityExpression.evaluate(opacityExpression, Double.class); } } } @Override public void visit(TextSymbolizer text) { super.visit(text); TextSymbolizer textCopy = (TextSymbolizer) pages.peek(); Fill textFill = textCopy.getFill(); if (textFill != null) { Expression opacityExpression = textFill.getOpacity(); if (opacityExpression != null) { textOpacity = opacityExpression.evaluate(opacityExpression, Double.class); } } } } }
10,571
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FeatureLayerType.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/FeatureLayerType.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import com.bc.ceres.binding.*; import com.bc.ceres.binding.dom.DefaultDomConverter; import com.bc.ceres.binding.dom.DomConverter; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.binding.dom.XppDomElement; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerContext; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.annotations.LayerTypeMetadata; import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier; import com.thoughtworks.xstream.io.xml.XppDomWriter; import com.thoughtworks.xstream.io.xml.XppReader; import org.esa.snap.core.util.FeatureUtils; import org.geotools.data.FeatureSource; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.FeatureCollection; import org.geotools.referencing.CRS; import org.geotools.referencing.crs.DefaultGeographicCRS; import org.geotools.styling.Style; import org.geotools.xml.styling.SLDParser; import org.geotools.xml.styling.SLDTransformer; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import javax.xml.transform.TransformerException; import java.io.IOException; import java.io.StringReader; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * The type of a {@link FeatureLayer}. * <p> * Unstable API. Use at own risk. */ @LayerTypeMetadata(name = "FeatureLayerType", aliasNames = {"FeatureLayerType"}) public class FeatureLayerType extends LayerType { public static final String PROPERTY_NAME_SLD_STYLE = "sldStyle"; public static final String PROPERTY_NAME_FEATURE_COLLECTION = "featureCollection"; public static final String PROPERTY_NAME_FEATURE_COLLECTION_URL = "featureCollectionUrl"; public static final String PROPERTY_NAME_FEATURE_COLLECTION_CRS = "featureCollectionTargetCrs"; public static final String PROPERTY_NAME_FEATURE_COLLECTION_CLIP_GEOMETRY = "featureCollectionClipGeometry"; @Override public boolean isValidFor(LayerContext ctx) { return true; } @Override public Layer createLayer(LayerContext ctx, PropertySet configuration) { CoordinateReferenceSystem targetCrs = null; if (ctx != null) { targetCrs = (CoordinateReferenceSystem) ctx.getCoordinateReferenceSystem(); } FeatureCollection<SimpleFeatureType, SimpleFeature> fc; fc = (FeatureCollection<SimpleFeatureType, SimpleFeature>) configuration.getValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION); if (fc == null) { try { final URL url = (URL) configuration.getValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_URL); FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = FeatureUtils.getFeatureSource(url); fc = featureSource.getFeatures(); } catch (IOException e) { throw new IllegalArgumentException(e); } } final CoordinateReferenceSystem featureCrs = (CoordinateReferenceSystem) configuration.getValue( FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_CRS); final Geometry clipGeometry = (Geometry) configuration.getValue( FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_CLIP_GEOMETRY); fc = FeatureUtils.clipCollection(fc, featureCrs, clipGeometry, DefaultGeographicCRS.WGS84, null, targetCrs, ProgressMonitor.NULL); return new FeatureLayer(this, fc, configuration); } @Override public PropertySet createLayerConfig(LayerContext ctx) { final PropertyContainer configuration = new PropertyContainer(); // Mandatory Parameters configuration.addProperty(Property.create(PROPERTY_NAME_FEATURE_COLLECTION, FeatureCollection.class)); configuration.getDescriptor(PROPERTY_NAME_FEATURE_COLLECTION).setTransient(true); configuration.addProperty(Property.create(PROPERTY_NAME_SLD_STYLE, Style.class)); configuration.getDescriptor(PROPERTY_NAME_SLD_STYLE).setDomConverter(new StyleDomConverter()); configuration.getDescriptor(PROPERTY_NAME_SLD_STYLE).setNotNull(true); // Optional Parameters configuration.addProperty(Property.create(PROPERTY_NAME_FEATURE_COLLECTION_CLIP_GEOMETRY, Geometry.class)); configuration.getDescriptor(PROPERTY_NAME_FEATURE_COLLECTION_CLIP_GEOMETRY).setDomConverter( new GeometryDomConverter()); configuration.addProperty(Property.create(PROPERTY_NAME_FEATURE_COLLECTION_URL, URL.class)); configuration.addProperty(Property.create(PROPERTY_NAME_FEATURE_COLLECTION_CRS, CoordinateReferenceSystem.class)); configuration.getDescriptor(PROPERTY_NAME_FEATURE_COLLECTION_CRS).setDomConverter(new CRSDomConverter()); return configuration; } private static class StyleDomConverter implements DomConverter { @Override public Class<?> getValueType() { return Style.class; } @Override public Object convertDomToValue(DomElement parentElement, Object value) throws ConversionException, ValidationException { final DomElement child = parentElement.getChild(0); SLDParser s = new SLDParser(CommonFactoryFinder.getStyleFactory(null), new StringReader(child.toXml())); final Style[] styles = s.readXML(); return styles[0]; } @Override public void convertValueToDom(Object value, DomElement parentElement) throws ConversionException { Style style = (Style) value; final SLDTransformer transformer = new SLDTransformer(); transformer.setIndentation(2); try { final String s = transformer.transform(style); XppDomWriter domWriter = new XppDomWriter(); new HierarchicalStreamCopier().copy(new XppReader(new StringReader(s)), domWriter); parentElement.addChild(new XppDomElement(domWriter.getConfiguration())); } catch (TransformerException e) { throw new IllegalArgumentException(e); } } } private static class CRSDomConverter implements DomConverter { @Override public Class<?> getValueType() { return null; } @Override public Object convertDomToValue(DomElement parentElement, Object value) throws ConversionException, ValidationException { try { value = CRS.parseWKT(parentElement.getValue()); } catch (FactoryException e) { throw new IllegalArgumentException(e); } return value; } @Override public void convertValueToDom(Object value, DomElement parentElement) throws ConversionException { CoordinateReferenceSystem crs = (CoordinateReferenceSystem) value; parentElement.setValue(crs.toWKT()); } } private static class GeometryDomConverter implements DomConverter { @Override public Class<?> getValueType() { return Geometry.class; } @Override public Object convertDomToValue(DomElement parentElement, Object value) throws ConversionException, ValidationException { org.locationtech.jts.geom.GeometryFactory gf = new org.locationtech.jts.geom.GeometryFactory(); final DefaultDomConverter domConverter = new DefaultDomConverter(Coordinate.class); final DomElement[] children = parentElement.getChildren("coordinate"); List<Coordinate> coordList = new ArrayList<Coordinate>(); for (DomElement child : children) { final Coordinate coordinate = (Coordinate) domConverter.convertDomToValue(child, null); coordList.add(coordinate); } return gf.createPolygon(gf.createLinearRing(coordList.toArray(new Coordinate[coordList.size()])), null); } @Override public void convertValueToDom(Object value, DomElement parentElement) throws ConversionException { Geometry geom = (Geometry) value; final Coordinate[] coordinates = geom.getCoordinates(); final DefaultDomConverter domConverter = new DefaultDomConverter(Coordinate.class); for (Coordinate coordinate : coordinates) { final DomElement child = parentElement.createChild("coordinate"); domConverter.convertValueToDom(coordinate, child); } } } }
9,718
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ShapefileLoader.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/ShapefileLoader.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.LineString; import org.locationtech.jts.geom.MultiLineString; import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.geom.Polygon; import org.esa.snap.core.util.FeatureUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.esa.snap.ui.product.ProductSceneView; import org.geotools.factory.CommonFactoryFinder; import org.geotools.feature.FeatureCollection; import org.geotools.styling.FeatureTypeStyle; import org.geotools.styling.Fill; import org.geotools.styling.LineSymbolizer; import org.geotools.styling.PointSymbolizer; import org.geotools.styling.PolygonSymbolizer; import org.geotools.styling.Rule; import org.geotools.styling.SLD; import org.geotools.styling.Stroke; import org.geotools.styling.Style; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.FeatureType; import org.opengis.filter.FilterFactory; import org.opengis.referencing.crs.CoordinateReferenceSystem; import java.awt.Color; import java.io.File; import java.io.IOException; /** * @author Marco Peters * @since BEAM 4.6 */ class ShapefileLoader extends ProgressMonitorSwingWorker<Layer, Object> { private static final org.geotools.styling.StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null); private static final FilterFactory filterFactory = CommonFactoryFinder.getFilterFactory(null); private final LayerSourcePageContext context; ShapefileLoader(LayerSourcePageContext context) { super(context.getWindow(), "Loading Shapefile"); this.context = context; } protected LayerSourcePageContext getContext() { return context; } @Override protected Layer doInBackground(ProgressMonitor pm) throws Exception { try { pm.beginTask("Reading shapes", ProgressMonitor.UNKNOWN); final ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); final Geometry clipGeometry = FeatureUtils.createGeoBoundaryPolygon(sceneView.getProduct()); File file = new File((String) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FILE_PATH)); FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = getFeatureCollection(file); CoordinateReferenceSystem featureCrs = (CoordinateReferenceSystem) context.getPropertyValue( ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION_CRS); Style[] styles = getStyles(file, featureCollection); Style selectedStyle = getSelectedStyle(styles); final LayerType type = LayerTypeRegistry.getLayerType(FeatureLayerType.class.getName()); final PropertySet configuration = type.createLayerConfig(sceneView); configuration.setValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_URL, file.toURI().toURL()); configuration.setValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION, featureCollection); configuration.setValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_CRS, featureCrs); configuration.setValue(FeatureLayerType.PROPERTY_NAME_FEATURE_COLLECTION_CLIP_GEOMETRY, clipGeometry); configuration.setValue(FeatureLayerType.PROPERTY_NAME_SLD_STYLE, selectedStyle); Layer featureLayer = type.createLayer(sceneView, configuration); featureLayer.setName(file.getName()); featureLayer.setVisible(true); return featureLayer; } finally { pm.done(); } } private FeatureCollection<SimpleFeatureType, SimpleFeature> getFeatureCollection(File file) throws IOException { Object featureCollectionValue = context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION); FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection; if (featureCollectionValue == null) { featureCollection = FeatureUtils.getFeatureSource(file.toURI().toURL()).getFeatures(); } else { featureCollection = (FeatureCollection<SimpleFeatureType, SimpleFeature>) featureCollectionValue; } return featureCollection; } private Style getSelectedStyle(Style[] styles) { Style selectedStyle = (Style) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_SELECTED_STYLE); if (selectedStyle == null) { selectedStyle = styles[0]; context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_SELECTED_STYLE, styles[0]); } return selectedStyle; } private Style[] getStyles(File file, FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection) { Style[] styles = (Style[]) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_STYLES); if (styles == null || styles.length == 0) { styles = createStyle(file, featureCollection.getSchema()); context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_STYLES, styles); } return styles; } private static Style[] createStyle(File shapeFile, FeatureType schema) { final Style[] styles = SLDUtils.loadSLD(shapeFile); if (styles != null && styles.length > 0) { return styles; } Class<?> type = schema.getGeometryDescriptor().getType().getBinding(); if (type.isAssignableFrom(Polygon.class) || type.isAssignableFrom(MultiPolygon.class)) { return new Style[]{createPolygonStyle()}; } else if (type.isAssignableFrom(LineString.class) || type.isAssignableFrom(MultiLineString.class)) { return new Style[]{createLineStyle()}; } else { return new Style[]{createPointStyle()}; } } private static Style createPointStyle() { PointSymbolizer symbolizer = styleFactory.createPointSymbolizer(); symbolizer.getGraphic().setSize(filterFactory.literal(1)); Rule rule = styleFactory.createRule(); rule.symbolizers().add(symbolizer); FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(); fts.rules().add(rule); Style style = styleFactory.createStyle(); style.featureTypeStyles().add(fts); return style; } private static Style createLineStyle() { LineSymbolizer symbolizer = styleFactory.createLineSymbolizer(); SLD.setLineColour(symbolizer, Color.BLUE); symbolizer.getStroke().setWidth(filterFactory.literal(1)); symbolizer.getStroke().setColor(filterFactory.literal(Color.BLUE)); Rule rule = styleFactory.createRule(); rule.symbolizers().add(symbolizer); FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(); fts.rules().add(rule); Style style = styleFactory.createStyle(); style.featureTypeStyles().add(fts); return style; } private static Style createPolygonStyle() { PolygonSymbolizer symbolizer = styleFactory.createPolygonSymbolizer(); Fill fill = styleFactory.createFill( filterFactory.literal("#FFAA00"), filterFactory.literal(0.5) ); final Stroke stroke = styleFactory.createStroke(filterFactory.literal(Color.BLACK), filterFactory.literal(1)); symbolizer.setFill(fill); symbolizer.setStroke(stroke); Rule rule = styleFactory.createRule(); rule.symbolizers().add(symbolizer); FeatureTypeStyle fts = styleFactory.createFeatureTypeStyle(); fts.rules().add(rule); Style style = styleFactory.createStyle(); style.featureTypeStyles().add(fts); return style; } }
8,953
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ShapefileAssistantPage2.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/ShapefileAssistantPage2.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.crs.CrsSelectionPanel; import org.esa.snap.ui.crs.CustomCrsForm; import org.esa.snap.ui.crs.PredefinedCrsForm; import org.esa.snap.ui.crs.ProductCrsForm; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.Component; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.*; class ShapefileAssistantPage2 extends AbstractLayerSourceAssistantPage { private CrsSelectionPanel crsSelectionPanel; ShapefileAssistantPage2() { super("Define CRS"); } @Override public Component createPageComponent() { final AppContext snapContext = SnapApp.getDefault().getAppContext(); final ProductCrsForm productCrsForm = new ProductCrsForm(snapContext, SnapApp.getDefault().getSelectedProduct(VIEW)); final CustomCrsForm customCrsForm = new CustomCrsForm(snapContext); final PredefinedCrsForm predefinedCrsForm = new PredefinedCrsForm(snapContext); final TableLayout tableLayout = new TableLayout(1); tableLayout.setTablePadding(4, 4); tableLayout.setTableWeightX(1.0); tableLayout.setTableWeightY(1.0); tableLayout.setTableFill(TableLayout.Fill.BOTH); final JPanel pageComponent = new JPanel(tableLayout); final JLabel label = new JLabel("<html><b>No CRS found for ESRI Shapefile. Please specify.</b>"); crsSelectionPanel = new CrsSelectionPanel(productCrsForm, customCrsForm, predefinedCrsForm); pageComponent.add(label); pageComponent.add(crsSelectionPanel); return pageComponent; } @Override public boolean validatePage() { try { crsSelectionPanel.getCrs(ProductUtils.getCenterGeoPos(SnapApp.getDefault().getSelectedProduct(VIEW))); } catch (FactoryException ignored) { return false; } return true; } @Override public boolean hasNextPage() { return true; } @Override public AbstractLayerSourceAssistantPage getNextPage() { final LayerSourcePageContext context = getContext(); try { final Product product = SnapApp.getDefault().getSelectedProduct(VIEW); final GeoPos referencePos = ProductUtils.getCenterGeoPos(product); final CoordinateReferenceSystem crs = crsSelectionPanel.getCrs(referencePos); context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION_CRS, crs); return new ShapefileAssistantPage3(); } catch (FactoryException e) { e.printStackTrace(); context.showErrorDialog("Could not create CRS:\n" + e.getMessage()); } return null; } @Override public boolean canFinish() { return false; } }
4,006
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ShapefileLayerLoader.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/ShapefileLayerLoader.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import com.bc.ceres.glayer.Layer; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.esa.snap.ui.product.ProductSceneView; import java.util.concurrent.ExecutionException; class ShapefileLayerLoader extends ShapefileLoader { ShapefileLayerLoader(LayerSourcePageContext context) { super(context); } @Override protected void done() { try { final Layer layer = get(); ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); final Layer rootLayer = getContext().getLayerContext().getRootLayer(); rootLayer.getChildren().add(sceneView.getFirstImageLayerIndex(), layer); } catch (InterruptedException ignored) { } catch (ExecutionException e) { getContext().showErrorDialog("Could not load shape file: \n" + e.getMessage()); e.printStackTrace(); } } }
1,734
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ShapefileLayerSource.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/ShapefileLayerSource.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import org.esa.snap.core.datamodel.Product; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSource; import org.esa.snap.ui.layer.LayerSourcePageContext; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.*; /** * A layer source for ESRI shape files. * <p> * Unstable API. Use at own risk. * * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.6 */ public class ShapefileLayerSource implements LayerSource { static final String PROPERTY_NAME_FILE_PATH = "fileName"; static final String PROPERTY_NAME_FEATURE_COLLECTION = "featureCollection"; static final String PROPERTY_NAME_FEATURE_COLLECTION_CRS = "featureCollectionCrs"; static final String PROPERTY_NAME_STYLES = "styles"; static final String PROPERTY_NAME_SELECTED_STYLE = "selectedStyle"; @Override public boolean isApplicable(LayerSourcePageContext pageContext) { final Product selectedProduct = SnapApp.getDefault().getSelectedProduct(VIEW); return selectedProduct != null && selectedProduct.getSceneGeoCoding() != null; } @Override public boolean hasFirstPage() { return true; } @Override public AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext) { return new ShapefileAssistantPage1(); } @Override public boolean canFinish(LayerSourcePageContext pageContext) { return false; } @Override public boolean performFinish(LayerSourcePageContext pageContext) { return false; } @Override public void cancel(LayerSourcePageContext pageContext) { } }
2,476
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ShapefileAssistantPage3.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/ShapefileAssistantPage3.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.swing.LayerCanvas; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.esa.snap.ui.product.ProductSceneView; import org.geotools.styling.Style; import org.opengis.util.InternationalString; 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 javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.geom.Rectangle2D; import java.io.File; import java.text.MessageFormat; import java.util.concurrent.ExecutionException; class ShapefileAssistantPage3 extends AbstractLayerSourceAssistantPage { private JComboBox styleList; private JPanel mapPanel; private SwingWorker<Layer, Object> worker; private boolean shapeFileLoaded; private JLabel infoLabel; private JLabel mapLabel; private ShapefileAssistantPage3.ResizeAdapter resizeAdapter; ShapefileAssistantPage3() { super("Layer Preview"); shapeFileLoaded = false; } @Override public boolean validatePage() { return shapeFileLoaded; } @Override public Component createPageComponent() { mapPanel = new JPanel(new BorderLayout()); mapLabel = new JLabel(); mapLabel.setHorizontalAlignment(JLabel.CENTER); mapPanel.add(mapLabel, BorderLayout.CENTER); LayerSourcePageContext context = getContext(); String filePath = (String) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FILE_PATH); String fileName = new File(filePath).getName(); infoLabel = new JLabel(); styleList = new JComboBox(); styleList.setRenderer(new StyleListCellRenderer()); styleList.addItemListener(new StyleSelectionListener()); styleList.setPreferredSize(new Dimension(100, styleList.getPreferredSize().height)); JPanel panel2 = new JPanel(new BorderLayout(4, 4)); panel2.setBorder(new EmptyBorder(4, 4, 4, 4)); panel2.add(new JLabel("Style:"), BorderLayout.WEST); panel2.add(styleList, BorderLayout.EAST); JPanel panel3 = new JPanel(new BorderLayout(4, 4)); panel3.setBorder(new EmptyBorder(4, 4, 4, 4)); panel3.add(new JLabel(String.format("<html><b>%s</b>", fileName)), BorderLayout.CENTER); panel3.add(panel2, BorderLayout.EAST); JPanel panel = new JPanel(new BorderLayout(4, 4)); panel.setBorder(new EmptyBorder(4, 4, 4, 4)); panel.add(panel3, BorderLayout.NORTH); panel.add(mapPanel, BorderLayout.CENTER); panel.add(infoLabel, BorderLayout.SOUTH); SwingUtilities.invokeLater(new Runnable() { @Override public void run() { updateMap(); } }); return panel; } @Override public boolean performFinish() { LayerSourcePageContext context = getContext(); new ShapefileLayerLoader(context).execute(); return true; } private void updateMap() { if (worker != null && !worker.isDone()) { try { worker.cancel(true); } catch (Throwable ignore) { // ok } } mapLabel.setText("<html><i>Loading map...</i></html>"); addToMapPanel(mapLabel); final LayerSourcePageContext context = getContext(); context.getWindow().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); shapeFileLoaded = false; context.updateState(); worker = new ShapeFilePreviewLoader(context); worker.execute(); } private void addToMapPanel(Component component) { if (resizeAdapter == null && component instanceof LayerCanvas) { final LayerCanvas layerCanvas = (LayerCanvas) component; resizeAdapter = new ResizeAdapter(layerCanvas); mapPanel.addComponentListener(resizeAdapter); } else { mapPanel.removeComponentListener(resizeAdapter); resizeAdapter = null; } mapPanel.removeAll(); mapPanel.add(component, BorderLayout.CENTER); } private class StyleSelectionListener implements ItemListener { @Override public void itemStateChanged(ItemEvent e) { LayerSourcePageContext context = getContext(); context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_SELECTED_STYLE, styleList.getSelectedItem()); context.updateState(); updateMap(); } } private static class StyleListCellRenderer extends DefaultListCellRenderer { @Override public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); String text = null; if (value != null) { Style style = (Style) value; InternationalString title = style.getDescription().getTitle(); if (title != null) { text = title.toString(); }else { text = "Default Styler"; } } label.setText(text); return label; } } private class ShapeFilePreviewLoader extends ShapefileLoader { private ShapeFilePreviewLoader(LayerSourcePageContext context) { super(context); } @Override protected void done() { final LayerSourcePageContext context = getContext(); context.getWindow().setCursor(Cursor.getDefaultCursor()); final ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); try { final Layer layer = get(); final LayerCanvas layerCanvas = new LayerCanvas(layer); layerCanvas.getViewport().setModelYAxisDown(sceneView.getLayerCanvas().getViewport().isModelYAxisDown()); addToMapPanel(layerCanvas); final Rectangle2D bounds = layer.getModelBounds(); infoLabel.setText(String.format("Model bounds [%.3f : %.3f, %.3f : %.3f]", bounds.getMinX(), bounds.getMinY(), bounds.getMaxX(), bounds.getMaxY())); Style[] styles = (Style[]) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_STYLES); Style selectedStyle = (Style) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_SELECTED_STYLE); styleList.setModel(new DefaultComboBoxModel(styles)); styleList.setSelectedItem(selectedStyle); shapeFileLoaded = true; } catch (ExecutionException e) { final String errorMessage = MessageFormat.format("<html><b>Error:</b> <i>{0}</i></html>", e.getMessage()); e.printStackTrace(); mapLabel.setText(errorMessage); addToMapPanel(mapLabel); } catch (InterruptedException ignore) { // ok } finally { context.updateState(); } } } private static class ResizeAdapter extends ComponentAdapter { private final LayerCanvas layerCanvas; private ResizeAdapter(LayerCanvas layerCanvas) { this.layerCanvas = layerCanvas; } @Override public void componentResized(ComponentEvent e) { layerCanvas.zoomAll(); } } }
9,031
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ShapefileAssistantPage1.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/shapefile/ShapefileAssistantPage1.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.shapefile; import org.esa.snap.core.util.FeatureUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.layermanager.layersrc.FilePathListCellRenderer; import org.esa.snap.rcp.layermanager.layersrc.HistoryComboBoxModel; import org.esa.snap.ui.FileHistory; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.geotools.data.FeatureSource; import org.geotools.feature.FeatureCollection; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.referencing.crs.CoordinateReferenceSystem; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.net.URL; import java.util.prefs.Preferences; class ShapefileAssistantPage1 extends AbstractLayerSourceAssistantPage { private static final String PROPERTY_LAST_FILE_PREFIX = "ShapefileAssistant.Shapefile.history"; private static final String PROPERTY_LAST_DIR = "ShapefileAssistant.Shapefile.lastDir"; private HistoryComboBoxModel fileHistoryModel; ShapefileAssistantPage1() { super("Select ESRI Shapefile"); } @Override public Component createPageComponent() { GridBagConstraints gbc = new GridBagConstraints(); final JPanel panel = new JPanel(new GridBagLayout()); gbc.anchor = GridBagConstraints.WEST; gbc.gridy = 0; gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 2; panel.add(new JLabel("Path to ESRI Shapefile (*.shp):"), gbc); gbc.weightx = 1; gbc.weighty = 0; gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 1; final LayerSourcePageContext context = getContext(); final Preferences preferences = SnapApp.getDefault().getPreferences(); final FileHistory fileHistory = new FileHistory(5, PROPERTY_LAST_FILE_PREFIX); fileHistory.initBy(preferences); fileHistoryModel = new HistoryComboBoxModel(fileHistory); JComboBox shapefileBox = new JComboBox(fileHistoryModel); shapefileBox.setRenderer(new FilePathListCellRenderer(80)); shapefileBox.setEditable(true); shapefileBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { context.updateState(); } }); panel.add(shapefileBox, gbc); gbc.weightx = 0; gbc.weighty = 0; gbc.gridx = 1; gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = 1; JButton button = new JButton("..."); button.addActionListener(new ShpaeFilechooserActionListener()); panel.add(button, gbc); return panel; } @Override public boolean validatePage() { if (fileHistoryModel != null) { String path = (String) fileHistoryModel.getSelectedItem(); return path != null && !path.trim().isEmpty(); } return false; } @Override public boolean hasNextPage() { return true; } @Override public AbstractLayerSourceAssistantPage getNextPage() { final LayerSourcePageContext context = getContext(); fileHistoryModel.getHistory().copyInto(SnapApp.getDefault().getPreferences()); String path = (String) fileHistoryModel.getSelectedItem(); if (path != null && !path.trim().isEmpty()) { try { final String oldPath = (String) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FILE_PATH); if (!path.equals(oldPath)) { context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FILE_PATH, path); final URL fileUrl = new File(path).toURI().toURL(); final FeatureSource<SimpleFeatureType, SimpleFeature> featureSource = FeatureUtils.getFeatureSource(fileUrl); context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION, featureSource.getFeatures()); // clear other properties they are not valid anymore context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_SELECTED_STYLE, null); context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_STYLES, null); context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION_CRS, null); } FeatureCollection fc = (FeatureCollection) context.getPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION); final CoordinateReferenceSystem featureCrs = fc.getSchema().getCoordinateReferenceSystem(); if (featureCrs == null) { return new ShapefileAssistantPage2(); } else { context.setPropertyValue(ShapefileLayerSource.PROPERTY_NAME_FEATURE_COLLECTION_CRS, featureCrs); return new ShapefileAssistantPage3(); } } catch (Exception e) { e.printStackTrace(); context.showErrorDialog("Failed to load ESRI shapefile:\n" + e.getMessage()); } } return null; } @Override public boolean canFinish() { return false; } private class ShpaeFilechooserActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.setAcceptAllFileFilterUsed(false); final FileNameExtensionFilter shapefileFilter = new FileNameExtensionFilter("ESRI Shapefile", "shp"); fileChooser.addChoosableFileFilter(shapefileFilter); fileChooser.setFileFilter(shapefileFilter); File lastDir = getLastDirectory(); fileChooser.setCurrentDirectory(lastDir); LayerSourcePageContext pageContext = getContext(); fileChooser.showOpenDialog(pageContext.getWindow()); if (fileChooser.getSelectedFile() != null) { String filePath = fileChooser.getSelectedFile().getPath(); fileHistoryModel.setSelectedItem(filePath); Preferences preferences = SnapApp.getDefault().getPreferences(); preferences.put(PROPERTY_LAST_DIR, fileChooser.getCurrentDirectory().getAbsolutePath()); pageContext.updateState(); } } private File getLastDirectory() { Preferences preferences = SnapApp.getDefault().getPreferences(); String dirPath = preferences.get(PROPERTY_LAST_DIR, System.getProperty("user.home")); File lastDir = new File(dirPath); if (!lastDir.isDirectory()) { lastDir = new File(System.getProperty("user.home")); } return lastDir; } } }
8,105
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductLayerSource.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/product/ProductLayerSource.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.product; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSource; import org.esa.snap.ui.layer.LayerSourcePageContext; /** * A layer source that adds band or tie-point-grids * from compatible products as new bands. * * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.6 */ public class ProductLayerSource implements LayerSource { @Override public boolean isApplicable(LayerSourcePageContext pageContext) { return true; } @Override public boolean hasFirstPage() { return true; } @Override public AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext) { return new ProductLayerAssistantPage(); } @Override public boolean canFinish(LayerSourcePageContext pageContext) { return false; } @Override public boolean performFinish(LayerSourcePageContext pageContext) { return pageContext.getCurrentPage().performFinish(); } @Override public void cancel(LayerSourcePageContext pageContext) { } }
1,878
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LayerDataHandler.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/product/LayerDataHandler.java
/* /* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.product; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.support.AbstractLayerListener; import com.bc.ceres.glayer.support.ImageLayer; 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.VirtualBand; import org.esa.snap.core.image.ColoredBandImageMultiLevelSource; import java.util.Arrays; import java.util.List; class LayerDataHandler extends AbstractLayerListener implements ProductNodeListener { private final List<String> imageChangingProperties = Arrays.asList(RasterDataNode.PROPERTY_NAME_DATA, RasterDataNode.PROPERTY_NAME_NO_DATA_VALUE, RasterDataNode.PROPERTY_NAME_NO_DATA_VALUE_USED, RasterDataNode.PROPERTY_NAME_VALID_PIXEL_EXPRESSION, RasterDataNode.PROPERTY_NAME_IMAGE_INFO, VirtualBand.PROPERTY_NAME_EXPRESSION); private final RasterDataNode rasterDataNode; private final ImageLayer imageLayer; LayerDataHandler(RasterDataNode rasterDataNode, ImageLayer imageLayer) { this.rasterDataNode = rasterDataNode; this.imageLayer = imageLayer; } @Override public void handleLayersRemoved(Layer parentLayer, Layer[] childLayers) { for (Layer childLayer : childLayers) { if (childLayer == imageLayer) { final Product product = rasterDataNode.getProduct(); if (product != null) { product.removeProductNodeListener(this); } } } } @Override public void nodeChanged(ProductNodeEvent event) { if (event.getSourceNode() == rasterDataNode) { if (RasterDataNode.PROPERTY_NAME_NAME.equals(event.getPropertyName())) { imageLayer.setName(rasterDataNode.getDisplayName()); } else if (imageChangingProperties.contains(event.getPropertyName())) { ColoredBandImageMultiLevelSource bandImageSource = (ColoredBandImageMultiLevelSource) imageLayer.getMultiLevelSource(); bandImageSource.setImageInfo(rasterDataNode.getImageInfo()); imageLayer.regenerate(); } } } @Override public void nodeDataChanged(ProductNodeEvent event) { if (event.getSourceNode() == rasterDataNode) { imageLayer.regenerate(); } } @Override public void nodeAdded(ProductNodeEvent event) { } @Override public void nodeRemoved(ProductNodeEvent event) { } }
3,699
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductLayerAssistantPage.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/product/ProductLayerAssistantPage.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.product; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.glayer.support.ImageLayer; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.core.layer.RasterImageLayerType; import org.esa.snap.core.util.ObjectUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.product.ProductSceneView; import org.geotools.referencing.CRS; import org.opengis.referencing.ReferenceIdentifier; import org.opengis.referencing.crs.CoordinateReferenceSystem; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTree; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Dimension; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import java.util.WeakHashMap; class ProductLayerAssistantPage extends AbstractLayerSourceAssistantPage { private JTree tree; ProductLayerAssistantPage() { super("Select Band / Tie-Point Grid"); } @Override public Component createPageComponent() { ProductTreeModel model = createTreeModel(); tree = new JTree(model); tree.setEditable(false); tree.setShowsRootHandles(true); tree.setRootVisible(false); tree.setCellRenderer(new ProductNodeTreeCellRenderer()); tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); tree.getSelectionModel().addTreeSelectionListener(new ProductNodeSelectionListener()); List<CompatibleNodeList> nodeLists = model.compatibleNodeLists; for (CompatibleNodeList nodeList : nodeLists) { tree.expandPath(new TreePath(new Object[]{nodeLists, nodeList})); } JPanel panel = new JPanel(new BorderLayout(4, 4)); panel.setBorder(new EmptyBorder(4, 4, 4, 4)); panel.add(new JLabel("Compatible bands and tie-point grids:"), BorderLayout.NORTH); panel.add(new JScrollPane(tree), BorderLayout.CENTER); return panel; } @Override public boolean validatePage() { TreePath path = tree.getSelectionPath(); return path != null && path.getLastPathComponent() instanceof RasterDataNode; } @Override public boolean hasNextPage() { return false; } @Override public boolean canFinish() { return true; } @Override public boolean performFinish() { //allow multiple selections final TreePath[] selectionPaths = tree.getSelectionPaths(); if (selectionPaths == null) { return false; } for (TreePath treePath : selectionPaths) { final RasterDataNode rasterDataNode = (RasterDataNode) treePath.getLastPathComponent(); LayerType type = LayerTypeRegistry.getLayerType(RasterImageLayerType.class.getName()); PropertySet configuration = type.createLayerConfig(getContext().getLayerContext()); configuration.setValue(RasterImageLayerType.PROPERTY_NAME_RASTER, rasterDataNode); configuration.setValue(ImageLayer.PROPERTY_NAME_BORDER_SHOWN, false); configuration.setValue(ImageLayer.PROPERTY_NAME_BORDER_COLOR, ImageLayer.DEFAULT_BORDER_COLOR); configuration.setValue(ImageLayer.PROPERTY_NAME_BORDER_WIDTH, ImageLayer.DEFAULT_BORDER_WIDTH); configuration.setValue(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_SHOWN, false); final ImageLayer imageLayer = (ImageLayer) type.createLayer(getContext().getLayerContext(), configuration); imageLayer.setName(rasterDataNode.getDisplayName()); ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); Layer rootLayer = sceneView.getRootLayer(); rootLayer.getChildren().add(sceneView.getFirstImageLayerIndex(), imageLayer); final LayerDataHandler layerDataHandler = new LayerDataHandler(rasterDataNode, imageLayer); rasterDataNode.getProduct().addProductNodeListener(layerDataHandler); rootLayer.addListener(layerDataHandler); } return true; } private static class CompatibleNodeList { private final String name; private final List<RasterDataNode> rasterDataNodes; CompatibleNodeList(String name, List<RasterDataNode> rasterDataNodes) { this.name = name; this.rasterDataNodes = rasterDataNodes; } } private ProductTreeModel createTreeModel() { final ProductSceneView selectedProductSceneView = SnapApp.getDefault().getSelectedProductSceneView(); Product selectedProduct = selectedProductSceneView.getProduct(); RasterDataNode raster = selectedProductSceneView.getRaster(); CoordinateReferenceSystem modelCRS = selectedProduct.getSceneCRS(); ArrayList<CompatibleNodeList> compatibleNodeLists = new ArrayList<>(3); List<RasterDataNode> compatibleNodes = new ArrayList<>(); collectCompatibleBands(raster, selectedProduct.getBands(), compatibleNodes); if (raster.getRasterWidth() == selectedProduct.getSceneRasterWidth() && raster.getRasterHeight() == selectedProduct.getSceneRasterHeight()) { compatibleNodes.addAll(Arrays.asList(selectedProduct.getTiePointGrids())); } if (!compatibleNodes.isEmpty()) { compatibleNodeLists.add(new CompatibleNodeList(selectedProduct.getDisplayName(), compatibleNodes)); } if (modelCRS != null) { final ProductManager productManager = SnapApp.getDefault().getProductManager(); final Product[] products = productManager.getProducts(); for (Product product : products) { if (product == selectedProduct) { continue; } compatibleNodes = new ArrayList<>(); collectCompatibleRasterDataNodes(modelCRS, product.getBands(), compatibleNodes); collectCompatibleRasterDataNodes(modelCRS, product.getTiePointGrids(), compatibleNodes); if (!compatibleNodes.isEmpty()) { compatibleNodeLists.add(new CompatibleNodeList(product.getDisplayName(), compatibleNodes)); } } } return new ProductTreeModel(compatibleNodeLists); } private void collectCompatibleBands(RasterDataNode referenceRaster, RasterDataNode[] dataNodes, Collection<RasterDataNode> rasterDataNodes) { final Dimension referenceRasterSize = referenceRaster.getRasterSize(); for (RasterDataNode node : dataNodes) { if (node.getRasterSize().equals(referenceRasterSize)) { rasterDataNodes.add(node); } } } private void collectCompatibleRasterDataNodes(CoordinateReferenceSystem thisCrs, RasterDataNode[] bands, Collection<RasterDataNode> rasterDataNodes) { for (RasterDataNode node : bands) { CoordinateReferenceSystem otherCrs = Product.findModelCRS(node.getGeoCoding()); // For GeoTools, two CRS where unequal if the authorities of their CS only differ in version // This happened with the S-2 L1C CRS, namely an EPSG:32615. Here one authority's version was null, // the other "7.9". Extremely annoying to debug and find out :-( (nf, Feb 2013) if (CRS.equalsIgnoreMetadata(thisCrs, otherCrs) || haveCommonReferenceIdentifiers(thisCrs, otherCrs)) { rasterDataNodes.add(node); } } } private static boolean haveCommonReferenceIdentifiers(CoordinateReferenceSystem crs1, CoordinateReferenceSystem crs2) { Set<ReferenceIdentifier> identifiers1 = crs1.getIdentifiers(); Set<ReferenceIdentifier> identifiers2 = crs2.getIdentifiers(); // If a CRS does not have identifiers or if they have different number of identifiers // they cannot be equal. if (identifiers1 == null || identifiers1.isEmpty() || identifiers2 == null || identifiers2.isEmpty() || identifiers1.size() != identifiers2.size()) { return false; } // The two CRSs can only be equal if they have the same number of identifiers // and all of them are common to both. int eqCount = 0; for (ReferenceIdentifier refId1 : identifiers1) { for (ReferenceIdentifier refId2 : identifiers2) { if (compareRefIds(refId1, refId2)) { eqCount++; break; } } } return eqCount == identifiers1.size(); } private static boolean compareRefIds(ReferenceIdentifier refId1, ReferenceIdentifier refId2) { return ObjectUtils.equalObjects(refId1.getCodeSpace(), refId2.getCodeSpace()) && ObjectUtils.equalObjects(refId1.getCode(), refId2.getCode()) && compareVersions(refId1.getVersion(), refId2.getVersion()); } // Other than GeoTools, we compare versions only if given. // We interpret the case version==null, as not provided, hence all versions match (nf, Feb 2013) private static boolean compareVersions(String version1, String version2) { return version1 == null || version2 == null || version1.equalsIgnoreCase(version2); } private static class ProductNodeTreeCellRenderer extends DefaultTreeCellRenderer { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { JLabel label = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (value instanceof CompatibleNodeList) { label.setText(MessageFormat.format("<html><b>{0}</b></html>", ((CompatibleNodeList) value).name)); } else if (value instanceof Band) { label.setText(MessageFormat.format("<html><b>{0}</b></html>", ((Band) value).getName())); } else if (value instanceof TiePointGrid) { label.setText(MessageFormat.format("<html><b>{0}</b> (Tie-point grid)</html>", ((TiePointGrid) value).getName())); } return label; } } private class ProductNodeSelectionListener implements TreeSelectionListener { @Override public void valueChanged(TreeSelectionEvent e) { getContext().updateState(); } } private static class ProductTreeModel implements TreeModel { private final WeakHashMap<TreeModelListener, Object> treeModelListeners; private final List<CompatibleNodeList> compatibleNodeLists; private ProductTreeModel(List<CompatibleNodeList> compatibleNodeLists) { this.compatibleNodeLists = compatibleNodeLists; this.treeModelListeners = new WeakHashMap<>(); } @Override public Object getRoot() { return compatibleNodeLists; } @Override public Object getChild(Object parent, int index) { if (parent == compatibleNodeLists) { return compatibleNodeLists.get(index); } else if (parent instanceof CompatibleNodeList) { return ((CompatibleNodeList) parent).rasterDataNodes.get(index); } return null; } @Override public int getChildCount(Object parent) { if (parent == compatibleNodeLists) { return compatibleNodeLists.size(); } else if (parent instanceof CompatibleNodeList) { return ((CompatibleNodeList) parent).rasterDataNodes.size(); } return 0; } @Override public boolean isLeaf(Object node) { return node instanceof RasterDataNode; } @Override public int getIndexOfChild(Object parent, Object child) { if (parent == compatibleNodeLists) { return compatibleNodeLists.indexOf(child); } else if (parent instanceof CompatibleNodeList) { return ((CompatibleNodeList) parent).rasterDataNodes.indexOf(child); } return -1; } @Override public void valueForPathChanged(TreePath path, Object newValue) { fireTreeNodeChanged(path); } @Override public void addTreeModelListener(TreeModelListener l) { treeModelListeners.put(l, ""); } @Override public void removeTreeModelListener(TreeModelListener l) { treeModelListeners.remove(l); } protected void fireTreeNodeChanged(TreePath treePath) { TreeModelEvent event = new TreeModelEvent(this, treePath); for (TreeModelListener treeModelListener : treeModelListeners.keySet()) { treeModelListener.treeNodesChanged(event); } } } }
14,808
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WindFieldLayerSource.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/windfield/WindFieldLayerSource.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.windfield; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSource; import org.esa.snap.ui.layer.LayerSourcePageContext; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.*; /** * A source for {@link WindFieldLayer}s. * * @author Norman Fomferra * @since BEAM 4.6 */ public class WindFieldLayerSource implements LayerSource { private static final String WINDU_NAME = "zonal_wind"; private static final String WINDV_NAME = "merid_wind"; @Override public boolean isApplicable(LayerSourcePageContext pageContext) { final Product product = SnapApp.getDefault().getSelectedProduct(VIEW); final RasterDataNode windu = product.getRasterDataNode(WINDU_NAME); final RasterDataNode windv = product.getRasterDataNode(WINDV_NAME); return windu != null && windv != null; } @Override public boolean hasFirstPage() { return false; } @Override public AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext) { return null; } @Override public boolean canFinish(LayerSourcePageContext pageContext) { return true; } @Override public boolean performFinish(LayerSourcePageContext pageContext) { final Product product = SnapApp.getDefault().getSelectedProduct(VIEW); final RasterDataNode windu = product.getRasterDataNode(WINDU_NAME); final RasterDataNode windv = product.getRasterDataNode(WINDV_NAME); final WindFieldLayer fieldLayer = WindFieldLayerType.createLayer(windu, windv); pageContext.getLayerContext().getRootLayer().getChildren().add(0, fieldLayer); return true; } @Override public void cancel(LayerSourcePageContext pageContext) { } }
2,703
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WindFieldLayerType.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/windfield/WindFieldLayerType.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.windfield; 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.accessors.DefaultPropertyAccessor; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerContext; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.glayer.annotations.LayerTypeMetadata; import org.esa.snap.core.datamodel.RasterDataNode; /** * The type descriptor of the {@link WindFieldLayer}. * * @author Norman Fomferra * @since BEAM 4.6 */ @LayerTypeMetadata(name = "WindFieldLayerType", aliasNames = {"WindFieldLayerType"}) public class WindFieldLayerType extends LayerType { public static WindFieldLayer createLayer(RasterDataNode windu, RasterDataNode windv) { LayerType type = LayerTypeRegistry.getLayerType(WindFieldLayerType.class); final PropertySet template = type.createLayerConfig(null); template.setValue("windu", windu); template.setValue("windv", windv); return new WindFieldLayer(type, windu, windv, template); } @Override public boolean isValidFor(LayerContext ctx) { // todo - need to check for availability of windu, windv (nf) return true; } @Override public Layer createLayer(LayerContext ctx, PropertySet configuration) { final RasterDataNode windu = (RasterDataNode) configuration.getValue("windu"); final RasterDataNode windv = (RasterDataNode) configuration.getValue("windv"); return new WindFieldLayer(this, windu, windv, configuration); } @Override public PropertySet createLayerConfig(LayerContext ctx) { final PropertyContainer propertyContainer = new PropertyContainer(); // todo - how do I know whether my value model type can be serialized or not? (nf) propertyContainer.addProperty(new Property(new PropertyDescriptor("windu", RasterDataNode.class), new DefaultPropertyAccessor())); propertyContainer.addProperty(new Property(new PropertyDescriptor("windv", RasterDataNode.class), new DefaultPropertyAccessor())); return propertyContainer; } }
3,021
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WindFieldLayer.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/windfield/WindFieldLayer.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.windfield; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.LayerTypeRegistry; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.glevel.MultiLevelImage; import com.bc.ceres.grender.Rendering; import com.bc.ceres.grender.Viewport; import org.esa.snap.core.datamodel.RasterDataNode; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.image.RenderedImage; /** * Experimental wind field layer. Given two band names for u,v, it could * be generalized to any vector field layer. * * @author Norman Fomferra * @since BEAM 4.6 */ public class WindFieldLayer extends Layer { private RasterDataNode windu; private RasterDataNode windv; private final Color[] palette; private double maxLength = 10.0; // m/s private int res = 16; private float lineThickness = 2.0f; public WindFieldLayer(PropertyContainer configuration) { this(LayerTypeRegistry.getLayerType(WindFieldLayerType.class.getName()), (RasterDataNode) configuration.getValue("windu"), (RasterDataNode) configuration.getValue("windv"), configuration); } public WindFieldLayer(LayerType layerType, RasterDataNode windu, RasterDataNode windv, PropertySet configuration) { super(layerType, configuration); setName("Wind Speed"); this.windu = windu; this.windv = windv; palette = new Color[256]; for (int i = 0; i < palette.length; i++) { palette[i] = new Color(i, i, i); } } @Override protected void renderLayer(Rendering rendering) { final MultiLevelImage winduMLI = windu.getGeophysicalImage(); final MultiLevelImage windvMLI = windv.getGeophysicalImage(); final Viewport vp = rendering.getViewport(); final int level = ImageLayer.getLevel(winduMLI.getModel(), vp); final AffineTransform m2i = winduMLI.getModel().getModelToImageTransform(level); final AffineTransform i2m = winduMLI.getModel().getImageToModelTransform(level); final Shape vbounds = vp.getViewBounds(); final Shape mbounds = vp.getViewToModelTransform().createTransformedShape(vbounds); final Shape ibounds = m2i.createTransformedShape(mbounds); final RenderedImage winduRI = winduMLI.getImage(level); final RenderedImage windvRI = windvMLI.getImage(level); final int width = winduRI.getWidth(); final int height = winduRI.getHeight(); final Rectangle irect = ibounds.getBounds().intersection(new Rectangle(0, 0, width, height)); if (irect.isEmpty()) { return; } final AffineTransform m2v = vp.getModelToViewTransform(); final Graphics2D graphics = rendering.getGraphics(); graphics.setStroke(new BasicStroke(lineThickness)); final MultiLevelImage winduValidMLI = windu.getValidMaskImage(); final MultiLevelImage windvValidMLI = windv.getValidMaskImage(); final RenderedImage winduValidRI = winduValidMLI != null ? winduValidMLI.getImage(level) : null; final RenderedImage windvValidRI = windvValidMLI != null ? windvValidMLI.getImage(level) : null; final int x1 = res * (irect.x / res); final int x2 = x1 + res * (1 + irect.width / res); final int y1 = res * (irect.y / res); final int y2 = y1 + res * (1 + irect.height / res); final double[] ipts = new double[8]; final double[] mpts = new double[8]; final double[] vpts = new double[8]; final Rectangle pixelRect = new Rectangle(0, 0, 1, 1); for (int y = y1; y <= y2; y += res) { for (int x = x1; x <= x2; x += res) { if (x >= 0 && x < width && y >= 0 && y < height) { pixelRect.x = x; pixelRect.y = y; final boolean winduValid = winduValidRI == null || winduValidRI.getData(pixelRect).getSample(x, y, 0) != 0; if (!winduValid) { continue; } final boolean windvValid = windvValidRI == null || windvValidRI.getData(pixelRect).getSample(x, y, 0) != 0; if (!windvValid) { continue; } final double u = winduRI.getData(pixelRect).getSampleDouble(x, y, 0); final double v = windvRI.getData(pixelRect).getSampleDouble(x, y, 0); final double length = Math.sqrt(u * u + v * v); final double ndx = length > 0 ? +u / length : 0; final double ndy = length > 0 ? -v / length : 0; final double ondx = -ndy; final double ondy = ndx; final double s0 = (length / maxLength) * res; final double s1 = s0 - 0.2 * res; final double s2 = 0.1 * res; ipts[0] = x; ipts[1] = y; ipts[2] = x + s0 * ndx; ipts[3] = y + s0 * ndy; ipts[4] = x + s1 * ndx + s2 * ondx; ipts[5] = y + s1 * ndy + s2 * ondy; ipts[6] = x + s1 * ndx - s2 * ondx; ipts[7] = y + s1 * ndy - s2 * ondy; i2m.transform(ipts, 0, mpts, 0, 4); m2v.transform(mpts, 0, vpts, 0, 4); final int grey = Math.min(255, (int) Math.round(256 * length / maxLength)); graphics.setColor(palette[grey]); graphics.draw(new Line2D.Double(vpts[0], vpts[1], vpts[2], vpts[3])); graphics.draw(new Line2D.Double(vpts[4], vpts[5], vpts[2], vpts[3])); graphics.draw(new Line2D.Double(vpts[6], vpts[7], vpts[2], vpts[3])); } } } } }
6,960
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageFileLayerSource.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/image/ImageFileLayerSource.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.image; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerTypeRegistry; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSource; import org.esa.snap.ui.layer.LayerSourcePageContext; import org.esa.snap.ui.product.ProductSceneView; import java.awt.geom.AffineTransform; import java.io.File; /** * A layer source for images. * <p> * The image can either be associated with an "world-file" or * the orientation relative to the existing layers has to be given by hand. * * @author Marco Zuehlke * @version $Revision$ $Date$ * @since BEAM 4.6 */ public class ImageFileLayerSource implements LayerSource { static final String PROPERTY_NAME_IMAGE_FILE_PATH = "imageFilePath"; static final String PROPERTY_NAME_WORLD_FILE_PATH = "worldFilePath"; static final String PROPERTY_NAME_WORLD_TRANSFORM = "worldTransform"; @Override public boolean isApplicable(LayerSourcePageContext pageContext) { return true; } @Override public boolean hasFirstPage() { return true; } @Override public AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext) { return new ImageFileAssistantPage1(); } @Override public boolean canFinish(LayerSourcePageContext pageContext) { return false; } @Override public boolean performFinish(LayerSourcePageContext pageContext) { return false; } @Override public void cancel(LayerSourcePageContext pageContext) { pageContext.setPropertyValue(PROPERTY_NAME_IMAGE_FILE_PATH, null); } static boolean insertImageLayer(LayerSourcePageContext pageContext) { AffineTransform transform = (AffineTransform) pageContext.getPropertyValue(PROPERTY_NAME_WORLD_TRANSFORM); String imageFilePath = (String) pageContext.getPropertyValue(PROPERTY_NAME_IMAGE_FILE_PATH); try { ProductSceneView sceneView = SnapApp.getDefault().getSelectedProductSceneView(); final ImageFileLayerType type = LayerTypeRegistry.getLayerType(ImageFileLayerType.class); final PropertySet configuration = type.createLayerConfig(sceneView); configuration.setValue(ImageFileLayerType.PROPERTY_NAME_IMAGE_FILE, new File(imageFilePath)); configuration.setValue(ImageFileLayerType.PROPERTY_NAME_WORLD_TRANSFORM, transform); Layer layer = type.createLayer(sceneView, configuration); layer.setName(FileUtils.getFilenameFromPath(imageFilePath)); Layer rootLayer = sceneView.getRootLayer(); rootLayer.getChildren().add(sceneView.getFirstImageLayerIndex(), layer); return true; } catch (Exception e) { pageContext.showErrorDialog(e.getMessage()); return false; } } }
3,742
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageFileAssistantPage2.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/image/ImageFileAssistantPage2.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.image; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.JTextComponent; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.geom.AffineTransform; class ImageFileAssistantPage2 extends AbstractLayerSourceAssistantPage { private JTextField[] numberFields; ImageFileAssistantPage2() { super("Edit Affine Transformation"); } @Override public Component createPageComponent() { GridBagConstraints gbc = new GridBagConstraints(); final JPanel panel = new JPanel(new GridBagLayout()); gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridy = 0; gbc.gridx = 0; gbc.weighty = 0.0; gbc.weightx = 1.0; gbc.insets = new Insets(4, 0, 4, 2); double[] flatmatrix = new double[6]; numberFields = new JTextField[flatmatrix.length]; AffineTransform transform = (AffineTransform) getContext().getPropertyValue( ImageFileLayerSource.PROPERTY_NAME_WORLD_TRANSFORM); transform.getMatrix(flatmatrix); // see http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=17489 String[] labels = new String[]{ "X-dimension of a pixel in map units: ", "Rotation parameter for row: ", "Rotation parameter for column: ", "Negative of Y-dimension of a pixel in map units: ", "X-coordinate of center of upper left pixel: ", "Y-coordinate of centre of upper left pixel: " }; numberFields[0] = addRow(panel, labels[0], gbc); numberFields[0].setText(String.valueOf(flatmatrix[0])); numberFields[1] = addRow(panel, labels[1], gbc); numberFields[1].setText(String.valueOf(flatmatrix[1])); numberFields[2] = addRow(panel, labels[2], gbc); numberFields[2].setText(String.valueOf(flatmatrix[2])); numberFields[3] = addRow(panel, labels[3], gbc); numberFields[3].setText(String.valueOf(flatmatrix[3])); numberFields[4] = addRow(panel, labels[4], gbc); numberFields[4].setText(String.valueOf(flatmatrix[4])); numberFields[5] = addRow(panel, labels[5], gbc); numberFields[5].setText(String.valueOf(flatmatrix[5])); return panel; } @Override public boolean validatePage() { try { return createTransform().getDeterminant() != 0.0; } catch (Exception ignore) { return false; } } @Override public boolean performFinish() { AffineTransform transform = createTransform(); final LayerSourcePageContext context = getContext(); context.setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_TRANSFORM, transform); return ImageFileLayerSource.insertImageLayer(context); } private JTextField addRow(JPanel panel, String label, GridBagConstraints gbc) { gbc.gridy++; gbc.weightx = 0.2; gbc.gridx = 0; panel.add(new JLabel(label), gbc); gbc.weightx = 0.8; gbc.gridx = 1; final JTextField fileField = new JTextField(12); fileField.setHorizontalAlignment(JTextField.RIGHT); panel.add(fileField, gbc); fileField.getDocument().addDocumentListener(new MyDocumentListener()); return fileField; } private AffineTransform createTransform() { double[] flatmatrix = new double[numberFields.length]; for (int i = 0; i < flatmatrix.length; i++) { flatmatrix[i] = Double.parseDouble(getText(numberFields[i])); } return new AffineTransform(flatmatrix); } private String getText(JTextComponent textComponent) { String s = textComponent.getText(); return s != null ? s.trim() : ""; } private class MyDocumentListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { getContext().updateState(); } @Override public void removeUpdate(DocumentEvent e) { getContext().updateState(); } @Override public void changedUpdate(DocumentEvent e) { getContext().updateState(); } } }
5,382
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageFileAssistantPage1.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/image/ImageFileAssistantPage1.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.image; import com.bc.ceres.glayer.tools.Tools; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.layermanager.layersrc.FilePathListCellRenderer; import org.esa.snap.rcp.layermanager.layersrc.HistoryComboBoxModel; import org.esa.snap.ui.FileHistory; import org.esa.snap.ui.layer.AbstractLayerSourceAssistantPage; import org.esa.snap.ui.layer.LayerSourcePageContext; import javax.media.jai.Interpolation; import javax.media.jai.PlanarImage; import javax.media.jai.operator.FileLoadDescriptor; import javax.media.jai.operator.ScaleDescriptor; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.SwingWorker; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.filechooser.FileFilter; import javax.swing.filechooser.FileNameExtensionFilter; import java.awt.Component; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.RenderedImage; import java.io.File; import java.io.IOException; import java.util.concurrent.ExecutionException; import java.util.prefs.Preferences; // todo - Check, if image is GeoTIFF -> no world file is needed class ImageFileAssistantPage1 extends AbstractLayerSourceAssistantPage { private static final String LAST_IMAGE_PREFIX = "ImageFileAssistantPage1.ImageFile.history"; private static final String LAST_DIR = "ImageFileAssistantPage1.ImageFile.lastDir"; private JComboBox imageFileBox; private JTextField worldFileField; private HistoryComboBoxModel imageHistoryModel; private JLabel imagePreviewLabel; ImageFileAssistantPage1() { super("Select Image File"); } @Override public boolean validatePage() { String imageFilePath = (String) getContext().getPropertyValue(ImageFileLayerSource.PROPERTY_NAME_IMAGE_FILE_PATH); String worldFilePath = (String) getContext().getPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_FILE_PATH); if (imageFilePath == null) { return false; } return new File(imageFilePath).exists() && (worldFilePath == null || new File(worldFilePath).exists()); } @Override public boolean hasNextPage() { return getContext().getPropertyValue(ImageFileLayerSource.PROPERTY_NAME_IMAGE_FILE_PATH) != null; } @Override public AbstractLayerSourceAssistantPage getNextPage() { imageHistoryModel.getHistory().copyInto(SnapApp.getDefault().getPreferences()); createTransform(getContext()); return new ImageFileAssistantPage2(); } @Override public boolean canFinish() { return getContext().getPropertyValue(ImageFileLayerSource.PROPERTY_NAME_IMAGE_FILE_PATH) != null; } @Override public boolean performFinish() { imageHistoryModel.getHistory().copyInto(SnapApp.getDefault().getPreferences()); createTransform(getContext()); return ImageFileLayerSource.insertImageLayer(getContext()); } @Override public Component createPageComponent() { GridBagConstraints gbc = new GridBagConstraints(); final JPanel panel = new JPanel(new GridBagLayout()); gbc.anchor = GridBagConstraints.WEST; gbc.gridy = 0; final Preferences preferences = SnapApp.getDefault().getPreferences(); FileHistory fileHistory = new FileHistory(5, LAST_IMAGE_PREFIX); fileHistory.initBy(preferences); imageHistoryModel = new HistoryComboBoxModel(fileHistory); imageFileBox = new JComboBox(imageHistoryModel); imageFileBox.addActionListener(new ImageFileItemListener()); imageFileBox.setRenderer(new FilePathListCellRenderer(80)); final JLabel imageFileLabel = new JLabel("Path to image file (.png, .jpg, .tif, .gif):"); JButton imageFileButton = new JButton("..."); final FileNameExtensionFilter imageFileFilter = new FileNameExtensionFilter("Image Files", "png", "jpg", "tif", "gif"); imageFileButton.addActionListener(new FileChooserActionListener(imageFileFilter) { @Override protected void onFileSelected(LayerSourcePageContext pageContext, String filePath) { pageContext.setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_IMAGE_FILE_PATH, filePath); } }); addRow(panel, gbc, imageFileLabel, imageFileBox, imageFileButton); worldFileField = new JTextField(); worldFileField.getDocument().addDocumentListener(new WorldFilePathDocumentListener()); final JLabel worldFileLabel = new JLabel("Path to world file (.pgw, .jgw, .tfw, .gfw):"); JButton worldFileButton = new JButton("..."); final FileNameExtensionFilter worldFileFilter = new FileNameExtensionFilter("World Files", "pgw", "jgw", "tfw", "gfw"); worldFileButton.addActionListener(new FileChooserActionListener(worldFileFilter) { @Override protected void onFileSelected(LayerSourcePageContext pageContext, String filePath) { pageContext.setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_FILE_PATH, filePath); } }); addRow(panel, gbc, worldFileLabel, worldFileField, worldFileButton); gbc.insets = new Insets(4, 4, 4, 4); gbc.weightx = 1; gbc.weighty = 1; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.BOTH; gbc.gridwidth = 1; imagePreviewLabel = new JLabel(); imagePreviewLabel.setPreferredSize(new Dimension(200, 200)); panel.add(imagePreviewLabel, gbc); getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_IMAGE_FILE_PATH, null); getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_FILE_PATH, null); // getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_IMAGE, null); getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_TRANSFORM, null); return panel; } private void addRow(JPanel panel, GridBagConstraints gbc, JLabel label, JComponent component, JButton button) { gbc.insets = new Insets(4, 4, 4, 4); gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 1; panel.add(label, gbc); gbc.insets = new Insets(0, 4, 0, 4); gbc.weightx = 0; gbc.weighty = 0; gbc.gridx = 0; gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridwidth = 1; panel.add(component, gbc); gbc.weightx = 0; gbc.weighty = 0; gbc.gridx = 1; gbc.fill = GridBagConstraints.NONE; gbc.gridwidth = 1; panel.add(button, gbc); } private static void createTransform(LayerSourcePageContext pageContext) { AffineTransform transform = new AffineTransform(); String worldFilePath = (String) pageContext.getPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_FILE_PATH); if (worldFilePath != null && !worldFilePath.isEmpty()) { try { transform = Tools.loadWorldFile(worldFilePath); } catch (IOException e) { e.printStackTrace(); pageContext.showErrorDialog(e.getMessage()); } } pageContext.setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_TRANSFORM, transform); } private class WorldFilePathDocumentListener implements DocumentListener { @Override public void insertUpdate(DocumentEvent e) { getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_FILE_PATH, worldFileField.getText()); getContext().updateState(); } @Override public void removeUpdate(DocumentEvent e) { getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_FILE_PATH, worldFileField.getText()); getContext().updateState(); } @Override public void changedUpdate(DocumentEvent e) { getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_WORLD_FILE_PATH, worldFileField.getText()); getContext().updateState(); } } private abstract class FileChooserActionListener implements ActionListener { private final FileFilter filter; private FileChooserActionListener(FileFilter fileFilter) { filter = fileFilter; } @Override public void actionPerformed(ActionEvent e) { JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(filter); fileChooser.setCurrentDirectory(getLastDirectory()); LayerSourcePageContext pageContext = getContext(); fileChooser.showOpenDialog(pageContext.getWindow()); if (fileChooser.getSelectedFile() != null) { String filePath = fileChooser.getSelectedFile().getPath(); imageHistoryModel.setSelectedItem(filePath); Preferences preferences = SnapApp.getDefault().getPreferences(); preferences.put(LAST_DIR, fileChooser.getCurrentDirectory().getAbsolutePath()); onFileSelected(pageContext, filePath); pageContext.updateState(); } } protected abstract void onFileSelected(LayerSourcePageContext pageContext, String filePath); private File getLastDirectory() { Preferences preferences = SnapApp.getDefault().getPreferences(); String dirPath = preferences.get(LAST_DIR, System.getProperty("user.home")); File lastDir = new File(dirPath); if (!lastDir.isDirectory()) { lastDir = new File(System.getProperty("user.home")); } return lastDir; } } private class ImageFileItemListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String imageFilePath = (String) imageFileBox.getSelectedItem(); if (imageFilePath == null || !new File(imageFilePath).isFile()) { return; } ImagePreviewWorker worker = new ImagePreviewWorker(imageFilePath, imagePreviewLabel); worker.execute(); getContext().setPropertyValue(ImageFileLayerSource.PROPERTY_NAME_IMAGE_FILE_PATH, imageFilePath); String worldFilePath = createWorldFilePath(imageFilePath); if (new File(worldFilePath).isFile()) { worldFileField.setText(worldFilePath); } else { worldFileField.setText(null); } getContext().updateState(); } private String createWorldFilePath(String imageFilePath) { String imageFileExt = FileUtils.getExtension(imageFilePath); // Rule for world file extension: <name>.<a><b><c> --> <name>.<a><c>w // see http://support.esri.com/index.cfm?fa=knowledgebase.techarticles.articleShow&d=17489 String worldFilePath; if (imageFileExt != null && imageFileExt.length() == 4) { // three chars + leading dot String worldFileExt = imageFileExt.substring(0, 2) + imageFileExt.charAt(imageFileExt.length() - 1) + "w"; worldFilePath = FileUtils.exchangeExtension(imageFilePath, worldFileExt); } else { worldFilePath = imageFilePath + "w"; } return worldFilePath; } private class ImagePreviewWorker extends SwingWorker<Image, Object> { private final Dimension targetDimension; private final String imageFilePath; private final JLabel imageLabel; private ImagePreviewWorker(String imageFilePath, JLabel imageLabel) { this.imageFilePath = imageFilePath; this.imageLabel = imageLabel; this.targetDimension = this.imageLabel.getSize(); } @Override protected Image doInBackground() throws Exception { RenderedImage sourceImage = FileLoadDescriptor.create(imageFilePath, null, true, null); int width = sourceImage.getWidth(); int height = sourceImage.getHeight(); float scale = (float) (targetDimension.getWidth() / width); scale = (float) Math.min(scale, targetDimension.getHeight() / height); if (scale > 1) { scale = 1.0f; } Interpolation interpolation = Interpolation.getInstance(Interpolation.INTERP_NEAREST); RenderedImage scaledImage = ScaleDescriptor.create(sourceImage, scale, scale, 0.0f, 0.0f, interpolation, null); PlanarImage planarImage = PlanarImage.wrapRenderedImage(scaledImage); BufferedImage bufferedImage = planarImage.getAsBufferedImage(); planarImage.dispose(); return bufferedImage; } @Override protected void done() { try { imageLabel.setIcon(new ImageIcon(get())); imageLabel.setText(null); } catch (InterruptedException e) { e.printStackTrace(); imageLabel.setText("Could not create preview"); } catch (ExecutionException e) { e.printStackTrace(); imageLabel.setText("Could not create preview"); } } } } }
15,300
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageFileLayerType.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/layermanager/layersrc/image/ImageFileLayerType.java
/* * Copyright (C) 2010 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.rcp.layermanager.layersrc.image; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerContext; import com.bc.ceres.glayer.annotations.LayerTypeMetadata; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.glevel.MultiLevelSource; import com.bc.ceres.glevel.support.DefaultMultiLevelModel; import com.bc.ceres.glevel.support.DefaultMultiLevelSource; import javax.media.jai.operator.FileLoadDescriptor; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.awt.image.RenderedImage; import java.io.File; @LayerTypeMetadata(name = "ImageFileLayerType", aliasNames = {"org.esa.snap.rcp.layermanager.layersrc.image.ImageFileLayerType"}) public class ImageFileLayerType extends ImageLayer.Type { static final String PROPERTY_NAME_IMAGE_FILE = "filePath"; static final String PROPERTY_NAME_WORLD_TRANSFORM = "worldTransform"; @Override public Layer createLayer(LayerContext ctx, PropertySet configuration) { final File file = (File) configuration.getValue(PROPERTY_NAME_IMAGE_FILE); final AffineTransform transform = (AffineTransform) configuration.getValue(PROPERTY_NAME_WORLD_TRANSFORM); RenderedImage image = FileLoadDescriptor.create(file.getPath(), null, true, null); final Rectangle2D modelBounds = DefaultMultiLevelModel.getModelBounds(transform, image); final DefaultMultiLevelModel model = new DefaultMultiLevelModel(1, transform, modelBounds); final MultiLevelSource multiLevelSource = new DefaultMultiLevelSource(image, model); return new ImageLayer(this, multiLevelSource, configuration); } @Override public PropertySet createLayerConfig(LayerContext ctx) { final PropertyContainer template = new PropertyContainer(); final Property filePathModel = Property.create(PROPERTY_NAME_IMAGE_FILE, File.class); filePathModel.getDescriptor().setNotNull(true); template.addProperty(filePathModel); final Property worldTransformModel = Property.create(PROPERTY_NAME_WORLD_TRANSFORM, AffineTransform.class); worldTransformModel.getDescriptor().setNotNull(true); template.addProperty(worldTransformModel); return template; } }
3,127
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterPropertiesForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterPropertiesForm.java
package org.esa.snap.rcp.imgfilter; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.Converter; import com.bc.ceres.binding.PropertyContainer; 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.Enablement; import org.esa.snap.rcp.imgfilter.model.Filter; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; /** * A tabular editor form for a filter's properties. * * @author Norman */ public class FilterPropertiesForm extends JPanel implements PropertyChangeListener, Filter.Listener { public static final TrueCondition TRUE_CONDITION = new TrueCondition(); private Filter filter; private JComboBox<Filter.Operation> operationComboBox; private JTextField nameField; private JTextField shorthandField; private JTextField tagsField; private JTextField kernelOffsetXField; private JTextField kernelOffsetYField; private JTextField kernelWidthField; private JTextField kernelHeightField; private JTextField kernelQuotientField; private BindingContext bindingContext; public FilterPropertiesForm(Filter filter) { // super(new GridBagLayout()); super(new TableLayout()); setBorder(new EmptyBorder(4, 4, 4, 4)); createUI(); setFilter(filter); } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { if (this.filter != filter) { if (this.filter != null) { this.filter.removeListener(this); } if (bindingContext != null) { bindingContext.removePropertyChangeListener(this); bindingContext.unbind(bindingContext.getBinding("operation")); bindingContext.unbind(bindingContext.getBinding("name")); bindingContext.unbind(bindingContext.getBinding("shorthand")); bindingContext.unbind(bindingContext.getBinding("tags")); bindingContext.unbind(bindingContext.getBinding("kernelQuotient")); bindingContext.unbind(bindingContext.getBinding("kernelOffsetX")); bindingContext.unbind(bindingContext.getBinding("kernelOffsetY")); bindingContext.unbind(bindingContext.getBinding("kernelWidth")); bindingContext.unbind(bindingContext.getBinding("kernelHeight")); bindingContext = null; } Filter oldFilter = this.filter; this.filter = filter; if (this.filter != null) { PropertyContainer propertyContainer = PropertyContainer.createObjectBacked(this.filter); propertyContainer.getDescriptor("tags").setConverter(new TagsConverter()); propertyContainer.getDescriptor("operation").setDescription("<html>The image filter operation.<br/>CONVOLVE uses a real-valued kernel matrix.<br/>Other operations have Boolean matrices."); propertyContainer.getDescriptor("tags").setDescription("<html>Tags are used categorise and group filters.<br/>Use a comma to separate multiple tags."); propertyContainer.getDescriptor("name").setDescription("The filter's display name"); propertyContainer.getDescriptor("shorthand").setDescription("A shorthand for the name, used as default band name suffix"); propertyContainer.getDescriptor("kernelQuotient").setDescription("<html>Inverse scaling factor, will be used<br/>to pre-multiply the kernel matrix before convolution"); propertyContainer.getDescriptor("kernelWidth").setDescription("<html>Width of the kernel matrix<br/>(editing not supported here, use the graphical editor)"); propertyContainer.getDescriptor("kernelHeight").setDescription("<html>Height of the kernel matrix<br/>(editing not supported here, use the graphical editor)"); propertyContainer.getDescriptor("kernelOffsetX").setDescription("<html>Offset in X of the kernel matrix' 'key element'<br/>(editing not yet supported, will always be kernel center)"); propertyContainer.getDescriptor("kernelOffsetY").setDescription("<html>Offset in Y of the kernel matrix' 'key element'<br/>(editing not yet supported, will always be kernel center)"); bindingContext = new BindingContext(propertyContainer); bindingContext.bind("operation", operationComboBox); bindingContext.bind("name", nameField); bindingContext.bind("shorthand", shorthandField); bindingContext.bind("tags", tagsField); bindingContext.bind("kernelQuotient", kernelQuotientField); bindingContext.bind("kernelOffsetX", kernelOffsetXField); bindingContext.bind("kernelOffsetY", kernelOffsetYField); bindingContext.bind("kernelWidth", kernelWidthField); bindingContext.bind("kernelHeight", kernelHeightField); Enablement.Condition editableCondition = new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { return bindingContext.getPropertySet().getValue("editable"); } }; Enablement.Condition editableConvolutionCondition = new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { PropertySet propertySet = bindingContext.getPropertySet(); return Boolean.TRUE.equals(propertySet.getValue("editable")) && Filter.Operation.CONVOLVE.equals(propertySet.getValue("operation")); } }; bindingContext.bindEnabledState("operation", true, editableCondition); bindingContext.bindEnabledState("name", true, editableCondition); bindingContext.bindEnabledState("shorthand", true, editableCondition); bindingContext.bindEnabledState("tags", true, editableCondition); bindingContext.bindEnabledState("kernelQuotient", true, editableConvolutionCondition); // width and height are disabled here, because user shall use intended spinners bindingContext.bindEnabledState("kernelWidth", false, TRUE_CONDITION); bindingContext.bindEnabledState("kernelHeight", false, TRUE_CONDITION); // offsetX and offsetY are disabled here, because com.bc.ceres.jai.opimage.GeneralFilterOpImage does not support it so far bindingContext.bindEnabledState("kernelOffsetX", false, TRUE_CONDITION); bindingContext.bindEnabledState("kernelOffsetY", false, TRUE_CONDITION); bindingContext.adjustComponents(); bindingContext.addPropertyChangeListener(this); this.filter.addListener(this); } else { clearComponents(); } firePropertyChange("filter", oldFilter, this.filter); } } @Override public void filterChanged(Filter filter, String propertyName) { if (this.filter == filter) { bindingContext.adjustComponents(); } } @Override public void propertyChange(PropertyChangeEvent evt) { if (this.filter != null) { this.filter.fireChange(evt.getPropertyName()); } } private void clearComponents() { operationComboBox.setSelectedItem(null); nameField.setText(null); shorthandField.setText(null); tagsField.setText(null); kernelQuotientField.setText(null); kernelOffsetXField.setText(null); kernelOffsetYField.setText(null); kernelWidthField.setText(null); kernelHeightField.setText(null); } void createUI() { operationComboBox = new JComboBox<>(Filter.Operation.values()); nameField = new JTextField(12); shorthandField = new JTextField(6); tagsField = new JTextField(16); kernelQuotientField = new JTextField(8); kernelOffsetXField = new JTextField(8); kernelOffsetYField = new JTextField(8); kernelWidthField = new JTextField(8); kernelHeightField = new JTextField(8); TableLayout layout = (TableLayout) getLayout(); layout.setColumnCount(2); layout.setTableFill(TableLayout.Fill.HORIZONTAL); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableWeightX(0.5); layout.setTablePadding(2, 2); int row = 0; add(new JLabel("Operation:"), TableLayout.cell(row, 0)); add(operationComboBox, TableLayout.cell(row, 1)); row++; add(new JLabel("Name:"), TableLayout.cell(row, 0)); add(nameField, TableLayout.cell(row, 1)); row++; add(new JLabel("Shorthand:"), TableLayout.cell(row, 0)); add(shorthandField, TableLayout.cell(row, 1)); row++; add(new JLabel("Tags:"), TableLayout.cell(row, 0)); add(tagsField, TableLayout.cell(row, 1)); row++; add(new JLabel("Kernel quotient:"), TableLayout.cell(row, 0)); add(kernelQuotientField, TableLayout.cell(row, 1)); row++; add(new JLabel("Kernel offset X:"), TableLayout.cell(row, 0)); add(kernelOffsetXField, TableLayout.cell(row, 1)); row++; add(new JLabel("Kernel offset Y:"), TableLayout.cell(row, 0)); add(kernelOffsetYField, TableLayout.cell(row, 1)); row++; add(new JLabel("Kernel width:"), TableLayout.cell(row, 0)); add(kernelWidthField, TableLayout.cell(row, 1)); row++; add(new JLabel("Kernel height:"), TableLayout.cell(row, 0)); add(kernelHeightField, TableLayout.cell(row, 1)); /* GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 0; gbc.weightx = 0.5; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(2, 0, 2, 0); gbc.gridy = -1; gbc.gridy++; gbc.gridx = 0; add(new JLabel("Operation:"), gbc); gbc.gridx = 1; add(operationComboBox, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Name:"), gbc); gbc.gridx = 1; add(nameField, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Shorthand:"), gbc); gbc.gridx = 1; add(shorthandField, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Tags:"), gbc); gbc.gridx = 1; add(tagsField, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Kernel quotient:"), gbc); gbc.gridx = 1; add(kernelQuotientField, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Kernel offset X:"), gbc); gbc.gridx = 1; add(kernelOffsetXField, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Kernel offset Y:"), gbc); gbc.gridx = 1; add(kernelOffsetYField, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Kernel width:"), gbc); gbc.gridx = 1; add(kernelWidthField, gbc); gbc.gridy++; gbc.gridx = 0; add(new JLabel("Kernel height:"), gbc); gbc.gridx = 1; add(kernelHeightField, gbc); */ } private static class TagsConverter implements Converter<Object> { public static final HashSet<String> EMPTY_TAGS = new HashSet<>(); @Override public Class<?> getValueType() { return HashSet.class; } @Override public HashSet<String> parse(String text) throws ConversionException { if (text == null || text.isEmpty()) { return EMPTY_TAGS; } String[] tagArray = text.split(","); HashSet<String> tags = new LinkedHashSet<>(); for (String rawTag : tagArray) { String tag = rawTag.trim(); if (!tag.isEmpty()) { tags.add(tag); } } return tags; } @Override public String format(Object value) { if (value instanceof Set) { Set<String> set = (Set<String>) value; if (!set.isEmpty()) { StringBuilder sb = new StringBuilder(); for (String s : set) { if (sb.length() > 0) { sb.append(","); } sb.append(s); } return sb.toString(); } } return null; } } private static class TrueCondition extends Enablement.Condition { @Override public boolean evaluate(BindingContext bindingContext) { return true; } } }
13,455
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterSetsForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterSetsForm.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.rcp.imgfilter.model.Filter; import org.esa.snap.rcp.imgfilter.model.FilterSet; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; /** * A form used too edit and display multiple {@link FilterSet}s arranged in a {@code JTabbedPane}. * * @author Norman */ public class FilterSetsForm extends JPanel implements FilterSetForm.Listener { private final String sourceBandName; private final JTabbedPane tabbedPane; private final JTextField targetBandNameField; private final JComboBox<Integer> iterationCountComboBox; private Filter selectedFilter; public FilterSetsForm(String sourceBandName, final FilterSetForm.Listener selectionListener, FilterSetFileStore filterSetStore, FilterEditor filterEditor, FilterSet[] filterSets) { super(new BorderLayout(4, 4)); setBorder(new EmptyBorder(4, 4, 4, 4)); this.sourceBandName = sourceBandName; tabbedPane = new JTabbedPane(); for (FilterSet filterSet : filterSets) { FilterSetForm filterSetForm = new FilterSetForm(filterSet, filterSetStore, filterEditor); filterSetForm.addListener(selectionListener); filterSetForm.addListener(this); tabbedPane.addTab(filterSet.getName(), filterSetForm); } tabbedPane.addChangeListener(e -> { FilterSetForm filterSetForm = (FilterSetForm) tabbedPane.getSelectedComponent(); if (filterSetForm != null) { Filter selectedFilter1 = filterSetForm.getSelectedFilterModel(); filterSetForm.fireFilterSelected(selectedFilter1); } }); targetBandNameField = new JTextField(10); iterationCountComboBox = new JComboBox<>(new Integer[]{1, 2, 3, 4, 5}); JPanel namePanel = new JPanel(new BorderLayout(2, 2)); namePanel.add(new JLabel("Band name:"), BorderLayout.WEST); namePanel.add(targetBandNameField, BorderLayout.CENTER); namePanel.setToolTipText("The target band name"); JPanel iterPanel = new JPanel(new BorderLayout(2, 2)); iterPanel.add(new JLabel("Number of iterations:"), BorderLayout.WEST); iterPanel.add(iterationCountComboBox, BorderLayout.CENTER); iterPanel.setToolTipText("The number of times the filter will selected be applied to the source band"); JPanel inputPanel = new JPanel(new BorderLayout(2, 2)); inputPanel.add(namePanel, BorderLayout.NORTH); inputPanel.add(iterPanel, BorderLayout.SOUTH); add(tabbedPane, BorderLayout.CENTER); add(inputPanel, BorderLayout.SOUTH); updateBandNameField(); } public Filter getSelectedFilter() { return selectedFilter; } public String getTargetBandName() { return targetBandNameField.getText(); } public int getIterationCount() { return (Integer) iterationCountComboBox.getSelectedItem(); } @Override public void filterSelected(FilterSet filterSet, Filter filter) { if (this.selectedFilter != filter) { this.selectedFilter = filter; updateBandNameField(); } } @Override public void filterChanged(FilterSet filterSet, Filter filter, String propertyName) { if (this.selectedFilter == filter) { updateBandNameField(); } } @Override public void filterAdded(FilterSet filterSet, Filter filter) { } @Override public void filterRemoved(FilterSet filterSet, Filter filter) { } private void updateBandNameField() { if (selectedFilter != null) { targetBandNameField.setText(sourceBandName + "_" + selectedFilter.getShorthand()); targetBandNameField.setEditable(true); } else { targetBandNameField.setText(sourceBandName + "_?"); targetBandNameField.setEditable(false); } } }
4,108
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterSetForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterSetForm.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.rcp.imgfilter.model.Filter; import org.esa.snap.rcp.imgfilter.model.FilterSet; import org.esa.snap.rcp.imgfilter.model.FilterSetStore; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.tango.TangoIcons; import javax.swing.DropMode; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JToolBar; import javax.swing.JTree; import javax.swing.SwingConstants; import javax.swing.border.EmptyBorder; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.TreePath; import javax.swing.tree.TreeSelectionModel; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Font; import java.awt.dnd.DnDConstants; import java.awt.dnd.DropTarget; import java.awt.dnd.DropTargetAdapter; import java.awt.dnd.DropTargetDragEvent; import java.awt.dnd.DropTargetDropEvent; import java.awt.dnd.DropTargetEvent; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * A form used too edit and display a single {@link FilterSet} in a {@code JTree}. * * @author Norman */ public class FilterSetForm extends JPanel { private FilterSet filterSet; private JButton addButton; private JButton removeButton; private JButton editButton; private JTree filterTree; private FilterSetStore filterSetStore; private FilterEditor filterEditor; private transient List<Listener> listeners; private JButton saveButton; private boolean modified; public FilterSetForm(FilterSet filterSet, FilterSetStore filterSetStore, FilterEditor filterEditor) { super(new BorderLayout(4, 4)); this.filterSetStore = filterSetStore; this.filterEditor = filterEditor; setBorder(new EmptyBorder(4, 4, 4, 4)); listeners = new ArrayList<>(); this.filterSet = filterSet; this.filterSet.addListener(new FilterSet.Listener() { @Override public void filterAdded(FilterSet filterSet, Filter filter) { setModified(true); } @Override public void filterRemoved(FilterSet filterSet, Filter filter) { setModified(true); } @Override public void filterChanged(FilterSet filterSet, Filter filter, String propertyName) { setModified(true); } }); initUI(); } public boolean isModified() { return modified; } public void setModified(boolean modified) { if (this.modified != modified) { this.modified = modified; updateState(); } } public void addListener(Listener listener) { listeners.add(listener); filterSet.addListener(listener); } public void removeListener(Listener listener) { listeners.remove(listener); filterSet.removeListener(listener); } public Filter getSelectedFilterModel() { TreePath selectionPath = filterTree.getSelectionPath(); if (selectionPath != null) { return getFilterForSelectionPath(selectionPath); } return null; } private void initUI() { addButton = new JButton(TangoIcons.actions_list_add(TangoIcons.Res.R22)); addButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Filter filter = Filter.create(5); filter.setEditable(true); FilterTreeModel model = (FilterTreeModel) filterTree.getModel(); model.addFilter(filter, filterTree.getSelectionPath()); TreePath filterPath = model.getFilterPath(filter); filterTree.setSelectionPath(filterPath); } }); addButton.setToolTipText("Add user-defined filter"); removeButton = new JButton(TangoIcons.actions_list_remove(TangoIcons.Res.R22)); removeButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ((FilterTreeModel) filterTree.getModel()).removeFilter((Filter) filterTree.getSelectionPath().getLastPathComponent()); } }); removeButton.setToolTipText("Remove user-defined filter"); editButton = new JButton(TangoIcons.actions_document_properties(TangoIcons.Res.R22)); editButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Filter filter = (Filter) filterTree.getSelectionPath().getLastPathComponent(); filterEditor.setFilter(filter); filterEditor.show(); } }); editButton.setToolTipText("Show or edit properties of selected filter"); saveButton = new JButton(TangoIcons.actions_document_save(TangoIcons.Res.R22)); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { filterSetStore.storeFilterSetModel(filterSet); setModified(false); } catch (IOException ioe) { Dialogs.showError("Save","Failed to save:\n" + ioe.getMessage()); } } }); saveButton.setToolTipText("Store the selected user-defined filter"); JToolBar toolBar = new JToolBar(SwingConstants.VERTICAL); toolBar.setFloatable(false); toolBar.setBorderPainted(false); toolBar.add(addButton); toolBar.add(removeButton); toolBar.add(editButton); toolBar.add(saveButton); filterTree = new JTree(filterSet != null ? new FilterTreeModel(filterSet) : null); filterTree.setRootVisible(false); filterTree.setShowsRootHandles(true); filterTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); filterTree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { updateState(); TreePath selectionPath = filterTree.getSelectionPath(); System.out.println("TreeSelectionListener.valueChanged: selectionPath = " + selectionPath); Filter selectedFilter = getFilterForSelectionPath(selectionPath); if (selectedFilter != null) { filterEditor.setFilter(selectedFilter); fireFilterSelected(selectedFilter); } else { // selectedFilter == null: We will clear editor only, if the currently displayed filter // is still contained in our filter set (otherwise the selection change may have occurred due to a removal). Filter displayedFilter = filterEditor.getFilter(); if (!filterSet.containsFilter(displayedFilter)) { filterEditor.setFilter(null); } } } }); filterTree.setCellRenderer(new MyDefaultTreeCellRenderer()); filterTree.putClientProperty("JTree.lineStyle", "Angled"); filterTree.getModel().addTreeModelListener(new TreeModelListener() { @Override public void treeNodesChanged(TreeModelEvent e) { } @Override public void treeNodesInserted(TreeModelEvent e) { } @Override public void treeNodesRemoved(TreeModelEvent e) { } @Override public void treeStructureChanged(TreeModelEvent e) { Filter filter = filterEditor.getFilter(); if (filter != null) { FilterTreeModel model = (FilterTreeModel) filterTree.getModel(); TreePath filterPath = model.getFilterPath(filter); filterTree.expandPath(filterPath); filterTree.setSelectionPath(filterPath); } } }); //installTreeDragAndDrop(); expandAllTreeNodes(); add(new JScrollPane(filterTree), BorderLayout.CENTER); add(toolBar, BorderLayout.EAST); updateState(); } private Filter getFilterForSelectionPath(TreePath selectionPath) { if (selectionPath != null) { Object lastPathComponent = selectionPath.getLastPathComponent(); if (lastPathComponent instanceof Filter) { return (Filter) lastPathComponent; } } return null; } @SuppressWarnings("UnusedDeclaration") private void installTreeDragAndDrop() { filterTree.setDragEnabled(true); filterTree.setDropMode(DropMode.INSERT); filterTree.setDropTarget(new DropTarget(filterTree, DnDConstants.ACTION_MOVE, new DropTargetAdapter() { @Override public void dragEnter(DropTargetDragEvent dtde) { System.out.println("dragEnter: dtde = " + dtde); } @Override public void dragOver(DropTargetDragEvent dtde) { System.out.println("dragOver: dtde = " + dtde); } @Override public void dropActionChanged(DropTargetDragEvent dtde) { System.out.println("dropActionChanged: dtde = " + dtde); } @Override public void dragExit(DropTargetEvent dte) { System.out.println("dragExit: dte = " + dte); } @Override public void drop(DropTargetDropEvent dtde) { System.out.println("drop: dtde = " + dtde); } })); } private void updateState() { TreePath selectionPath = filterTree.getSelectionPath(); boolean filterModelSelected = selectionPath != null && selectionPath.getLastPathComponent() instanceof Filter; addButton.setEnabled(filterSet.isEditable()); removeButton.setEnabled(filterModelSelected && filterSet.isEditable()); editButton.setEnabled(filterModelSelected); saveButton.setEnabled(filterSet.isEditable() && isModified()); } private void expandAllTreeNodes() { FilterTreeModel model = (FilterTreeModel) filterTree.getModel(); int childCount = model.getChildCount(model.getRoot()); for (int i = 0; i < childCount; i++) { Object child = model.getChild(model.getRoot(), i); TreePath treePath = new TreePath(new Object[]{model.getRoot(), child}); filterTree.expandRow(filterTree.getRowForPath(treePath)); } } private static class MyDefaultTreeCellRenderer extends DefaultTreeCellRenderer { private final static Icon seIcon = new ImageIcon(FilterSetForm.class.getResource("se.png")); private final static Icon kernelIcon = new ImageIcon(FilterSetForm.class.getResource("kernel.png")); private Font plainFont; private Font boldFont; @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { final JLabel c = (JLabel) super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (plainFont == null) { plainFont = c.getFont().deriveFont(Font.PLAIN); boldFont = c.getFont().deriveFont(Font.BOLD); } c.setFont(leaf ? plainFont : boldFont); if (value instanceof Filter) { Filter filter = (Filter) value; c.setIcon(filter.getOperation() == Filter.Operation.CONVOLVE ? kernelIcon : seIcon); } else { c.setIcon(null); } return c; } } void fireFilterSelected(Filter filter) { for (Listener listener : listeners) { listener.filterSelected(filterSet, filter); } } public interface Listener extends FilterSet.Listener { void filterSelected(FilterSet filterSet, Filter filter); } }
12,671
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterKernelForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterKernelForm.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.rcp.imgfilter.model.Filter; import javax.swing.Box; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JSpinner; import javax.swing.JTextField; import javax.swing.JToolBar; import javax.swing.SpinnerNumberModel; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; /** * A form containing a {link @FilterKernelCanvas} and components to change size and fill value of the kernel. * * @author Norman */ public class FilterKernelForm extends JPanel implements Filter.Listener { private Filter filter; private CanvasMouseListener canvasMouseListener; private FilterKernelCanvas kernelCanvas; private JSpinner kernelWidthSpinner; private JSpinner kernelHeightSpinner; private JComboBox<Number> fillValueCombo; private double fillValue; private final DefaultComboBoxModel<Number> structuringFillValueModel = new DefaultComboBoxModel<>(new Number[]{0, 1}); private final DefaultComboBoxModel<Number> kernelFillValueModel = new DefaultComboBoxModel<>(new Number[]{-5., -4., -3., -2., -1., 0., 1., 2., 3., 4., 5.}); public FilterKernelForm(Filter filter) { super(new BorderLayout(4, 4)); setBorder(new EmptyBorder(4, 4, 4, 4)); this.filter = null; this.fillValue = 0.0; setFilter(filter); } public double getFillValue() { return fillValue; } public void setFillValue(double fillValue) { double fillValueOld = this.fillValue; this.fillValue = fillValue; firePropertyChange("fillValue", fillValueOld, fillValue); } @Override public void filterChanged(Filter filter, String propertyName) { if (this.filter != filter) { return; } boolean structureElement = filter.getOperation() != Filter.Operation.CONVOLVE; fillValueCombo.setModel(structureElement ? structuringFillValueModel : kernelFillValueModel); int kernelWidth = filter.getKernelWidth(); int kernelHeight = filter.getKernelHeight(); if (kernelWidthSpinner != null && ((Number) kernelWidthSpinner.getValue()).intValue() != kernelWidth) { kernelWidthSpinner.setValue(kernelWidth); } if (kernelHeightSpinner != null && ((Number) kernelHeightSpinner.getValue()).intValue() != kernelHeight) { kernelHeightSpinner.setValue(kernelHeight); } } @Override public Dimension getPreferredSize() { return new Dimension(320, 320); } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { Filter filterOld = this.filter; if (filterOld != filter) { if (this.filter != null) { this.filter.removeListener(this); } this.filter = filter; initUI(); if (this.filter != null) { this.filter.addListener(this); } firePropertyChange("filter", filterOld, this.filter); } } private void initUI() { removeAll(); if (kernelCanvas != null && canvasMouseListener != null) { kernelCanvas.removeMouseListener(canvasMouseListener); kernelCanvas.removeMouseMotionListener(canvasMouseListener); kernelCanvas = null; } fillValueCombo = null; kernelHeightSpinner = null; kernelWidthSpinner = null; if (filter == null) { invalidate(); revalidate(); repaint(); return; } kernelCanvas = new FilterKernelCanvas(filter); if (canvasMouseListener == null) { canvasMouseListener = new CanvasMouseListener(); } kernelCanvas.addMouseListener(canvasMouseListener); if (filter.isEditable()) { kernelCanvas.addMouseMotionListener(canvasMouseListener); } if (filter.isEditable()) { boolean structureElement = filter.getOperation() != Filter.Operation.CONVOLVE; if (structureElement) { fillValueCombo = new JComboBox<>(structuringFillValueModel); ((JTextField) fillValueCombo.getEditor().getEditorComponent()).setColumns(1); fillValueCombo.setEditable(false); fillValueCombo.setSelectedItem((int) getFillValue()); } else { fillValueCombo = new JComboBox<>(kernelFillValueModel); ((JTextField) fillValueCombo.getEditor().getEditorComponent()).setColumns(3); fillValueCombo.setEditable(true); fillValueCombo.setSelectedItem(getFillValue()); } fillValueCombo.addItemListener(e -> setFillValue(((Number) fillValueCombo.getSelectedItem()).doubleValue())); fillValueCombo.setToolTipText("Value that will be used to set a kernel element when clicking into the matrix"); kernelWidthSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 100, 1)); kernelWidthSpinner.setValue(filter.getKernelHeight()); kernelWidthSpinner.addChangeListener(e -> { Integer kernelWidth = (Integer) kernelWidthSpinner.getValue(); filter.setKernelSize(kernelWidth, filter.getKernelHeight()); }); kernelWidthSpinner.setToolTipText("Width of the kernel (number of matrix columns)"); kernelHeightSpinner = new JSpinner(new SpinnerNumberModel(1, 1, 100, 1)); kernelHeightSpinner.setValue(filter.getKernelWidth()); kernelHeightSpinner.addChangeListener(e -> { Integer kernelHeight = (Integer) kernelHeightSpinner.getValue(); filter.setKernelSize(filter.getKernelWidth(), kernelHeight); }); kernelHeightSpinner.setToolTipText("Height of the kernel (number of matrix rows)"); JToolBar toolBar = new JToolBar(JToolBar.HORIZONTAL); toolBar.setFloatable(false); toolBar.setRollover(true); toolBar.add(new JLabel("Fill:")); toolBar.add(fillValueCombo); toolBar.add(Box.createHorizontalStrut(32)); toolBar.add(new JLabel(" W:")); toolBar.add(kernelWidthSpinner); toolBar.add(new JLabel(" H:")); toolBar.add(kernelHeightSpinner); add(kernelCanvas, BorderLayout.CENTER); add(toolBar, BorderLayout.SOUTH); } else { add(kernelCanvas, BorderLayout.CENTER); } invalidate(); revalidate(); repaint(); } private class CanvasMouseListener extends MouseAdapter { @Override public void mouseReleased(MouseEvent e) { FilterKernelCanvas kernelCanvas = (FilterKernelCanvas) e.getComponent(); if (e.isPopupTrigger()) { showPopup(e, kernelCanvas); } else { kernelCanvas.getFilter().adjustKernelQuotient(); } } @Override public void mousePressed(MouseEvent e) { FilterKernelCanvas kernelCanvas = (FilterKernelCanvas) e.getComponent(); if (e.isPopupTrigger()) { showPopup(e, kernelCanvas); } else if (e.getButton() == 1 && kernelCanvas.getFilter().isEditable()) { setElement(kernelCanvas, e); } } @Override public void mouseDragged(MouseEvent e) { boolean button1 = (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0; if (button1 && kernelCanvas.getFilter().isEditable()) { FilterKernelCanvas kernelCanvas = (FilterKernelCanvas) e.getComponent(); setElement(kernelCanvas, e); } } private void showPopup(MouseEvent e, FilterKernelCanvas kernelCanvas) { e.consume(); JPopupMenu popupMenu = createPopupMenu(kernelCanvas); popupMenu.show(kernelCanvas, e.getX(), e.getY()); } private void setElement(FilterKernelCanvas kernelCanvas, MouseEvent e) { int index = kernelCanvas.getKernelElementIndex(e.getX(), e.getY()); if (index >= 0) { kernelCanvas.getFilter().setKernelElement(index, getFillValue()); } } } protected JPopupMenu createPopupMenu(final FilterKernelCanvas kernelCanvas) { JPopupMenu popupMenu = new JPopupMenu(); JMenuItem copyItem = new JMenuItem("Copy"); copyItem.addActionListener(e -> { Clipboard systemClip = Toolkit.getDefaultToolkit().getSystemClipboard(); systemClip.setContents(new StringSelection(kernelCanvas.getFilter().getKernelElementsAsText()), null); }); popupMenu.add(copyItem); if (!filter.isEditable()) { return popupMenu; } JMenuItem pasteItem = new JMenuItem("Paste"); pasteItem.setEnabled(isPastePossible()); pasteItem.addActionListener(e -> { Clipboard systemClip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable transfer = systemClip.getContents(null); try { String data = (String) transfer.getTransferData(DataFlavor.stringFlavor); kernelCanvas.getFilter().setKernelElementsFromText(data); kernelCanvas.getFilter().adjustKernelQuotient(); } catch (Error | RuntimeException e1) { e1.printStackTrace(); throw e1; } catch (Throwable e1) { e1.printStackTrace(); } }); popupMenu.add(pasteItem); JMenuItem clearItem = new JMenuItem("Clear"); clearItem.addActionListener(e -> kernelCanvas.getFilter().fillRectangle(0.0)); popupMenu.add(clearItem); popupMenu.addSeparator(); final double fillValue = getFillValue(); String fillValueText = fillValue == (int) fillValue ? String.valueOf((int) fillValue) : String.valueOf(fillValue); JMenuItem fillRectangleItem = new JMenuItem(String.format("Fill Rectangle by <%s>", fillValueText)); fillRectangleItem.addActionListener(e -> { kernelCanvas.getFilter().fillRectangle(fillValue); kernelCanvas.getFilter().adjustKernelQuotient(); }); popupMenu.add(fillRectangleItem); JMenuItem fillEllipseItem = new JMenuItem(String.format("Fill Ellipse by <%s>", fillValueText)); fillEllipseItem.addActionListener(e -> { kernelCanvas.getFilter().fillEllipse(fillValue); kernelCanvas.getFilter().adjustKernelQuotient(); }); popupMenu.add(fillEllipseItem); JMenuItem fillGaussItem = new JMenuItem("Fill Gaussian"); fillGaussItem.addActionListener(e -> { kernelCanvas.getFilter().fillGaussian(); kernelCanvas.getFilter().adjustKernelQuotient(); }); popupMenu.add(fillGaussItem); JMenuItem fillLaplaceItem = new JMenuItem("Fill Laplacian"); fillLaplaceItem.addActionListener(e -> { kernelCanvas.getFilter().fillLaplacian(); kernelCanvas.getFilter().adjustKernelQuotient(); }); popupMenu.add(fillLaplaceItem); JMenuItem fillRandomItem = new JMenuItem("Fill Random"); fillRandomItem.addActionListener(e -> { kernelCanvas.getFilter().fillRandom(); kernelCanvas.getFilter().adjustKernelQuotient(); }); popupMenu.add(fillRandomItem); return popupMenu; } private boolean isPastePossible() { boolean enabled = false; Clipboard systemClip = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable transfer = systemClip.getContents(null); if (transfer.isDataFlavorSupported(DataFlavor.stringFlavor)) { try { String data = (String) transfer.getTransferData(DataFlavor.stringFlavor); enabled = Filter.isKernelDataText(data); } catch (UnsupportedFlavorException | IOException ignored) { } } return enabled; } }
12,783
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterEditor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterEditor.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.rcp.imgfilter.model.Filter; /** * Filter editors are used to get/set a filter and can be displayed. * * @author Norman */ public interface FilterEditor { Filter getFilter(); void setFilter(Filter filter); void show(); void hide(); }
316
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterSetFileStore.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterSetFileStore.java
package org.esa.snap.rcp.imgfilter; import com.thoughtworks.xstream.XStream; import org.esa.snap.rcp.imgfilter.model.FilterSet; import org.esa.snap.rcp.imgfilter.model.FilterSetStore; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Class used to store/reload user-defined image filters. * * @author Norman */ public class FilterSetFileStore implements FilterSetStore { final File filtersDir; public FilterSetFileStore(File filtersDir) { this.filtersDir = filtersDir; } public List<FilterSet> loadFilterSetModels() throws IOException { XStream xStream = FilterSet.createXStream(); File[] files = filtersDir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".xml"); } }); ArrayList<FilterSet> list = new ArrayList<>(); if (files == null) { return list; } IOException ioe = null; for (File file : files) { try { FilterSet filterSet = new FilterSet(); xStream.fromXML(file, filterSet); list.add(filterSet); } catch (Exception e) { ioe = new IOException(e); } } if (ioe != null && list.isEmpty()) { throw ioe; } return list; } @Override public void storeFilterSetModel(FilterSet filterSet) throws IOException { if (!filtersDir.exists() && !filtersDir.mkdirs()) { throw new IOException("Failed to create directory\n" + filtersDir); } File file = new File(filtersDir, filterSet.getName().toLowerCase() + "-filters.xml"); XStream xStream = FilterSet.createXStream(); try (FileWriter fileWriter = new FileWriter(file)) { xStream.toXML(filterSet, fileWriter); } } }
2,048
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterWindow.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterWindow.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.imgfilter.model.Filter; import org.esa.snap.rcp.util.Dialogs; import org.openide.util.NbBundle; import javax.swing.JDialog; import javax.swing.JTabbedPane; import java.awt.Dialog; import java.awt.Dimension; import java.awt.Window; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.prefs.Preferences; /** * Represents a window that lets users inspect and edit a single image {@link Filter}. * * @author Norman */ @NbBundle.Messages({ "LBL_FilterWindow_Title=Image Filter", "LBL_FilterWindow_Kernel=Filter Kernel", "LBL_FilterWindow_Properties=Filter Properties", "TXT_FilterWindow_Hint=<html>Right-clicking into the kernel editor canvas<br>" + "opens a context menu with <b>more options</b>", }) public class FilterWindow implements FilterEditor { private Window parentWindow; private JDialog dialog; private FilterKernelForm kernelForm; private Filter filter; private FilterPropertiesForm propertiesForm; public FilterWindow(Window parentWindow) { this.parentWindow = parentWindow; } @Override public Filter getFilter() { return filter; } @Override public void setFilter(Filter filter) { this.filter = filter; if (kernelForm != null) { kernelForm.setFilter(filter); } if (propertiesForm != null) { propertiesForm.setFilter(filter); } } @Override public void show() { if (dialog == null) { kernelForm = new FilterKernelForm(filter); propertiesForm = new FilterPropertiesForm(filter); dialog = new JDialog(parentWindow, Bundle.LBL_FilterWindow_Title(), Dialog.ModalityType.MODELESS); JTabbedPane tabbedPane = new JTabbedPane(); tabbedPane.addTab(Bundle.LBL_FilterWindow_Kernel(), kernelForm); tabbedPane.addTab(Bundle.LBL_FilterWindow_Properties(), propertiesForm); dialog.setContentPane(tabbedPane); Preferences filterWindowPrefs = SnapApp.getDefault().getPreferences().node("filterWindow"); dialog.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { filterWindowPrefs.putInt("x", e.getWindow().getX()); filterWindowPrefs.putInt("y", e.getWindow().getY()); filterWindowPrefs.putInt("width", e.getWindow().getWidth()); filterWindowPrefs.putInt("height", e.getWindow().getHeight()); } }); Dimension preferredSize = dialog.getPreferredSize(); int x = filterWindowPrefs.getInt("x", 100); int y = filterWindowPrefs.getInt("y", 100); int w = filterWindowPrefs.getInt("width", preferredSize.width); int h = filterWindowPrefs.getInt("height", preferredSize.height); dialog.setBounds(x, y, w, h); Dialogs.showInformation(Bundle.LBL_FilterWindow_Title(), Bundle.TXT_FilterWindow_Hint(), "filterWindow.moreOptions"); } dialog.setVisible(true); } @Override public void hide() { if (dialog != null) { dialog.setVisible(false); } } }
3,469
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterKernelCanvas.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterKernelCanvas.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.rcp.imgfilter.model.Filter; import javax.swing.JPanel; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Insets; import java.awt.geom.Rectangle2D; /** * A canvas that displays the filter's kernel matrix. * * @author Norman */ public class FilterKernelCanvas extends JPanel implements Filter.Listener { private final Filter filter; private double maxAbsElementValue; public FilterKernelCanvas(Filter filter) { this.filter = filter; setFont(new Font("Verdana", Font.PLAIN, 10)); this.filter.addListener(this); maxAbsElementValue = -1; } public Filter getFilter() { return filter; } @Override public void filterChanged(Filter filter, String propertyName) { updateMaxAbsElementValue(); repaint(); } @Override public Dimension getPreferredSize() { return new Dimension( Math.max(filter.getKernelWidth() * 16, 200), Math.max(filter.getKernelHeight() * 16, 200)); } public int getKernelElementIndex(int x, int y) { Insets insets = getInsets(); int w = getWidth() - (insets.left + insets.right); int h = getHeight() - (insets.top + insets.bottom); int kernelWidth = filter.getKernelWidth(); int kernelHeight = filter.getKernelHeight(); int cellSize = Math.min(w / kernelWidth, h / kernelHeight); int x0 = insets.left + (w - cellSize * kernelWidth) / 2; int y0 = insets.top + (h - cellSize * kernelHeight) / 2; int i = (x - x0) / cellSize; int j = (y - y0) / cellSize; if (i >= 0 && i < kernelWidth && j >= 0 && j < kernelHeight) { return j * kernelWidth + i; } return -1; } @Override protected void paintComponent(Graphics g) { if (filter == null) { return; } if (maxAbsElementValue < 0) { updateMaxAbsElementValue(); } g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); Insets insets = getInsets(); int w = getWidth() - (insets.left + insets.right); int h = getHeight() - (insets.top + insets.bottom); int kernelWidth = filter.getKernelWidth(); int kernelHeight = filter.getKernelHeight(); int cellSize = Math.min(w / kernelWidth, h / kernelHeight); int x0 = insets.left + (w - cellSize * kernelWidth) / 2; int y0 = insets.top + (h - cellSize * kernelHeight) / 2; for (int j = 0; j < kernelHeight; j++) { int y = y0 + j * cellSize; for (int i = 0; i < kernelWidth; i++) { int x = x0 + i * cellSize; paintKernelElement(g, x, y, cellSize, cellSize, j * kernelWidth + i); } } g.setColor(Color.GRAY); g.drawRect(x0, y0, kernelWidth * cellSize, kernelHeight * cellSize); } private void paintKernelElement(Graphics g, int x, int y, int cw, int ch, int index) { if (filter.getOperation() == Filter.Operation.CONVOLVE) { paintConvolutionElement(g, x, y, cw, ch, index); } else { paintStructuringElement(g, x, y, cw, ch, index); } } private void paintConvolutionElement(Graphics g, int x, int y, int cw, int ch, int index) { double value = filter.getKernelElement(index); Color color = Color.WHITE; if (value > 0) { int comp = 255 - (int) (maxAbsElementValue == 0 ? 0 : (100 * value) / maxAbsElementValue); color = new Color(255, comp, comp); } else if (value < 0) { int comp = 255 - (int) (maxAbsElementValue == 0 ? 0 : (100 * -value) / maxAbsElementValue); color = new Color(comp, comp, 255); } g.setColor(color); g.fillRect(x, y, cw, ch); int cellSize = Math.min(cw, ch); //System.out.println("cellSize = " + cellSize); if (cellSize >= 4) { g.setColor(Color.GRAY); g.drawRect(x, y, cw, ch); if (isOffsetIndex(index)) { g.setColor(Color.GRAY); g.drawRect(x + 1, y + 1, cw - 2, ch - 2); } } if (cellSize > 12) { float fontSize = Math.min(16.0f, 0.5f * cellSize); String text = value == (int) value ? String.valueOf((int) value) : String.valueOf(value); g.setFont(getFont().deriveFont(fontSize)); Rectangle2D bounds = g.getFontMetrics().getStringBounds(text, g); int x1 = x + (int) (0.5 * cw - 0.5 * bounds.getWidth()); int y1 = y + (int) (ch - 0.5 * bounds.getHeight()); g.setColor(filter.isEditable() ? getForeground() : Color.DARK_GRAY); g.drawString(text, x1, y1); } } private boolean isOffsetIndex(int index) { return index == filter.getKernelOffsetY() * filter.getKernelWidth() + filter.getKernelOffsetX(); } private void paintStructuringElement(Graphics g, int x, int y, int cw, int ch, int index) { g.setColor(filter.getKernelElement(index) != 0.0 ? Color.DARK_GRAY : Color.WHITE); g.fillRect(x, y, cw, ch); int cellSize = Math.min(cw, ch); //System.out.println("cellSize = " + cellSize); if (cellSize >= 4) { g.setColor(Color.GRAY); g.drawRect(x, y, cw, ch); if (isOffsetIndex(index)) { g.setColor(Color.GRAY); g.drawRect(x + 1, y + 1, cw - 2, ch - 2); } } } private void updateMaxAbsElementValue() { maxAbsElementValue = 0; if (filter != null) { for (double v : filter.getKernelElements()) { maxAbsElementValue = Math.max(maxAbsElementValue, Math.abs(v)); } } } }
5,961
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterTreeModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilterTreeModel.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.rcp.imgfilter.model.Filter; import org.esa.snap.rcp.imgfilter.model.FilterSet; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.tree.TreeModel; import javax.swing.tree.TreePath; import java.util.ArrayList; import java.util.HashSet; import java.util.List; /** * The internal model for a {@code JTree} displaying a {@link FilterSet}. * * @author Norman */ class FilterTreeModel implements TreeModel, FilterSet.Listener { private final Root root; private final ArrayList<TreeModelListener> listeners; private final FilterSet filterSet; public FilterTreeModel(FilterSet filterSet) { this.filterSet = filterSet; this.filterSet.addListener(this); root = new Root(); listeners = new ArrayList<>(); createTreeNodes(); } public void addFilter(Filter filter, TreePath selectionPath) { if (selectionPath != null) { Object[] path = selectionPath.getPath(); if (path.length >= 2) { Group group = (Group) path[1]; filter.getTags().add(group.name); } } filterSet.addFilter(filter); } public void removeFilter(Filter filter) { filterSet.removeFilter(filter); } public TreePath getFilterPath(Filter filter) { for (Group group : root.groups) { for (Filter filter1 : group.filters) { if (filter1 == filter) { return new TreePath(new Object[] {root, group, filter}); } } } return null; } @Override public void filterAdded(FilterSet filterSet, Filter filter) { insertTreeNodes(filter); } @Override public void filterRemoved(FilterSet filterSet, Filter filter) { removeTreeNodes(filter); } @Override public void filterChanged(FilterSet filterSet, Filter filter, String propertyName) { if ("tags".equals(propertyName)) { createTreeNodes(); fireTreeStructureChanged(); } else { fireTreeNodesChanged(filter); } } @Override public Object getRoot() { return root; } @Override public Object getChild(Object parent, int index) { if (parent == root) { return root.groups.get(index); } else if (parent instanceof Group) { return ((Group) parent).filters.get(index); } return null; } @Override public int getChildCount(Object parent) { if (parent == root) { return root.groups.size(); } else if (parent instanceof Group) { return ((Group) parent).filters.size(); } return 0; } @Override public int getIndexOfChild(Object parent, Object child) { if (parent == root) { return root.groups.indexOf(child); } else if (parent instanceof Group) { return ((Group) parent).filters.indexOf(child); } return -1; } @Override public boolean isLeaf(Object node) { return node instanceof Filter; } @Override public void valueForPathChanged(TreePath treePath, Object newValue) { /* System.out.print("valueForPathChanged: "); for (Object node : treePath.getPath()) { System.out.print("/" + node); } System.out.print(" = " + newValue); */ //notifyTreeNodeChanged(treePath); } @Override public void addTreeModelListener(TreeModelListener l) { listeners.add(l); } @Override public void removeTreeModelListener(TreeModelListener l) { listeners.remove(l); } private synchronized void insertTreeNodes(Filter filter) { HashSet<String> remainingTags = new HashSet<>(filter.getTags()); if (filter.getTags().isEmpty() || filter.getTags().contains(root.any.name )) { Group group = root.any; if (!root.groups.contains(group)) { _addGroup(group); } _addFilter(group, filter); remainingTags.remove(group.name); if (remainingTags.isEmpty()) { return; } } for (Group group : root.groups) { if (filter.getTags().contains(group.name) || filter.getTags().isEmpty() && group == root.any) { _addFilter(group, filter); remainingTags.remove(group.name); } } for (String remainingTag : remainingTags) { Group group = new Group(remainingTag); _addGroup(group); _addFilter(group, filter); } } private void _addGroup(Group group) { root.groups.add(group); fireTreeNodeInserted(root.groups.size() - 1, group); } private void _addFilter(Group group, Filter filter) { group.filters.add(filter); fireTreeNodeInserted(group, group.filters.size() - 1, filter); } private synchronized void removeTreeNodes(Filter filter) { int groupIndex = 0; while (groupIndex < root.groups.size()) { Group group = root.groups.get(groupIndex); int filterIndex = group.filters.indexOf(filter); if (filterIndex >= 0) { group.filters.remove(filterIndex); if (group.filters.isEmpty() && group != root.any) { root.groups.remove(groupIndex); fireTreeNodeRemoved(groupIndex, group); } else { fireTreeNodeRemoved(group, filterIndex, filter); groupIndex++; } } else { groupIndex++; } } } private void fireTreeNodeInserted(int groupIndex, Group group) { fireTreeNodesInserted(new TreeModelEvent(this, getPath(root), new int[]{groupIndex}, new Object[]{group})); } private void fireTreeNodeInserted(Group group, int filterIndex, Filter filter) { fireTreeNodesInserted(new TreeModelEvent(this, getPath(root, group), new int[]{filterIndex}, new Object[]{filter})); } private void fireTreeNodesInserted(TreeModelEvent treeModelEvent) { for (TreeModelListener listener : listeners) { listener.treeNodesInserted(treeModelEvent); } } private void fireTreeNodeRemoved(int groupIndex, Group group) { fireTreeNodesRemoved(new TreeModelEvent(this, getPath(root), new int[]{groupIndex}, new Object[]{group})); } private void fireTreeNodeRemoved(Group group, int filterIndex, Filter filter) { fireTreeNodesRemoved(new TreeModelEvent(this, getPath(root, group), new int[]{filterIndex}, new Object[]{filter})); } private void fireTreeNodesRemoved(TreeModelEvent treeModelEvent) { for (TreeModelListener listener : listeners) { listener.treeNodesRemoved(treeModelEvent); } } private void fireTreeNodesChanged(Filter filter) { for (Group group : root.groups) { for (Filter filter1 : group.filters) { if (filter1 == filter) { fireTreeNodeChanged(group, filter); } } } } private void fireTreeNodeChanged(Group group, Filter filter) { fireTreeNodesChanged(new TreeModelEvent(this, getPath(root, group, filter))); } private void fireTreeNodesChanged(TreeModelEvent treeModelEvent) { for (TreeModelListener listener : listeners) { listener.treeNodesChanged(treeModelEvent); } } public void fireTreeStructureChanged() { TreeModelEvent treeModelEvent = new TreeModelEvent(this, getPath(root)); for (TreeModelListener listener : listeners) { listener.treeStructureChanged(treeModelEvent); } } static Object[] getPath(Object ... path) { return path; } private void createTreeNodes() { root.any.filters.clear(); root.groups.clear(); List<Filter> filters = filterSet.getFilters(); for (Filter filter : filters) { insertTreeNodes(filter); } } public static class Root { final Group any = new Group("Any"); final List<Group> groups; private Root() { this.groups = new ArrayList<>(); } @Override public String toString() { return "Root"; } } public static class Group implements Comparable<Group> { final String name; final String nameLC; final List<Filter> filters; private Group(String name) { this.name = name; this.nameLC = name.toLowerCase(); filters = new ArrayList<>(); } @Override public String toString() { return name; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Group group = (Group) o; return name.equalsIgnoreCase(group.name); } @Override public int hashCode() { return nameLC.hashCode(); } @Override public int compareTo(Group group) { return name.compareToIgnoreCase(group.name); } } }
9,538
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CreateFilteredBandDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/CreateFilteredBandDialog.java
package org.esa.snap.rcp.imgfilter; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.imgfilter.model.Filter; import org.esa.snap.rcp.imgfilter.model.FilterSet; import org.esa.snap.rcp.imgfilter.model.StandardFilters; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.ModalDialog; import java.io.File; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; /** * The dialog that lets users select existing or define new image filters. * * @author Norman */ public class CreateFilteredBandDialog extends ModalDialog implements FilterSetForm.Listener { public static final String TITLE = "Create Filtered Band"; /*I18N*/ private final Product product; private final FilterSetsForm filterSetsForm; private final FilterSetFileStore filterSetStore; private List<FilterSet> userFilterSets; public CreateFilteredBandDialog(Product product, String sourceBandName, String helpId) { super(SnapApp.getDefault().getMainFrame(), TITLE, ModalDialog.ID_OK_CANCEL_HELP, helpId); this.product = product; FilterSet systemFilterSet = new FilterSet("System", false); systemFilterSet.addFilter("Detect Lines", StandardFilters.LINE_DETECTION_FILTERS); systemFilterSet.addFilter("Detect Gradients (Emboss)", StandardFilters.GRADIENT_DETECTION_FILTERS); systemFilterSet.addFilter("Smooth and Blurr", StandardFilters.SMOOTHING_FILTERS); systemFilterSet.addFilter("Sharpen", StandardFilters.SHARPENING_FILTERS); systemFilterSet.addFilter("Enhance Discontinuities", StandardFilters.LAPLACIAN_FILTERS); systemFilterSet.addFilter("Non-Linear Filters", StandardFilters.NON_LINEAR_FILTERS); systemFilterSet.addFilter("Morphological Filters", StandardFilters.MORPHOLOGICAL_FILTERS); filterSetStore = new FilterSetFileStore(getFiltersDir()); try { userFilterSets = filterSetStore.loadFilterSetModels(); } catch (IOException e) { userFilterSets = new ArrayList<>(); Dialogs.showError(TITLE, "Failed to load filter sets:\n" + e.getMessage()); SystemUtils.LOG.log(Level.WARNING, "Failed to load filter sets", e); } ArrayList<FilterSet> filterSets = new ArrayList<>(); filterSets.add(systemFilterSet); if (userFilterSets.isEmpty()) { userFilterSets.add(new FilterSet("User", true)); } filterSets.addAll(userFilterSets); filterSetsForm = new FilterSetsForm(sourceBandName, this, filterSetStore, new FilterWindow(getJDialog()), filterSets.toArray(new FilterSet[filterSets.size()])); setContent(filterSetsForm); } @Override protected void onOK() { super.onOK(); for (FilterSet userFilterSet : userFilterSets) { userFilterSet.setEditable(true); try { filterSetStore.storeFilterSetModel(userFilterSet); } catch (IOException e) { Dialogs.showError(TITLE, "Failed to store filter sets:\n" + e.getMessage()); } } } public DialogData getDialogData() { return new DialogData(filterSetsForm.getSelectedFilter(), filterSetsForm.getTargetBandName(), filterSetsForm.getIterationCount()); } @Override protected boolean verifyUserInput() { String message = null; final String targetBandName = filterSetsForm.getTargetBandName(); if (targetBandName.equals("")) { message = "Please enter a name for the new filtered band."; /*I18N*/ } else if (!ProductNode.isValidNodeName(targetBandName)) { message = MessageFormat.format("The band name ''{0}'' appears not to be valid.\n" + "Please choose a different band name.", targetBandName); /*I18N*/ } else if (product.containsBand(targetBandName)) { message = MessageFormat.format("The selected product already contains a band named ''{0}''.\n" + "Please choose a different band name.", targetBandName); /*I18N*/ } else if (filterSetsForm.getSelectedFilter() == null) { message = "Please select an image filter."; /*I18N*/ } if (message != null) { Dialogs.showError(TITLE, message); return false; } return true; } @Override public void filterSelected(FilterSet filterSet, Filter filter) { //System.out.println("filterModelSelected: filterModel = " + filter); } @Override public void filterAdded(FilterSet filterSet, Filter filter) { //System.out.println("filterModelAdded: filterModel = " + filter); } @Override public void filterRemoved(FilterSet filterSet, Filter filter) { //System.out.println("filterModelRemoved: filterModel = " + filter); } @Override public void filterChanged(FilterSet filterSet, Filter filter, String propertyName) { //System.out.println("filterModelChanged: filterModel = " + filter + ", propertyName = \"" + propertyName + "\""); } private File getFiltersDir() { return new File(SystemUtils.getAuxDataPath().toFile(), "image_filters"); } public static class DialogData { private final Filter filter; private final String bandName; private final int iterationCount; private DialogData(Filter filter, String bandName, int iterationCount) { this.filter = filter; this.bandName = bandName; this.iterationCount = iterationCount; } public String getBandName() { return bandName; } public Filter getFilter() { return filter; } public int getIterationCount() { return iterationCount; } } }
6,264
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilteredBandAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/FilteredBandAction.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.imgfilter; 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.ProductNode; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.window.OpenImageViewAction; import org.esa.snap.rcp.imgfilter.model.Filter; import org.esa.snap.ui.ModalDialog; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.ContextAwareAction; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.NbBundle; import org.openide.util.Utilities; import org.openide.util.WeakListeners; import javax.swing.AbstractAction; import javax.swing.Action; import java.awt.event.ActionEvent; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.*; @ActionID( category = "Tools", id = "FilteredBandAction" ) @ActionRegistration( displayName = "#CTL_FilteredBandAction_MenuText", popupText = "#CTL_FilteredBandAction_MenuText", lazy = false ) @ActionReferences({ @ActionReference(path = "Menu/Raster", position = 10), @ActionReference(path = "Context/Product/RasterDataNode", position = 40,separatorAfter = 45) }) @NbBundle.Messages({ "CTL_FilteredBandAction_MenuText=Filtered Band...", "CTL_FilteredBandAction_ShortDescription=Applies a filter to the currently selected band and adds it as a new band." }) public class FilteredBandAction extends AbstractAction implements LookupListener, ContextAwareAction { private Lookup lookup; private Lookup.Result<RasterDataNode> result; public FilteredBandAction() { this(Utilities.actionsGlobalContext()); } public FilteredBandAction(Lookup lookup){ super(Bundle.CTL_FilteredBandAction_MenuText()); this.lookup = lookup; result = lookup.lookupResult(RasterDataNode.class); result.addLookupListener(WeakListeners.create(LookupListener.class, this, result)); updateEnableState(this.lookup.lookup(RasterDataNode.class)); } @Override public Action createContextAwareInstance(Lookup actionContext) { return new FilteredBandAction(actionContext); } @Override public void resultChanged(LookupEvent ev) { updateEnableState(this.lookup.lookup(RasterDataNode.class)); } private void updateEnableState(RasterDataNode node) { //todo [multisize_products] compare scenerastertransform rather than size setEnabled(node != null); } @Override public void actionPerformed(ActionEvent e) { createFilteredBand(); } static GeneralFilterBand.OpType getOpType(Filter.Operation operation) { if (operation == Filter.Operation.OPEN) { return GeneralFilterBand.OpType.OPENING; } else if (operation == Filter.Operation.CLOSE) { return GeneralFilterBand.OpType.CLOSING; } else if (operation == Filter.Operation.ERODE) { return GeneralFilterBand.OpType.EROSION; } else if (operation == Filter.Operation.DILATE) { return GeneralFilterBand.OpType.DILATION; } else if (operation == Filter.Operation.MIN) { return GeneralFilterBand.OpType.MIN; } else if (operation == Filter.Operation.MAX) { return GeneralFilterBand.OpType.MAX; } else if (operation == Filter.Operation.MEAN) { return GeneralFilterBand.OpType.MEAN; } else if (operation == Filter.Operation.MEDIAN) { return GeneralFilterBand.OpType.MEDIAN; } else if (operation == Filter.Operation.STDDEV) { return GeneralFilterBand.OpType.STDDEV; } else { throw new IllegalArgumentException("illegal operation: " + operation); } } private void createFilteredBand() { RasterDataNode node = lookup.lookup(RasterDataNode.class); final CreateFilteredBandDialog.DialogData dialogData = promptForFilter(); if (dialogData == null) { return; } final FilterBand filterBand = getFilterBand(node, dialogData.getBandName(), dialogData.getFilter(), dialogData.getIterationCount()); OpenImageViewAction.openImageView(filterBand); } private static FilterBand getFilterBand(RasterDataNode sourceRaster, String bandName, Filter filter, int iterationCount) { FilterBand targetBand; Product targetProduct = sourceRaster.getProduct(); if (filter.getOperation() == Filter.Operation.CONVOLVE) { targetBand = new ConvolutionFilterBand(bandName, sourceRaster, getKernel(filter), iterationCount); if (sourceRaster instanceof Band) { ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand); } } else { GeneralFilterBand.OpType opType = getOpType(filter.getOperation()); targetBand = new GeneralFilterBand(bandName, sourceRaster, opType, getKernel(filter), iterationCount); if (sourceRaster instanceof Band) { ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand); } } targetBand.setDescription(String.format("Filter '%s' (=%s) applied to '%s'", filter.getName(), filter.getOperation(), sourceRaster.getName())); if (sourceRaster instanceof Band) { ProductUtils.copySpectralBandProperties((Band) sourceRaster, targetBand); } targetProduct.addBand(targetBand); ProductUtils.copyImageGeometry(sourceRaster, targetBand, false); targetBand.fireProductNodeDataChanged(); return targetBand; } private static Kernel getKernel(Filter filter) { return new Kernel(filter.getKernelWidth(), filter.getKernelHeight(), filter.getKernelOffsetX(), filter.getKernelOffsetY(), 1.0 / filter.getKernelQuotient(), filter.getKernelElements()); } private CreateFilteredBandDialog.DialogData promptForFilter() { final ProductNode selectedNode = SnapApp.getDefault().getSelectedProductNode(EXPLORER); final Product product = selectedNode.getProduct(); final CreateFilteredBandDialog dialog = new CreateFilteredBandDialog(product, selectedNode.getName(), "createFilteredBand"); if (dialog.show() == ModalDialog.ID_OK) { return dialog.getDialogData(); } return null; } }
7,687
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StandardFilters.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/model/StandardFilters.java
package org.esa.snap.rcp.imgfilter.model; /** * Created by Norman on 20.03.2014. */ public class StandardFilters { public static Filter[] LINE_DETECTION_FILTERS = { new Filter("Horizontal Edges", "he", 3, 3, new double[]{ -1, -1, -1, +2, +2, +2, -1, -1, -1 }, 1.0), new Filter("Vertical Edges", "ve", 3, 3, new double[]{ -1, +2, -1, -1, +2, -1, -1, +2, -1 }, 1.0), new Filter("Left Diagonal Edges", "lde", 3, 3, new double[]{ +2, -1, -1, -1, +2, -1, -1, -1, +2 }, 1.0), new Filter("Right Diagonal Edges", "rde", 3, 3, new double[]{ -1, -1, +2, -1, +2, -1, +2, -1, -1 }, 1.0), new Filter("Compass Edge Detector", "ced", 3, 3, new double[]{ -1, +1, +1, -1, -2, +1, -1, +1, +1, }, 1.0), new Filter("Diagonal Compass Edge Detector", "dced", 3, 3, new double[]{ +1, +1, +1, -1, -2, +1, -1, -1, +1, }, 1.0), new Filter("Roberts Cross North-West", "rcnw", 2, 2, new double[]{ +1, 0, 0, -1, }, 1.0), new Filter("Roberts Cross North-East", "rcne", 2, 2, new double[]{ 0, +1, -1, 0, }, 1.0), }; public static Filter[] GRADIENT_DETECTION_FILTERS = { new Filter("Sobel North", "sn", 3, 3, new double[]{ -1, -2, -1, +0, +0, +0, +1, +2, +1, }, 1.0), new Filter("Sobel South", "ss", 3, 3, new double[]{ +1, +2, +1, +0, +0, +0, -1, -2, -1, }, 1.0), new Filter("Sobel West", "sw", 3, 3, new double[]{ -1, 0, +1, -2, 0, +2, -1, 0, +1, }, 1.0), new Filter("Sobel East", "se", 3, 3, new double[]{ +1, 0, -1, +2, 0, -2, +1, 0, -1, }, 1.0), new Filter("Sobel North East", "sne", 3, 3, new double[]{ +0, -1, -2, +1, +0, -1, +2, +1, -0, }, 1.0), }; public static Filter[] SMOOTHING_FILTERS = { new Filter("Arithmetic Mean 3x3", "am3", 3, 3, new double[]{ +1, +1, +1, +1, +1, +1, +1, +1, +1, }, 9.0), new Filter("Arithmetic Mean 4x4", "am4", 4, 4, new double[]{ +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, }, 16.0), new Filter("Arithmetic Mean 5x5", "am5", 5, 5, new double[]{ +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, +1, }, 25.0), new Filter("Low-Pass 3x3", "lp3", 3, 3, new double[]{ +1, +2, +1, +2, +4, +2, +1, +2, +1, }, 16.0), new Filter("Low-Pass 5x5", "lp5", 5, 5, new double[]{ +1, +1, +1, +1, +1, +1, +4, +4, +4, +1, +1, +4, 12, +4, +1, +1, +4, +4, +4, +1, +1, +1, +1, +1, +1, }, 60.0), }; public static Filter[] SHARPENING_FILTERS = { new Filter("High-Pass 3x3 #1", "hp31", 3, 3, new double[]{ -1, -1, -1, -1, +9, -1, -1, -1, -1 }, 1.0), new Filter("High-Pass 3x3 #2", "hp32", 3, 3, new double[]{ +0, -1, +0, -1, +5, -1, +0, -1, +0 }, 1.0), new Filter("High-Pass 5x5", "hp5", 5, 5, new double[]{ +0, -1, -1, -1, +0, -1, +2, -4, +2, -1, -1, -4, 13, -4, -1, -1, +2, -4, +2, -1, +0, -1, -1, -1, +0, }, 1.0), }; public static Filter[] LAPLACIAN_FILTERS = { new Filter("Laplace 3x3 (a)", "lap3a", 3, 3, new double[]{ +0, -1, +0, -1, +4, -1, +0, -1, +0, }, 1.0), new Filter("Laplace 3x3 (b)", "lap3b", 3, 3, new double[]{ -1, -1, -1, -1, +8, -1, -1, -1, -1, }, 1.0), new Filter("Laplace 5x5 (a)", "lap5a", 5, 5, new double[]{ 0, 0, -1, 0, 0, 0, -1, -2, -1, 0, -1, -2, 16, -2, -1, 0, -1, -2, -1, 0, 0, 0, -1, 0, 0, }, 1.0), new Filter("Laplace 5x5 (b)", "lap5b", 5, 5, new double[]{ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 24, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }, 1.0), }; public static Filter[] NON_LINEAR_FILTERS = { new Filter("Minimum 3x3", "min3", Filter.Operation.MIN, 3, 3), new Filter("Minimum 5x5", "min5", Filter.Operation.MIN, 5, 5), new Filter("Minimum 7x7", "min7", Filter.Operation.MIN, 7, 7), new Filter("Maximum 3x3", "max3", Filter.Operation.MAX, 3, 3), new Filter("Maximum 5x5", "max5", Filter.Operation.MAX, 5, 5), new Filter("Maximum 7x7", "max7", Filter.Operation.MAX, 7, 7), new Filter("Mean 3x3", "mean3", Filter.Operation.MEAN, 3, 3), new Filter("Mean 5x5", "mean5", Filter.Operation.MEAN, 5, 5), new Filter("Mean 7x7", "mean7", Filter.Operation.MEAN, 7, 7), new Filter("Median 3x3", "median3", Filter.Operation.MEDIAN, 3, 3), new Filter("Median 5x5", "median5", Filter.Operation.MEDIAN, 5, 5), new Filter("Median 7x7", "median7", Filter.Operation.MEDIAN, 7, 7), new Filter("Standard Deviation 3x3", "stddev3", Filter.Operation.STDDEV, 3, 3), new Filter("Standard Deviation 5x5", "stddev5", Filter.Operation.STDDEV, 5, 5), new Filter("Standard Deviation 7x7", "stddev7", Filter.Operation.STDDEV, 7, 7), }; public static Filter[] MORPHOLOGICAL_FILTERS = { new Filter("Erosion 3x3", "erode3", Filter.Operation.ERODE, 3, 3), new Filter("Erosion 5x5", "erode5", Filter.Operation.ERODE, 5, 5), new Filter("Erosion 7x7", "erode7", Filter.Operation.ERODE, 7, 7), new Filter("Dilation 3x3", "dilate3", Filter.Operation.DILATE, 3, 3), new Filter("Dilation 5x5", "dilate5", Filter.Operation.DILATE, 5, 5), new Filter("Dilation 7x7", "dilate7", Filter.Operation.DILATE, 7, 7), new Filter("Opening 3x3", "open3", Filter.Operation.OPEN, 3, 3), new Filter("Opening 5x5", "open5", Filter.Operation.OPEN, 5, 5), new Filter("Opening 7x7", "open7", Filter.Operation.OPEN, 7, 7), new Filter("Closing 3x3", "close3", Filter.Operation.CLOSE, 3, 3), new Filter("Closing 5x5", "close5", Filter.Operation.CLOSE, 5, 5), new Filter("Closing 7x7", "close7", Filter.Operation.CLOSE, 7, 7), }; }
7,840
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Filter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/model/Filter.java
package org.esa.snap.rcp.imgfilter.model; import com.bc.ceres.core.Assert; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.SingleValueConverter; import java.awt.Dimension; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import static java.lang.Math.*; /** * @author Norman */ public class Filter { public enum Operation { CONVOLVE, MIN, MAX, MEAN, MEDIAN, STDDEV, ERODE, DILATE, OPEN, CLOSE } String name; String shorthand; Operation operation; boolean editable; HashSet<String> tags; double[] kernelElements; int kernelWidth; int kernelHeight; double kernelQuotient; int kernelOffsetX; int kernelOffsetY; transient List<Listener> listeners; private static int id = 1; public static Filter create(int kernelSize, String... tags) { return create(Operation.CONVOLVE, kernelSize, tags); } public static Filter create(Operation operation, int kernelSize, String... tags) { int id = Filter.id++; String name = System.getProperty("user.name") + id; String shorthand = "my" + id; return new Filter(name, shorthand, operation, kernelSize, kernelSize, null, 1.0, tags); } public Filter(String name, String shorthand, int kernelWidth, int kernelHeight, double[] kernelElements, double kernelQuotient, String... tags) { this(name, shorthand, Operation.CONVOLVE, kernelWidth, kernelHeight, kernelElements, kernelQuotient, tags); } public Filter(String name, String shorthand, Operation operation, int kernelWidth, int kernelHeight, String... tags) { this(name, shorthand, operation, kernelWidth, kernelHeight, null, 1.0, tags); } public Filter(String name, String shorthand, Operation operation, int kernelWidth, int kernelHeight, double[] kernelElements, double kernelQuotient, String... tags) { Assert.notNull(name, "name"); Assert.notNull(shorthand, "shorthand"); Assert.notNull(operation, "operation"); Assert.argument(kernelWidth > 0, "kernelWidth"); Assert.argument(kernelHeight > 0, "kernelHeight"); Assert.argument(Math.abs(kernelQuotient) > 0.0, "kernelQuotient"); this.name = name; this.shorthand = shorthand; this.operation = operation; this.tags = new HashSet<>(); this.tags.addAll(Arrays.asList(tags)); this.kernelWidth = kernelWidth; this.kernelHeight = kernelHeight; this.kernelQuotient = kernelQuotient; this.kernelOffsetX = kernelWidth / 2; this.kernelOffsetY = kernelHeight / 2; if (kernelElements != null) { Assert.argument(kernelElements.length == kernelWidth * kernelHeight, "kernelElements"); this.kernelElements = kernelElements.clone(); } else { this.kernelElements = new double[kernelWidth * kernelHeight]; if (operation == Operation.CONVOLVE) { this.kernelElements[kernelOffsetY * kernelWidth + kernelOffsetX] = 1.0; } else { Arrays.fill(this.kernelElements, 1.0); } } this.listeners = new ArrayList<>(); } public String getName() { return name; } public void setName(String name) { if (!name.equals(this.name)) { this.name = name; fireChange("name"); } } public String getShorthand() { return shorthand; } public void setShorthand(String shorthand) { if (!shorthand.equals(this.shorthand)) { this.shorthand = shorthand; fireChange("shorthand"); } } public Operation getOperation() { return operation; } public void setOperation(Operation operation) { if (operation != this.operation) { this.operation = operation; fireChange("operation"); } } public boolean isEditable() { return editable; } public void setEditable(boolean editable) { if (editable != this.editable) { this.editable = editable; fireChange("editable"); } } public Set<String> getTags() { return tags; } public void setTags(String... tags) { setTags(new HashSet<>(Arrays.asList(tags))); } private void setTags(HashSet<String> tags) { if (!tags.equals(this.tags)) { this.tags = tags; fireChange("tags"); } } public double getKernelElement(int i, int j) { return getKernelElement(j * kernelWidth + i); } public double getKernelElement(int index) { return kernelElements[index]; } public void setKernelElement(int i, int j, double value) { setKernelElement(j * kernelWidth + i, value); } public void setKernelElement(int index, double value) { if (value != kernelElements[index]) { kernelElements[index] = value; fireChange("kernelElements"); } } public double[] getKernelElements() { return kernelElements; } public void setKernelElements(double[] kernelElements) { if (!Arrays.equals(kernelElements, this.kernelElements)) { if (kernelElements.length != kernelWidth * kernelHeight) { throw new IllegalArgumentException("kernelElements.length != kernelWidth * kernelHeight"); } this.kernelElements = kernelElements; fireChange("kernelElements"); } } public int getKernelWidth() { return kernelWidth; } public int getKernelHeight() { return kernelHeight; } public void setKernelSize(int width, int height) { if (width != this.kernelWidth || height != this.kernelHeight) { int oldWidth = this.kernelWidth; int oldHeight = this.kernelHeight; double[] oldElements = kernelElements; double[] elements = new double[width * height]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { int oldI = (i * oldWidth) / width; int oldJ = (j * oldHeight) / height; int oldIndex = oldJ * oldWidth + oldI; int newIndex = j * width + i; elements[newIndex] = oldElements[oldIndex]; } } this.kernelWidth = width; this.kernelHeight = height; this.kernelOffsetX = width / 2; this.kernelOffsetY = height / 2; this.kernelElements = elements; fireChange("kernelSize"); } } public void fill(FillFunction fillFunction) { int w = kernelWidth; int h = kernelHeight; double x0 = -0.5 * (w - 1); double y0 = -0.5 * (h - 1); for (int j = 0; j < h; j++) { for (int i = 0; i < w; i++) { double x = x0 + i; double y = y0 + j; double v = fillFunction.compute(x, y, w, h); this.kernelElements[j * w + i] = v; } } fireChange("kernelElements"); } public void fillRectangle(double fillValue) { Arrays.fill(kernelElements, fillValue); fireChange("kernelElements"); } public void fillEllipse(final double fillValue) { fill(new FillFunction() { @Override public double compute(double x, double y, int w, int h) { double a = 0.5 * w; double b = 0.5 * h; double r = (x / a) * (x / a) + (y / b) * (y / b); return r < 1.0 ? fillValue : 0; } }); } public void fillGaussian() { fill(new FillFunction() { @Override public double compute(double x, double y, int w, int h) { double sigX = 0.2 * w; double sigY = 0.2 * h; double r = (x / sigX) * (x / sigX) + (y / sigY) * (y / sigY); double z = exp(-0.5 * r); return floor((round(2 * (1 + min(w, h)) * z))); } }); } public void fillLaplacian() { fill(new FillFunction() { @Override public double compute(double x, double y, int w, int h) { double sigX = 0.15 * w; double sigY = 0.15 * h; double r = (x / sigX) * (x / sigX) + (y / sigY) * (y / sigY); double z = (r - 1.0) * exp(-0.5 * r); return floor((round(2 * (1 + min(w, h)) * z))); } }); } public void fillRandom() { fill(new FillFunction() { @Override public double compute(double x, double y, int w, int h) { double range = min(w, h); return round(range * (2 * Math.random() - 1)); } }); } public double getKernelQuotient() { return kernelQuotient; } public void setKernelQuotient(double kernelQuotient) { if (kernelQuotient != this.kernelQuotient) { this.kernelQuotient = kernelQuotient; fireChange("kernelQuotient"); } } public void adjustKernelQuotient() { if (operation == Operation.CONVOLVE) { double sum = 0.0; for (double v : kernelElements) { sum += v; } setKernelQuotient(sum != 0 ? sum : 1.0); } else { setKernelQuotient(1.0); } } public int getKernelOffsetX() { return kernelOffsetX; } public int getKernelOffsetY() { return kernelOffsetY; } public void setKernelOffset(int kernelOffsetX, int kernelOffsetY) { if (kernelOffsetX != this.kernelOffsetX || kernelOffsetY != this.kernelOffsetY) { this.kernelOffsetX = kernelOffsetX; this.kernelOffsetY = kernelOffsetY; fireChange("kernelOffset"); } } public String getKernelElementsAsText() { return formatKernelElements(kernelElements, new Dimension(kernelWidth, kernelHeight), "\t"); } public void setKernelElementsFromText(String text) { Dimension dim = new Dimension(); double[] kernelElements = parseKernelElementsFromText(text, dim); if (kernelElements != null) { setKernelSize(dim.width, dim.height); setKernelElements(kernelElements); } } protected static double[] parseKernelElementsFromText(String text, Dimension dim) { String[][] tokens = tokenizeKernelElements(text); if (tokens == null) { return null; } int height = tokens.length; int width = tokens[0].length; double[] kernelElements = new double[width * height]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { try { kernelElements[j * width + i] = Double.parseDouble(tokens[j][i]); } catch (NumberFormatException e) { return null; } } } if (dim != null) { dim.width = width; dim.height = height; } return kernelElements; } public static String[][] tokenizeKernelElements(String text) { String[] lines = text.split("\n"); int height = lines.length; int width = -1; String[][] strings = new String[height][]; for (int j = 0; j < height; j++) { String line = lines[j]; String[] cells = line.split(",|;|\\s+"); if (width == -1) { width = cells.length; } else if (width != cells.length) { return null; } strings[j] = cells; } return strings; } public static String formatKernelElements(double[] kernelElements, Dimension dim, String sep) { StringBuilder text = new StringBuilder(); for (int j = 0; j < dim.height; j++) { for (int i = 0; i < dim.width; i++) { if (i != 0) { text.append(sep); } double v = kernelElements[j * dim.width + i]; if (v == (int) v) { text.append((int) v); } else { text.append(v); } } if (j < dim.height - 1) { text.append('\n'); } } return text.toString(); } public static XStream createXStream() { final XStream xStream = new XStream(); xStream.setClassLoader(Filter.class.getClassLoader()); xStream.alias("filter", Filter.class); xStream.registerLocalConverter(Filter.class, "kernelElements", new SingleValueConverter() { @Override public String toString(Object o) { double[] o1 = (double[]) o; // todo - find out how to obtain width, height return Filter.formatKernelElements(o1, new Dimension(o1.length, 1), ","); } @Override public Object fromString(String s) { return Filter.parseKernelElementsFromText(s, null); } @Override public boolean canConvert(Class aClass) { return aClass.equals(double[].class); } }); return xStream; } @SuppressWarnings("UnusedDeclaration") private Object readResolve() { if (tags == null) { tags = new HashSet<>(); } if (listeners == null) { listeners = new ArrayList<>(); } if (kernelQuotient == 0.0) { kernelQuotient = 1.0; } return this; } @Override public String toString() { return name; } public static boolean isKernelDataText(String text) { String[][] strings = tokenizeKernelElements(text); return strings != null; } public void fireChange(String propertyName) { Listener[] listeners = this.listeners.toArray(new Listener[this.listeners.size()]); for (Listener listener : listeners) { listener.filterChanged(this, propertyName); } } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public interface Listener { void filterChanged(Filter filter, String propertyName); } interface FillFunction { double compute(double x, double y, int w, int h); } }
14,938
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterSetStore.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/model/FilterSetStore.java
package org.esa.snap.rcp.imgfilter.model; import java.io.IOException; /** * @author Norman */ public interface FilterSetStore { void storeFilterSetModel(FilterSet filterSet) throws IOException; }
204
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FilterSet.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/imgfilter/model/FilterSet.java
package org.esa.snap.rcp.imgfilter.model; import com.thoughtworks.xstream.XStream; import java.util.ArrayList; import java.util.List; /** * @author Norman */ public class FilterSet implements Filter.Listener { String name; boolean editable; ArrayList<Filter> filters; transient List<Listener> listeners; public FilterSet() { this("", true); } public FilterSet(String name, boolean editable) { this.name = name; this.editable = editable; filters = new ArrayList<>(); listeners = new ArrayList<>(); } public String getName() { return name; } public boolean isEditable() { return editable; } public void setEditable(boolean editable) { this.editable = editable; } public int getFilterCount() { return filters.size(); } public Filter getFilter(int index) { return filters.get(index); } public List<Filter> getFilters() { return filters; } public boolean containsFilter(Filter filter) { return filters.contains(filter); } public int getFilterIndex(Filter filter) { return filters.indexOf(filter); } public void addFilter(String tag, Filter... filters) { for (Filter filter : filters) { filter.getTags().add(tag); addFilter(filter); } } public void addFilter(Filter filter) { filters.add(filter); filter.addListener(this); fireFilterAdded(filter); } public void removeFilter(Filter filter) { if (filters.remove(filter)) { filter.removeListener(this); fireFilterModelRemoved(filter); } } public static XStream createXStream() { final XStream xStream = Filter.createXStream(); xStream.alias("filterSet", FilterSet.class); return xStream; } @SuppressWarnings("UnusedDeclaration") private Object readResolve() { if (listeners == null) { listeners = new ArrayList<>(); } if (filters == null) { filters = new ArrayList<>(); } for (Filter filter : filters) { filter.removeListener(this); filter.addListener(this); } return this; } @Override public void filterChanged(Filter filter, String propertyName) { fireFilterChanged(filter, propertyName); } void fireFilterChanged(Filter filter, String propertyName) { for (Listener listener : listeners) { listener.filterChanged(this, filter, propertyName); } } void fireFilterAdded(Filter filter) { for (Listener listener : listeners) { listener.filterAdded(this, filter); } } void fireFilterModelRemoved(Filter filter) { for (Listener listener : listeners) { listener.filterRemoved(this, filter); } } public void addListener(Listener listener) { listeners.add(listener); } public void removeListener(Listener listener) { listeners.remove(listener); } public interface Listener { void filterAdded(FilterSet filterSet, Filter filter); void filterRemoved(FilterSet filterSet, Filter filter); void filterChanged(FilterSet filterSet, Filter filter, String propertyName); } }
3,398
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageInfoEditorModel1B.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ImageInfoEditorModel1B.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.colormanip; import org.esa.snap.core.datamodel.ImageInfo; import org.esa.snap.ui.DefaultImageInfoEditorModel; /** * todo - add API doc * * @author Norman Fomferra * @version $Revision$ $Date$ * @since BEAM 4.2 */ class ImageInfoEditorModel1B extends DefaultImageInfoEditorModel { ImageInfoEditorModel1B(ImageInfo imageInfo) { super(imageInfo); } }
1,120
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Continuous1BandBasicForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/Continuous1BandBasicForm.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.colormanip; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.runtime.internal.Platform; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.datamodel.ColorManipulationDefaults; import org.esa.snap.core.datamodel.ColorPaletteDef; import org.esa.snap.core.datamodel.ColorSchemeInfo; import org.esa.snap.core.datamodel.ImageInfo; 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.util.ProductUtils; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.math.Histogram; import org.esa.snap.core.util.math.Range; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.text.NumberFormatter; import java.awt.BorderLayout; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.text.DecimalFormat; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_DEFAULT; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_KEY; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_DEFAULT; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_KEY; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_LOG_DEFAULT; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_LOG_KEY; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_DEFAULT; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_KEY; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_DEFAULT; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_KEY; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.TOOLNAME_COLOR_MANIPULATION; /** * @author Brockmann Consult * @author Daniel Knowles (NASA) * @author Bing Yang (NASA) */ // OCT 2019 - Knowles / Yang // - Added DocumentListener to minField and maxField to make sure that the values are being updated. // Previously the values would only be updated if the user hit enter and a lose focus event would not // trigger a value update. // - Fixes log scaling bug where the log scaling was not affecting the palette values. This was achieved // by tracking the source and target log scaling and passing this information to the method // setColorPaletteDef() in the class ImageInfo. // - Added numerical checks on the minField and maxField. // // NOV 2019 - Knowles / Yang // - Added color scheme logic // - Added capability to reverse the color palette // - Added capabiltiy to load exact values of the cpd file within any mathematical interpolation applied. // DEC 2019 - Knowles / Yang // - Added capability to load scheme with data range values // - An empty min or empty max field within the schemes text will result in use of statistical min/max // JAN 2020 - Knowles // - Added notification to user in the GUI when a scheme has been used in a non-nominal state (if the preferences altered) // - Implemented ColorSchemeManager // - Added verbose options to the scheme selector // - Added call to store and retrieve color scheme selector settings from ImageInfo // FEB 2020 - Knowles // - Added functionality to select 'none' from the scheme selector // - Color scheme will be red if it is a duplicate scheme // - Popup window will notify a user why a color scheme is disabled (missing cpd file, etc.) // - Modifications to how min and max textfield listen to user input to enable a warning prompt for bad entries // - Reduced some event handling by checking if components have changed before updating them public class Continuous1BandBasicForm implements ColorManipulationChildForm { private final ColorManipulationForm parentForm; private final JPanel contentPanel; private final AbstractButton logDisplayButton; private final JLabel schemeInfoLabel; private final MoreOptionsForm moreOptionsForm; private final ColorPaletteChooser colorPaletteChooser; private final JFormattedTextField minField; private final JFormattedTextField maxField; private final JButton fromFile; private final JButton fromData; private final DiscreteCheckBox discreteCheckBox; private final JCheckBox loadWithCPDFileValuesCheckBox; private final ColorSchemeManager colorSchemeManager; private final JLabel colorSchemeJLabel; private final JButton paletteInversionButton; final Boolean[] minTextFieldListenerEnabled = {Boolean.TRUE}; final Boolean[] maxTextFieldListenerEnabled = {Boolean.TRUE}; final Boolean[] logButtonListenerEnabled = {true}; final Boolean[] basicSwitcherIsActive; PropertyMap configuration = null; private enum RangeKey {FromCpdFile, FromData, FromMinField, FromMaxField, FromPaletteChooser, FromLogButton, InvertPalette, Dummy} private boolean shouldFireChooserEvent; private boolean hidden = false; Continuous1BandBasicForm(final ColorManipulationForm parentForm, final Boolean[] basicSwitcherIsActive) { ColorPaletteManager.getDefault().loadAvailableColorPalettes(parentForm.getIODir().toFile()); this.parentForm = parentForm; this.basicSwitcherIsActive = basicSwitcherIsActive; if (parentForm.getFormModel().getProductSceneView() != null && parentForm.getFormModel().getProductSceneView().getSceneImage() != null) { configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); } colorSchemeJLabel = new JLabel(""); schemeInfoLabel = new JLabel(""); colorSchemeManager = ColorSchemeManager.getDefault(); loadWithCPDFileValuesCheckBox = new JCheckBox("Load exact values", false); loadWithCPDFileValuesCheckBox.setToolTipText("When loading a new cpd file, use its actual values and overwrite user min/max values"); paletteInversionButton = new JButton("Reverse"); paletteInversionButton.setToolTipText("Reverse (invert) palette"); /*I18N*/ paletteInversionButton.addActionListener(e -> applyChanges(RangeKey.InvertPalette)); paletteInversionButton.setEnabled(true); paletteInversionButton.setFocusable(false); colorPaletteChooser = new ColorPaletteChooser(); colorPaletteChooser.setFocusable(false); minField = getNumberTextField(0.0000001); maxField = getNumberTextField(1.0000001); fromFile = new JButton("From Palette"); fromData = new JButton("From Data"); final TableLayout layout = new TableLayout(); layout.setTableWeightX(1.0); layout.setTableWeightY(1.0); layout.setTablePadding(2, 2); layout.setTableFill(TableLayout.Fill.HORIZONTAL); layout.setTableAnchor(TableLayout.Anchor.NORTH); layout.setCellPadding(0, 0, new Insets(8, 2, 2, 2)); layout.setCellPadding(1, 0, new Insets(8, 2, 2, 2)); layout.setCellPadding(2, 0, new Insets(8, 2, 2, 2)); layout.setCellPadding(3, 0, new Insets(13, 2, 5, 2)); final JPanel editorPanel = new JPanel(layout); JPanel schemePanel = getSchemePanel("Scheme"); editorPanel.add(schemePanel); JPanel palettePanel = getPalettePanel("Palette"); editorPanel.add(palettePanel); JPanel rangePanel = getRangePanel("Range"); editorPanel.add(rangePanel); shouldFireChooserEvent = false; colorPaletteChooser.addActionListener(createListener(RangeKey.FromPaletteChooser)); // maxField.getDocument().addDocumentListener(new DocumentListener() { // @Override // public void insertUpdate(DocumentEvent e) { // if (shouldFireChooserEvent) { // ColorManipulationDefaults.debug("Inside maxField listener"); // assist(); // } // } // // private void assist() { // Runnable doAssist = new Runnable() { // @Override // public void run() { // handleMaxTextfield(); // } // }; // SwingUtilities.invokeLater(doAssist); // } // // @Override // public void removeUpdate(DocumentEvent e) {} // // @Override // public void changedUpdate(DocumentEvent e) {} // }); // minField.getDocument().addDocumentListener(new DocumentListener() { // @Override // public void insertUpdate(DocumentEvent e) { // if (shouldFireChooserEvent) { // ColorManipulationDefaults.debug("Inside minField listener"); // assist(); // } // } // // private void assist() { // Runnable doAssist = new Runnable() { // @Override // public void run() { // handleMinTextfield(); // } // }; // SwingUtilities.invokeLater(doAssist); // } // // @Override // public void removeUpdate(DocumentEvent e) {} // // @Override // public void changedUpdate(DocumentEvent e) {} // }); minField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { ColorManipulationDefaults.debug("minField: FocusListener: focusGained"); } @Override public void focusLost(FocusEvent e) { ColorManipulationDefaults.debug("minField: FocusListener: focusLost"); handleMinTextfield(); } }); minField.addActionListener(e -> { ColorManipulationDefaults.debug("minField: ActionListener: actionPerformed"); handleMinTextfield(); }); maxField.addActionListener(e -> { ColorManipulationDefaults.debug("maxField: ActionListener: actionPerformed"); handleMaxTextfield(); }); maxField.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { ColorManipulationDefaults.debug("maxField: FocusListener: focusGained"); } @Override public void focusLost(FocusEvent e) { ColorManipulationDefaults.debug("maxField: FocusListener: focusLost"); handleMaxTextfield(); } }); fromFile.addActionListener(e -> { ColorManipulationDefaults.debug("Inside fromFile.addActionListener"); if (shouldFireChooserEvent) { ColorManipulationDefaults.debug("Inside fromFile.addActionListener 2"); applyChanges(RangeKey.FromCpdFile); } }); fromData.addActionListener(e -> { ColorManipulationDefaults.debug("Inside fromData.addActionListener"); if (shouldFireChooserEvent) { ColorManipulationDefaults.debug("Inside fromData.addActionListener 2"); applyChanges(RangeKey.FromData); } }); fromData.setFocusable(false); fromFile.setFocusable(false); fromData.setToolTipText("Set range from data"); fromFile.setToolTipText("Set range from palette file"); contentPanel = new JPanel(new BorderLayout()); contentPanel.add(editorPanel, BorderLayout.NORTH); moreOptionsForm = new MoreOptionsForm(this, parentForm.getFormModel().canUseHistogramMatching()); discreteCheckBox = new DiscreteCheckBox(parentForm); moreOptionsForm.addRow(discreteCheckBox); parentForm.getFormModel().modifyMoreOptionsForm(moreOptionsForm); logDisplayButton = LogDisplay.createButton(); logDisplayButton.addActionListener(e -> { if (shouldFireChooserEvent) { if (logButtonListenerEnabled[0]) { logButtonListenerEnabled[0] = false; applyChanges(RangeKey.FromLogButton); logButtonListenerEnabled[0] = true; } } }); colorSchemeManager.getjComboBox().addActionListener(e -> { if (colorSchemeManager.isjComboBoxShouldFire()) { colorSchemeManager.setjComboBoxShouldFire(false); ColorManipulationDefaults.debug("Inside standardColorPaletteSchemes listener"); handleColorSchemeSelector(); colorSchemeManager.setjComboBoxShouldFire(true); } }); shouldFireChooserEvent = true; } private boolean testMinMaxAgainstCurrentLog(double min, double max) { boolean valid = true; final ImageInfo currentInfo = parentForm.getFormModel().getModifiedImageInfo(); boolean logScaled = currentInfo.isLogScaled(); if (logScaled && min <= 0) { valid = false; ColorUtils.showErrorDialog("ERROR!: " + TOOLNAME_COLOR_MANIPULATION + ": \nMin field cannot be set to less than or equal to zero with log scaling\""); } else if (logScaled && max <= 0) { valid = false; ColorUtils.showErrorDialog("ERROR!: " + TOOLNAME_COLOR_MANIPULATION + ": \nMax field cannot be set to less than or equal to zero with log scaling\""); } return valid; } private void handleMaxTextfield() { // This is a final action and we don't want cursor enabled anymore and we don't want cursor to // auto-move into the other textfield. So temporarily turn it off here setComponentsActive(false); if (maxTextFieldListenerEnabled[0] && !basicSwitcherIsActive[0]) { maxTextFieldListenerEnabled[0] = false; // if (!inCompleteNumber(maxField.getText())) { // applyChanges(RangeKey.FromMaxField); // } applyChanges(RangeKey.FromMaxField); maxTextFieldListenerEnabled[0] = true; } // this is a final action ... so if it failed to update then restore to image value final ImageInfo currentInfo = parentForm.getFormModel().getModifiedImageInfo(); maxField.setValue(currentInfo.getColorPaletteDef().getMaxDisplaySample()); // Turn back to editable setComponentsActive(true); } private void handleMinTextfield() { // This is a final action and we don't want cursor enabled anymore and we don't want cursor to // // auto-move into the other textfield. So temporarily turn it off here ColorManipulationDefaults.debug("Inside handleMinTextfield 0"); setComponentsActive(false); if (minTextFieldListenerEnabled[0] && !basicSwitcherIsActive[0]) { ColorManipulationDefaults.debug("Inside handleMinTextfield 1"); minTextFieldListenerEnabled[0] = false; // if (!inCompleteNumber(minField.getText())) { // applyChanges(RangeKey.FromMinField); // } applyChanges(RangeKey.FromMinField); minTextFieldListenerEnabled[0] = true; } ColorManipulationDefaults.debug("Inside handleMinTextfield 0"); // this is a final action ... so if it failed to update then restore to image value final ImageInfo currentInfo = parentForm.getFormModel().getModifiedImageInfo(); minField.setValue(currentInfo.getColorPaletteDef().getMinDisplaySample()); // Turn back to editable setComponentsActive(true); ColorManipulationDefaults.debug("Inside handleMinTextfield 0"); } private void setComponentsActive(boolean active) { ColorManipulationDefaults.debug("setComponentsActive"); // needs to be turned off in reverse order of auto-sequence in the form fromData.setEnabled(active); fromFile.setEnabled(active); maxField.setEditable(active); maxField.setEnabled(active); maxField.setFocusable(active); minField.setFocusable(active); minField.setEditable(active); minField.setEnabled(active); } @Override public Component getContentPanel() { return contentPanel; } @Override public ColorManipulationForm getParentForm() { return parentForm; } @Override public void handleFormShown(ColorFormModel formModel) { hidden = false; updateFormModel(formModel); } @Override public void handleFormHidden(ColorFormModel formModel) { hidden = true; } @Override public void updateFormModel(ColorFormModel formModel) { if (!hidden) { ColorPaletteManager.getDefault().loadAvailableColorPalettes(parentForm.getIODir().toFile()); colorPaletteChooser.reloadPalettes(); } final ImageInfo imageInfo = formModel.getOriginalImageInfo(); final ColorPaletteDef cpd = imageInfo.getColorPaletteDef(); final boolean logScaled = imageInfo.isLogScaled(); final boolean discrete = cpd.isDiscrete(); colorPaletteChooser.setLog10Display(logScaled); colorPaletteChooser.setDiscreteDisplay(discrete); shouldFireChooserEvent = false; colorPaletteChooser.setSelectedColorPaletteDefinition(cpd); discreteCheckBox.setDiscreteColorsMode(discrete); if (logScaled != logDisplayButton.isSelected()) { logDisplayButton.setSelected(logScaled); } PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); boolean schemeApply = configuration.getPropertyBool(PROPERTY_SCHEME_AUTO_APPLY_KEY, PROPERTY_SCHEME_AUTO_APPLY_DEFAULT); String schemeLogScaling = configuration.getPropertyString(PROPERTY_SCHEME_LOG_KEY, PROPERTY_SCHEME_LOG_DEFAULT); String schemeRange = configuration.getPropertyString(PROPERTY_SCHEME_RANGE_KEY, PROPERTY_SCHEME_RANGE_DEFAULT); String schemeCpd = configuration.getPropertyString(PROPERTY_SCHEME_PALETTE_KEY, PROPERTY_SCHEME_PALETTE_DEFAULT); schemeInfoLabel.setText("<html>*Modified scheme"); String optionsLocation = getOptionsLocation(); schemeInfoLabel.setToolTipText("Not using exact scheme default: see " + optionsLocation); boolean visible = false; ColorSchemeManager colorPaletteSchemes = ColorSchemeManager.getDefault(); colorPaletteSchemes.setSelected(imageInfo.getColorSchemeInfo()); if (colorPaletteSchemes.isSchemeSet() && schemeApply && (!PROPERTY_SCHEME_PALETTE_DEFAULT.equals(schemeCpd) || !PROPERTY_SCHEME_RANGE_DEFAULT.equals(schemeRange) || !PROPERTY_SCHEME_LOG_DEFAULT.equals(schemeLogScaling)) ) { visible = true; } schemeInfoLabel.setVisible(visible); colorPaletteSchemes.checkPreferences(configuration); parentForm.revalidateToolViewPaneControl(); if (cpd.getMinDisplaySample() != (Double) minField.getValue()) { minField.setValue(cpd.getMinDisplaySample()); } if (cpd.getMaxDisplaySample() != (Double) maxField.getValue()) { maxField.setValue(cpd.getMaxDisplaySample()); } shouldFireChooserEvent = true; } // this should get a common place. Maybe in Platform? Not sure, so it stays here for now. private String getOptionsLocation() { String optionsLocation = "Tools/Options"; final Platform currentPlatform = Platform.getCurrentPlatform(); if (currentPlatform != null && currentPlatform.getId() == Platform.ID.macosx) { optionsLocation = "App Menu/Preferences"; } return optionsLocation; } @Override public void resetFormModel(ColorFormModel formModel) { updateFormModel(formModel); parentForm.revalidateToolViewPaneControl(); } @Override public void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster) { if (event.getPropertyName().equals(RasterDataNode.PROPERTY_NAME_STX)) { updateFormModel(parentForm.getFormModel()); } } @Override public RasterDataNode[] getRasters() { return parentForm.getFormModel().getRasters(); } @Override public MoreOptionsForm getMoreOptionsForm() { return moreOptionsForm; } @Override public AbstractButton[] getToolButtons() { return new AbstractButton[]{ logDisplayButton, }; } private ActionListener createListener(final RangeKey key) { return e -> applyChanges(key); } private JFormattedTextField getNumberTextField(double value) { final NumberFormatter formatter = new NumberFormatter(new DecimalFormat("0.0############")); formatter.setValueClass(Double.class); // to ensure that double values are returned final JFormattedTextField numberField = new JFormattedTextField(formatter); numberField.setValue(value); numberField.setPreferredSize(numberField.getPreferredSize()); return numberField; } private void applyChanges(RangeKey key) { ColorManipulationDefaults.debug("applyChanges: Start: key=" + key.toString()); if (shouldFireChooserEvent) { // The 'valid' variable is used to determine whether the component entries are valid. For the cases // where the component entry is not valid, no update will occur, the user will be prompted, and the // offending component will be reset to the last valid value boolean valid = true; // The 'valueChange' variable is used when the GUI components match the current image info and hence no // change is needed. Excess events are undesirable here as the scheme selector will reset to "none" // for any component change event. boolean valueChange = false; final ColorPaletteDef selectedCPD = colorPaletteChooser.getSelectedColorPaletteDefinition(); final ImageInfo currentInfo = parentForm.getFormModel().getModifiedImageInfo(); final ColorPaletteDef currentCPD = currentInfo.getColorPaletteDef(); final ColorPaletteDef selectedCpdDeepCopy = selectedCPD.createDeepCopy(); selectedCpdDeepCopy.setDiscrete(currentCPD.isDiscrete()); // Set source and target values to be the same as the current values by default ColorPaletteDef sourceCpd = currentCPD; boolean sourceLogScaled = currentInfo.isLogScaled(); double targetMin = currentCPD.getMinDisplaySample(); double targetMax = currentCPD.getMaxDisplaySample(); boolean targetLogScaled = currentInfo.isLogScaled(); // Set 'targetAutoDistribute' = true as default because only the case of loading a new palette // with exact values will need false boolean targetAutoDistribute = true; // If retaining user textfield min/max make sure field is being passed along as it could be in a // lingering edit state. Treat log button click separately as the reset should be on the log button. ColorManipulationDefaults.debug("applyChanges: 2: key=" + key); if (key == RangeKey.FromCpdFile || key == RangeKey.FromData) { // restore textfield to match image. It will not be used and will be set later accordingly ColorManipulationDefaults.debug("applyChanges: targetMin=" + targetMin); ColorManipulationDefaults.debug("applyChanges: currentInfo.getColorPaletteDef().getMinDisplaySample=" + currentInfo.getColorPaletteDef().getMinDisplaySample()); ColorManipulationDefaults.debug("applyChanges: targetMax=" + targetMax); ColorManipulationDefaults.debug("applyChanges: currentInfo.getColorPaletteDef().getMaxDisplaySample=" + currentInfo.getColorPaletteDef().getMaxDisplaySample()); shouldFireChooserEvent = false; minField.setValue(targetMin); // minField.setText(Double.toString(targetMin)); maxField.setValue(targetMax); // maxField.setText(Double.toString(targetMax)); shouldFireChooserEvent = true; ColorManipulationDefaults.debug("applyChanges: targetMin=" + targetMin); ColorManipulationDefaults.debug("applyChanges: currentInfo.getColorPaletteDef().getMinDisplaySample=" + currentInfo.getColorPaletteDef().getMinDisplaySample()); ColorManipulationDefaults.debug("applyChanges: targetMax=" + targetMax); ColorManipulationDefaults.debug("applyChanges: currentInfo.getColorPaletteDef().getMaxDisplaySample=" + currentInfo.getColorPaletteDef().getMaxDisplaySample()); } else { String dialogErrorMsg = null; // textfield will be used and it could be in lingering state boolean minMaxValid = true; try { targetMin = getMinFieldValue(); } catch (NumberFormatException e) { minMaxValid = false; dialogErrorMsg = e.getMessage(); } if (minMaxValid) { try { targetMax = getMaxFieldValue(); } catch (NumberFormatException e) { minMaxValid = false; dialogErrorMsg = e.getMessage(); } } if (minMaxValid) { minMaxValid = checkMinMax(targetMin, targetMax); if (!minMaxValid) { dialogErrorMsg = "Max must be greater than Min. Resetting value."; } } if (minMaxValid) { //noinspection StatementWithEmptyBody if (key == RangeKey.FromLogButton) { // Accept textfields and deal with log case later } else { // leave log alone and reset textfields if log conflict minMaxValid = checkLogScalingAgainstMinMax(targetMin, targetMax, logDisplayButton.isSelected(), false); if (!minMaxValid) { dialogErrorMsg = "Min/Max cannot be non-positive value. Resetting Min/Max"; } } } ColorManipulationDefaults.debug("applyChanges: 3: key=" + key); if (!minMaxValid) { // restore to a valid setting targetMin = currentInfo.getColorPaletteDef().getMinDisplaySample(); targetMax = currentInfo.getColorPaletteDef().getMaxDisplaySample(); shouldFireChooserEvent = false; minField.setValue(targetMin); maxField.setValue(targetMax); shouldFireChooserEvent = true; if (dialogErrorMsg == null || dialogErrorMsg.length() <= 1) { // the dialogErrorMsg should have already been set ... but just in case set it here. dialogErrorMsg = "Min/Max formatting error. Resetting Min/Max"; } ColorUtils.showErrorDialog("ERROR!: " + TOOLNAME_COLOR_MANIPULATION + ": " + dialogErrorMsg); } ColorManipulationDefaults.debug("applyChanges: targetMin=" + targetMin); ColorManipulationDefaults.debug("applyChanges: currentInfo.getColorPaletteDef().getMinDisplaySample=" + currentInfo.getColorPaletteDef().getMinDisplaySample()); ColorManipulationDefaults.debug("applyChanges: targetMax=" + targetMax); ColorManipulationDefaults.debug("applyChanges: currentInfo.getColorPaletteDef().getMaxDisplaySample=" + currentInfo.getColorPaletteDef().getMaxDisplaySample()); valueChange = targetMin != currentInfo.getColorPaletteDef().getMinDisplaySample() || targetMax != currentInfo.getColorPaletteDef().getMaxDisplaySample(); } ColorManipulationDefaults.debug("valueChange: " + valueChange); ColorManipulationDefaults.debug("applyChanges: 4: key=" + key); // at this point textfields should be set to a desired valid value. double tmpMin; double tmpMax; switch (key) { case FromCpdFile: ColorManipulationDefaults.debug("Inside FromCpdFile"); // Updates targetMin and targetMax tmpMin = currentCPD.getSourceFileMin(); tmpMax = currentCPD.getSourceFileMax(); valid = testMinMaxAgainstCurrentLog(tmpMin, tmpMax); if (valid) { targetMin = tmpMin; targetMax = tmpMax; valueChange = targetMin != currentCPD.getMinDisplaySample() || targetMax != currentCPD.getMaxDisplaySample(); } break; case FromData: ColorManipulationDefaults.debug("Inside FromData"); // Updates targetMin and targetMax final Stx stx = parentForm.getStx(parentForm.getFormModel().getRaster()); if (stx != null) { final Histogram histogram = new Histogram(stx.getHistogramBins(), stx.getMinimum(), stx.getMaximum()); PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); double percentile = configuration.getPropertyDouble(PROPERTY_RANGE_PERCENTILE_KEY, PROPERTY_RANGE_PERCENTILE_DEFAULT); Range autoStretchRange = histogram.findRangeForPercent(percentile); if (autoStretchRange != null) { tmpMin = autoStretchRange.getMin(); tmpMax = autoStretchRange.getMax(); valid = testMinMaxAgainstCurrentLog(tmpMin, tmpMax); if (valid) { targetMin = tmpMin; targetMax = tmpMax; valueChange = targetMin != currentCPD.getMinDisplaySample() || targetMax != currentCPD.getMaxDisplaySample(); } } else { valid = false; } } else { valid = false; } break; case FromMinField: ColorManipulationDefaults.debug("Inside FromMinField"); // dealt with earlier break; case FromMaxField: ColorManipulationDefaults.debug("Inside FromMaxField"); // dealt with earlier break; case FromLogButton: ColorManipulationDefaults.debug("Inside FromLogButton"); if (logDisplayButton.isSelected()) { valid = checkLogScalingAgainstMinMax(targetMin, targetMax, logDisplayButton.isSelected(), false); if (valid) { colorPaletteChooser.setLog10Display(targetLogScaled); } else { // restore to a valid setting shouldFireChooserEvent = false; logDisplayButton.setSelected(false); shouldFireChooserEvent = true; String errorMessage = "Cannot set to log mode with a non-positive Min/Max"; ColorUtils.showErrorDialog("ERROR!: " + TOOLNAME_COLOR_MANIPULATION + ": \n" + errorMessage); } } targetLogScaled = logDisplayButton.isSelected(); if (targetLogScaled == currentInfo.isLogScaled()) { valueChange = false; } // todo Setting this to true just in case textfields were updated valueChange = true; break; case InvertPalette: ColorManipulationDefaults.debug("Inside InvertPalette"); valueChange = true; break; case FromPaletteChooser: ColorManipulationDefaults.debug("Inside FromPaletteChooser"); // the source needs to reflect the palette instead of the current imageInfo sourceLogScaled = selectedCPD.isLogScaled(); sourceCpd = selectedCpdDeepCopy; if (loadWithCPDFileValuesCheckBox.isSelected()) { targetLogScaled = selectedCPD.isLogScaled(); targetMin = selectedCPD.getSourceFileMin(); targetMax = selectedCPD.getSourceFileMax(); targetAutoDistribute = false; valid = checkLogScalingAgainstMinMax(targetMin, targetMax, targetLogScaled, false); if (valid) { valueChange = true; } else { String errorMessage = "Cannot load because CPD contains non-positive Min/Max contains with log mode set."; ColorUtils.showErrorDialog("ERROR!: " + TOOLNAME_COLOR_MANIPULATION + ": \n" + errorMessage); } } else { valueChange = true; } break; default: // this will not be reached } ColorManipulationDefaults.debug("valueChange: " + valueChange); ColorManipulationDefaults.debug("applyChanges: 6: key=" + key); // All cases of lingering textfield entry will have been handled, now make sure texfields get set // into a state of not being edited. shouldFireChooserEvent = false; setComponentsActive(false); setComponentsActive(true); shouldFireChooserEvent = true; ColorManipulationDefaults.debug("applyChanges: 7: key=" + key); if (logDisplayButton.isSelected()) { ColorManipulationDefaults.debug("logDisplayButton=TRUE"); } else { ColorManipulationDefaults.debug("logDisplayButton=FALSE"); } if (valid && valueChange) { ColorManipulationDefaults.debug("applyChanges: 8: key=" + key); ColorManipulationDefaults.debug("Is valid"); if (key == RangeKey.InvertPalette) { ColorManipulationDefaults.debug("Applying currentInfo.setColorPaletteDefInvert"); currentInfo.setColorPaletteDefInvert(sourceCpd, targetMin, targetMax); } else { ColorManipulationDefaults.debug("Applying currentInfo.setColorPaletteDef"); currentInfo.setColorPaletteDef(sourceCpd, targetMin, targetMax, targetAutoDistribute, sourceLogScaled, targetLogScaled); } colorSchemeManager.reset(); currentInfo.setColorSchemeInfo(colorSchemeManager.getNoneColorSchemeInfo()); parentForm.applyChanges(); } ColorManipulationDefaults.debug("applyChanges: Finish: key=" + key); } } private boolean checkMinMax(double min, double max) { boolean valid = true; if (min == max) { valid = false; } else if (min > max) { valid = false; } return valid; } private double getMinFieldValue() throws NumberFormatException { if (minField.getText().length() > 0) { try { return Double.parseDouble(minField.getText()); } catch (NumberFormatException e) { throw new NumberFormatException("Min textField is not a number\n" + e.getMessage()); } } throw new NumberFormatException("Min textfield is empty"); } private double getMaxFieldValue() throws NumberFormatException { if (maxField.getText().length() > 0) { try { return Double.parseDouble(maxField.getText()); } catch (NumberFormatException e) { String errorMessage = e.getMessage(); throw new NumberFormatException("Max textField is not a number\n" + e.getMessage()); } } throw new NumberFormatException("Max textfield is empty"); } private boolean checkLogScalingAgainstMinMax(double min, double max, boolean logScaled, boolean showErrorDialog) { boolean valid = true; String errorMessage = ""; if (logScaled) { if (min == 0) { valid = false; errorMessage = "Log scaling cannot be applied with min equal to zero"; } else if (min < 0) { errorMessage = "Log scaling cannot be applied with min less than zero"; valid = false; } else if (max == 0) { errorMessage = "Log scaling cannot be applied with max equal to zero"; valid = false; } else if (max < 0) { errorMessage = "Log scaling cannot be applied with max less than zero"; valid = false; } } if (!valid && showErrorDialog) { ColorUtils.showErrorDialog("ERROR!: " + TOOLNAME_COLOR_MANIPULATION + ": \n" + errorMessage); } return valid; } private JPanel getSchemePanel(String title) { JPanel jPanel = new JPanel(new GridBagLayout()); jPanel.setBorder(BorderFactory.createTitledBorder(title)); jPanel.setToolTipText("Load a preset color scheme (sets the color-palette, min, max, and log fields)"); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1.0; gbc.insets = new Insets(0, 4, 4, 4); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; jPanel.add(colorSchemeJLabel, gbc); gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; jPanel.add(ColorSchemeManager.getDefault().getjComboBox(), gbc); gbc.gridy++; jPanel.add(schemeInfoLabel, gbc); return jPanel; } private JPanel getPalettePanel(String title) { JPanel jPanel = new JPanel(new GridBagLayout()); jPanel.setBorder(BorderFactory.createTitledBorder(title)); jPanel.setToolTipText(""); GridBagConstraints gbc = new GridBagConstraints(); gbc.weightx = 1.0; gbc.insets = new Insets(0, 4, 4, 4); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; jPanel.add(colorPaletteChooser, gbc); gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; final JPanel row2Panel = new JPanel(new BorderLayout(0, 0)); row2Panel.add(loadWithCPDFileValuesCheckBox, BorderLayout.WEST); row2Panel.add(paletteInversionButton, BorderLayout.EAST); jPanel.add(row2Panel, gbc); return jPanel; } private JPanel getRangePanel(String title) { JPanel jPanel = new JPanel(new GridBagLayout()); jPanel.setBorder(BorderFactory.createTitledBorder(title)); jPanel.setToolTipText(""); GridBagConstraints gbc = new GridBagConstraints(); final JPanel minPanel = new JPanel(new BorderLayout(0, 0)); minPanel.add(new JLabel("Min:"), BorderLayout.WEST); minPanel.add(minField, BorderLayout.EAST); final JPanel maxPanel = new JPanel(new BorderLayout(0, 0)); maxPanel.add(new JLabel("Max:"), BorderLayout.WEST); maxPanel.add(maxField, BorderLayout.EAST); final JPanel minMaxPanel = new JPanel(new BorderLayout(0, 0)); minMaxPanel.add(minPanel, BorderLayout.WEST); minMaxPanel.add(maxPanel, BorderLayout.EAST); gbc.weightx = 1.0; gbc.insets = new Insets(0, 5, 5, 5); gbc.gridx = 0; gbc.gridy = 0; gbc.anchor = GridBagConstraints.WEST; gbc.fill = GridBagConstraints.HORIZONTAL; jPanel.add(minMaxPanel, gbc); final JPanel buttonPanel = new JPanel(new BorderLayout(5, 10)); buttonPanel.add(fromFile, BorderLayout.WEST); buttonPanel.add(fromData, BorderLayout.EAST); gbc.gridy++; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(0, 4, 4, 4); jPanel.add(buttonPanel, gbc); return jPanel; } private ImageInfo createDefaultImageInfo() { try { return ProductUtils.createImageInfo(parentForm.getFormModel().getRasters(), false, ProgressMonitor.NULL); } catch (Exception e) { JOptionPane.showMessageDialog(getContentPanel(), "Failed to create default image settings:\n" + e.getMessage(), "I/O Error", JOptionPane.ERROR_MESSAGE); return null; } } private void handleColorSchemeSelector() { ColorSchemeInfo colorSchemeInfo = (ColorSchemeInfo) colorSchemeManager.getjComboBox().getSelectedItem(); if (colorSchemeInfo != null) { if (colorSchemeInfo.isEnabled() && !colorSchemeInfo.isDivider()) { if (colorSchemeManager.isNoneScheme(colorSchemeInfo)) { ColorSchemeUtils.setImageInfoToGeneralColor(configuration, createDefaultImageInfo(), parentForm.getFormModel().getProductSceneView()); } else { ColorSchemeUtils.setImageInfoToColorScheme(colorSchemeInfo, parentForm.getFormModel().getProductSceneView()); } parentForm.getFormModel().setModifiedImageInfo(parentForm.getFormModel().getProductSceneView().getImageInfo()); } else { if (!colorSchemeInfo.isDivider()) { ColorManipulationDefaults.debug("Add a notification message window"); String message = colorSchemeManager.checkScheme(colorSchemeInfo); ColorManipulationDefaults.debug(message); ColorUtils.showErrorDialog(message); } } } parentForm.applyChanges(); } }
44,866
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DiscreteCheckBox.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/DiscreteCheckBox.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.util.NamingConvention; import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; class DiscreteCheckBox extends JCheckBox { private boolean shouldFireDiscreteEvent; DiscreteCheckBox(final ColorManipulationForm parentForm) { super("Discrete " + NamingConvention.COLOR_LOWER_CASE + "s"); addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (shouldFireDiscreteEvent) { parentForm.getFormModel().getModifiedImageInfo().getColorPaletteDef().setDiscrete(isSelected()); parentForm.applyChanges(); } } }); } void setDiscreteColorsMode(boolean discrete) { shouldFireDiscreteEvent = false; setSelected(discrete); shouldFireDiscreteEvent = true; } }
946
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageInfoEditorModel3B.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ImageInfoEditorModel3B.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.colormanip; import com.bc.ceres.core.Assert; import org.esa.snap.core.datamodel.ImageInfo; import org.esa.snap.core.util.math.MathUtils; import org.esa.snap.ui.AbstractImageInfoEditorModel; import java.awt.Color; class ImageInfoEditorModel3B extends AbstractImageInfoEditorModel { private final static Color[] RGB_COLORS = new Color[]{Color.RED, Color.GREEN, Color.BLUE}; private final int channel; private byte[] gammaCurve; ImageInfoEditorModel3B(ImageInfo imageInfo, int channel) { super(imageInfo); Assert.argument(imageInfo.getRgbChannelDef() != null, "imageInfo"); this.channel = channel; updateGammaCurve(); } @Override public int getSliderCount() { return 2; } @Override public double getSliderSample(int index) { if (index == 0) { return getImageInfo().getRgbChannelDef().getMinDisplaySample(channel); } else { return getImageInfo().getRgbChannelDef().getMaxDisplaySample(channel); } } @Override public void setSliderSample(int index, double sample) { if (index == 0) { getImageInfo().getRgbChannelDef().setMinDisplaySample(channel, sample); } else { getImageInfo().getRgbChannelDef().setMaxDisplaySample(channel, sample); } fireStateChanged(); } @Override public boolean isColorEditable() { return false; } @Override public Color getSliderColor(int index) { if (index == 0) { return Color.BLACK; } else { return RGB_COLORS[channel]; } } @Override public void setSliderColor(int index, Color color) { throw new IllegalStateException("not implemented for RGB"); } @Override public void createSliderAfter(int index) { throw new IllegalStateException("not implemented for RGB"); } @Override public void removeSlider(int removeIndex) { throw new IllegalStateException("not implemented for RGB"); } @Override public Color[] createColorPalette() { Color color = RGB_COLORS[channel]; Color[] palette = new Color[256]; final int redMult = color.getRed() / 255; final int greenMult = color.getGreen() / 255; final int blueMult = color.getBlue() / 255; for (int i = 0; i < palette.length; i++) { int j = i; if (gammaCurve != null) { j = gammaCurve[i] & 0xff; } final int r = j * redMult; final int g = j * greenMult; final int b = j * blueMult; palette[i] = new Color(r, g, b); } return palette; } @Override public boolean isGammaUsed() { return getImageInfo().getRgbChannelDef().isGammaUsed(channel); } @Override public double getGamma() { return getImageInfo().getRgbChannelDef().getGamma(channel); } @Override public void setGamma(double gamma) { getImageInfo().getRgbChannelDef().setGamma(channel, gamma); updateGammaCurve(); fireStateChanged(); } @Override public byte[] getGammaCurve() { return gammaCurve; } private void updateGammaCurve() { if (isGammaUsed()) { gammaCurve = MathUtils.createGammaCurve(getGamma(), null); } else { gammaCurve = null; } } }
4,197
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
UncertaintyVisualisationTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/UncertaintyVisualisationTopComponent.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.colormanip; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.datamodel.ImageInfo; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.image.ImageManager; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.BorderLayout; import java.awt.Component; /** * The uncertainty visualisation manipulation tool window. */ @TopComponent.Description( preferredID = "UncertaintyVisualisationTopComponent", iconBase = "org/esa/snap/rcp/icons/UncertaintyStretch.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS ) @TopComponent.Registration( mode = "navigator", openAtStartup = true, position = 30 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.colormanip.UncertaintyVisualisationTopComponent") @ActionReference(path = "Menu/View/Tool Windows", position = 45) @TopComponent.OpenActionRegistration( displayName = "#CTL_UncertaintyVisualisationTopComponent_Name", preferredID = "UncertaintyVisualisationTopComponent" ) @NbBundle.Messages({ "CTL_UncertaintyVisualisationTopComponent_Name=Uncertainty Visualisation", "CTL_UncertaintyVisualisationTopComponent_ComponentName=Uncertainty_Visualisation" }) public class UncertaintyVisualisationTopComponent extends TopComponent { public static final String UNCERTAINTY_MODE_PROPERTY = "uncertaintyMode"; public UncertaintyVisualisationTopComponent() { setName(Bundle.CTL_UncertaintyVisualisationTopComponent_ComponentName()); ColorManipulationForm cmf = new ColorManipulationFormImpl(this, new UncertaintyFormModel()); setLayout(new BorderLayout()); add(cmf.getContentPanel(), BorderLayout.CENTER); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("showUncertaintyManipulationWnd"); } private static class UncertaintyFormModel extends ColorFormModel { @Override public String getTitlePrefix() { return Bundle.CTL_UncertaintyVisualisationTopComponent_Name(); } @Override public boolean isValid() { return super.isValid() && !getProductSceneView().isRGB() && getRaster() != null; } @Override public RasterDataNode getRaster() { RasterDataNode raster = getProductSceneView().getRaster(); return ImageManager.getUncertaintyBand(raster); } @Override public RasterDataNode[] getRasters() { RasterDataNode raster = getRaster(); if (raster != null) { return new RasterDataNode[]{raster}; } return null; } @Override public void setRasters(RasterDataNode[] rasters) { // not applicable } @Override public ImageInfo getOriginalImageInfo() { return getRaster().getImageInfo(ProgressMonitor.NULL); } @Override public void applyModifiedImageInfo() { getProductSceneView().updateImage(); } @Override public boolean canUseHistogramMatching() { return false; } @Override public boolean isMoreOptionsFormCollapsedOnInit() { return false; } @Override public void modifyMoreOptionsForm(MoreOptionsForm moreOptionsForm) { JComboBox<ImageInfo.UncertaintyVisualisationMode> modeBox = new JComboBox<>(ImageInfo.UncertaintyVisualisationMode.values()); modeBox.setEditable(false); moreOptionsForm.insertRow(0, new JLabel("Visualisation mode: "), modeBox); Property modeProperty = Property.create(UNCERTAINTY_MODE_PROPERTY, ImageInfo.UncertaintyVisualisationMode.class); RasterDataNode uncertaintyBand = getRaster(); try { if (uncertaintyBand != null) { modeProperty.setValue(uncertaintyBand.getImageInfo(ProgressMonitor.NULL).getUncertaintyVisualisationMode()); } else { modeProperty.setValue(ImageInfo.UncertaintyVisualisationMode.None); } } catch (ValidationException e) { // ok } moreOptionsForm.getBindingContext().getPropertySet().addProperty(modeProperty); moreOptionsForm.getBindingContext().bind(modeProperty.getName(), modeBox); moreOptionsForm.getBindingContext().addPropertyChangeListener(modeProperty.getName(), evt -> { RasterDataNode uncertainBand = getRaster(); if (uncertainBand != null) { ImageInfo.UncertaintyVisualisationMode uvMode = (ImageInfo.UncertaintyVisualisationMode) evt.getNewValue(); ImageInfo imageInfo = uncertainBand.getImageInfo(); imageInfo.setUncertaintyVisualisationMode(uvMode); setModifiedImageInfo(imageInfo); //uncertainBand.fireImageInfoChanged(); applyModifiedImageInfo(); moreOptionsForm.getChildForm().updateFormModel(moreOptionsForm.getParentForm().getFormModel()); } }); } @Override public void updateMoreOptionsFromImageInfo(MoreOptionsForm moreOptionsForm) { super.updateMoreOptionsFromImageInfo(moreOptionsForm); BindingContext bindingContext = moreOptionsForm.getBindingContext(); ImageInfo.UncertaintyVisualisationMode mode = getModifiedImageInfo().getUncertaintyVisualisationMode(); bindingContext.getBinding(UNCERTAINTY_MODE_PROPERTY).setPropertyValue(mode); } @Override public void updateImageInfoFromMoreOptions(MoreOptionsForm moreOptionsForm) { super.updateImageInfoFromMoreOptions(moreOptionsForm); BindingContext bindingContext = moreOptionsForm.getBindingContext(); ImageInfo.UncertaintyVisualisationMode mode = (ImageInfo.UncertaintyVisualisationMode) bindingContext.getBinding(UNCERTAINTY_MODE_PROPERTY).getPropertyValue(); getModifiedImageInfo().setUncertaintyVisualisationMode(mode); } @Override public Component createEmptyContentPanel() { return new JLabel("<html>This tool window is used to visualise the<br>" + "<b>uncertainty information</b> associated<br>" + "with a band shown in an image view.<br>" + "Right now, there is no selected image view or<br>" + "uncertainty information is unavailable.", SwingConstants.CENTER); } } }
7,851
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LogDisplay.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/LogDisplay.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.ColorPaletteDef; import org.esa.snap.ui.AbstractDialog; import javax.swing.AbstractButton; import java.awt.Component; class LogDisplay { static AbstractButton createButton() { final AbstractButton logDisplayButton = ImageInfoEditorSupport.createToggleButton("org/esa/snap/rcp/icons/LogDisplay24.png"); logDisplayButton.setName("logDisplayButton"); logDisplayButton.setToolTipText("Switch to logarithmic display"); /*I18N*/ return logDisplayButton; } static void showNotApplicableInfo(Component parent) { AbstractDialog.showInformationDialog(parent, "Log display is not applicable!\nThe color palette must contain only positive slider values.", "Information"); } static boolean checkApplicability(ColorPaletteDef cpd) { final ColorPaletteDef.Point[] points = cpd.getPoints(); for (ColorPaletteDef.Point point : points) { if (point.getSample() <= 0.0) { return false; } } return true; } }
1,101
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorSchemeUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorSchemeUtils.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.math.Histogram; import org.esa.snap.core.util.math.Range; import org.esa.snap.ui.product.ProductSceneView; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.*; /** * Panel handling general layer preferences. Sub-panel of the "Layer"-panel. * * @author Daniel Knowles (NASA) */ public class ColorSchemeUtils { /** * Top level method which will set the desired color palette, range and log scaling within the imageInfo * of the given productSceneView. * <p> * This is called by either the reset button within the ColorManipulation GUI or when a new View * Window is opened for a band. * * @param defaultImageInfo * @param productSceneView */ public static void setImageInfoToDefaultColor(PropertyMap configuration, ImageInfo defaultImageInfo, ProductSceneView productSceneView, boolean resetToDefaults) { boolean imageInfoSet = false; ColorSchemeManager colorPaletteSchemes = ColorSchemeManager.getDefault(); if (configuration != null && configuration.getPropertyBool(PROPERTY_SCHEME_AUTO_APPLY_KEY, PROPERTY_SCHEME_AUTO_APPLY_DEFAULT)) { ColorSchemeInfo colorSchemeInfo = getColorPaletteInfoByBandNameLookup(productSceneView); if (colorSchemeInfo != null) { imageInfoSet = ColorSchemeUtils.setImageInfoToColorScheme(colorSchemeInfo, productSceneView); if (imageInfoSet) { colorPaletteSchemes.setSelected(colorSchemeInfo); } } } boolean customDefaultScheme = configuration.getPropertyBool(PROPERTY_GENERAL_CUSTOM_KEY, PROPERTY_GENERAL_CUSTOM_DEFAULT); if (!imageInfoSet) { if (customDefaultScheme) { colorPaletteSchemes.reset(); setImageInfoToGeneralColor(configuration, defaultImageInfo, productSceneView); } else { if (resetToDefaults) { productSceneView.setImageInfo(defaultImageInfo); } } } } public static boolean isRangeFromDataNonScheme(PropertyMap configuration) { if (configuration == null) { return false; } String generalRange = configuration.getPropertyString(PROPERTY_GENERAL_RANGE_KEY, PROPERTY_GENERAL_RANGE_DEFAULT); if (generalRange != null && generalRange.equals(ColorManipulationDefaults.OPTION_RANGE_FROM_DATA)) { return true; } else { return false; } } public static boolean isGeneralLogScaled(ColorPaletteDef colorPaletteDef, ProductSceneView productSceneView) { boolean logScaled = false; PropertyMap configuration = productSceneView.getSceneImage().getConfiguration(); if (configuration == null) { return false; } String logScaledOption = configuration.getPropertyString(PROPERTY_GENERAL_LOG_KEY, PROPERTY_GENERAL_LOG_DEFAULT); if (logScaledOption != null) { switch (logScaledOption) { case ColorManipulationDefaults.OPTION_LOG_TRUE: logScaled = true; break; case ColorManipulationDefaults.OPTION_LOG_FALSE: logScaled = false; break; case ColorManipulationDefaults.OPTION_LOG_FROM_PALETTE: if (colorPaletteDef != null) { logScaled = colorPaletteDef.isLogScaled(); } break; default: logScaled = false; } } return logScaled; } public static File getDefaultCpd(PropertyMap configuration) { String filename = null; String fileCategory = configuration.getPropertyString(ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_KEY, ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_DEFAULT); if (fileCategory != null) { switch (fileCategory) { case ColorManipulationDefaults.OPTION_COLOR_GRAY_SCALE: filename = configuration.getPropertyString(ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_DEFAULT); break; case ColorManipulationDefaults.OPTION_COLOR_STANDARD: filename = configuration.getPropertyString(ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_DEFAULT); break; case ColorManipulationDefaults.OPTION_COLOR_UNIVERSAL: filename = configuration.getPropertyString(ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_DEFAULT); break; case ColorManipulationDefaults.OPTION_COLOR_ANOMALIES: filename = configuration.getPropertyString(ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_DEFAULT); break; default: filename = ColorManipulationDefaults.PALETTE_DEFAULT; } } File auxDir = ColorSchemeUtils.getColorPalettesAuxDataDir().toFile(); if (filename != null) { File defaultCpd = new File(auxDir, filename); if (defaultCpd.exists()) { return defaultCpd; } } return null; } public static void setImageInfoToGeneralColor(PropertyMap configuration, ImageInfo defaultImageInfo, ProductSceneView productSceneView) { boolean imageInfoSet = false; File defaultCpdFile = getDefaultCpd(configuration); ColorSchemeInfo colorSchemeInfo = ColorSchemeManager.getDefault().getNoneColorSchemeInfo(); productSceneView.getImageInfo().setColorSchemeInfo(colorSchemeInfo); ColorPaletteDef colorPaletteDef = null; if (defaultCpdFile.exists()) { try { colorPaletteDef = ColorPaletteDef.loadColorPaletteDef(defaultCpdFile); } catch (IOException e) { } } if (colorPaletteDef != null) { double minTarget; double maxTarget; if (isRangeFromDataNonScheme(configuration)) { Stx stx = productSceneView.getRaster().getStx(); if (stx != null) { final Histogram histogram = new Histogram(stx.getHistogramBins(), stx.getMinimum(), stx.getMaximum()); double percentile = configuration.getPropertyDouble(PROPERTY_RANGE_PERCENTILE_KEY, PROPERTY_RANGE_PERCENTILE_DEFAULT); Range autoStretchRange = histogram.findRangeForPercent(percentile); if (autoStretchRange != null) { minTarget = autoStretchRange.getMin(); maxTarget = autoStretchRange.getMax(); } else { minTarget = stx.getMinimum(); maxTarget = stx.getMaximum(); } } else { minTarget = colorPaletteDef.getMinDisplaySample(); maxTarget = colorPaletteDef.getMaxDisplaySample(); } } else { minTarget = colorPaletteDef.getMinDisplaySample(); maxTarget = colorPaletteDef.getMaxDisplaySample(); } boolean logScaledSource = colorPaletteDef.isLogScaled(); boolean logScaledTarget = isGeneralLogScaled(colorPaletteDef, productSceneView); // todo Possibly show alert GUI in future - this line just prevents log scaling for min < 0 if (minTarget <= 0) { logScaledTarget = false; } productSceneView.getImageInfo().setColorPaletteDef(colorPaletteDef, minTarget, maxTarget, true, //colorPaletteDef.isAutoDistribute(), logScaledSource, logScaledTarget); productSceneView.getImageInfo().setLogScaled(logScaledTarget); imageInfoSet = true; } if (!imageInfoSet) { productSceneView.setImageInfo(defaultImageInfo); } return; } public static ColorSchemeInfo getColorPaletteInfoByBandNameLookup(ProductSceneView productSceneView) { ColorSchemeManager colorSchemeManager = ColorSchemeManager.getDefault(); if (colorSchemeManager != null) { String bandName = productSceneView.getBaseImageLayer().getName().trim(); bandName = bandName.substring(bandName.indexOf(" ")).trim(); ArrayList<ColorSchemeLookupInfo> colorSchemeLookupInfos = colorSchemeManager.getColorSchemeLookupInfos(); for (ColorSchemeLookupInfo colorSchemeLookupInfo : colorSchemeLookupInfos) { if (colorSchemeLookupInfo.isMatch(bandName)) { return colorSchemeManager.getColorSchemeInfoBySchemeId(colorSchemeLookupInfo.getScheme_id()); } } } return null; } public static boolean getLogScaledFromScheme(PropertyMap configuration, ColorSchemeInfo colorSchemeInfo, ColorPaletteDef colorPaletteDef) { boolean logScaled = false; String schemeLogScaling = configuration.getPropertyString(ColorManipulationDefaults.PROPERTY_SCHEME_LOG_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_LOG_DEFAULT); if (schemeLogScaling != null) { switch (schemeLogScaling) { case ColorManipulationDefaults.OPTION_LOG_TRUE: logScaled = true; break; case ColorManipulationDefaults.OPTION_LOG_FALSE: logScaled = false; break; case ColorManipulationDefaults.OPTION_LOG_FROM_PALETTE: if (colorPaletteDef != null) { logScaled = colorPaletteDef.isLogScaled(); } break; case ColorManipulationDefaults.OPTION_LOG_FROM_SCHEME: logScaled = colorSchemeInfo.isLogScaled(); break; default: logScaled = false; } } return logScaled; } public static String getCdpFileNameFromSchemeSelection(PropertyMap configuration, ColorSchemeInfo colorSchemeInfo) { String cpdFileName = null; String schemeCpdOption = configuration.getPropertyString( ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_DEFAULT); switch (schemeCpdOption) { case ColorManipulationDefaults.OPTION_COLOR_STANDARD_SCHEME: cpdFileName = colorSchemeInfo.getCpdFilename(false); break; case ColorManipulationDefaults.OPTION_COLOR_UNIVERSAL_SCHEME: cpdFileName = colorSchemeInfo.getCpdFilename(true); break; case ColorManipulationDefaults.OPTION_COLOR_GRAY_SCALE: cpdFileName = configuration.getPropertyString( ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_DEFAULT); break; case ColorManipulationDefaults.OPTION_COLOR_STANDARD: cpdFileName = configuration.getPropertyString( ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_DEFAULT); break; case ColorManipulationDefaults.OPTION_COLOR_UNIVERSAL: cpdFileName = configuration.getPropertyString( ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_DEFAULT); break; case ColorManipulationDefaults.OPTION_COLOR_ANOMALIES: cpdFileName = configuration.getPropertyString( ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_DEFAULT); break; default: break; } return cpdFileName; } public static boolean setImageInfoToColorScheme(ColorSchemeInfo colorSchemeInfo, ProductSceneView productSceneView) { ColorManipulationDefaults.debug("Inside setImageInfoToColorScheme"); if (colorSchemeInfo == null || productSceneView == null) { return false; } productSceneView.getImageInfo().setColorSchemeInfo(colorSchemeInfo); PropertyMap configuration = productSceneView.getSceneImage().getConfiguration(); String cpdFileName = getCdpFileNameFromSchemeSelection(configuration, colorSchemeInfo); ColorManipulationDefaults.debug("Inside setImageInfoToColorScheme: cpdFileName=" + cpdFileName); ColorPaletteDef colorPaletteDef = null; File auxDir = ColorSchemeUtils.getColorPalettesAuxDataDir().toFile(); if (cpdFileName != null) { File cpdFile = new File(auxDir, cpdFileName); try { if (cpdFileName.endsWith("cpt")) { colorPaletteDef = ColorPaletteDef.loadCpt(cpdFile); } else { colorPaletteDef = ColorPaletteDef.loadColorPaletteDef(cpdFile); } } catch (IOException e) { ColorManipulationDefaults.debug("Inside setImageInfoToColorScheme: cpd read exception"); return false; } } // Determine range: min and max double min; double max; Stx stx = productSceneView.getRaster().getStx(); String schemeRange = configuration.getPropertyString(ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_DEFAULT); switch (schemeRange) { case ColorManipulationDefaults.OPTION_RANGE_FROM_SCHEME: min = colorSchemeInfo.getMinValue(); if (min == ColorManipulationDefaults.DOUBLE_NULL) { min = stx.getMinimum(); } max = colorSchemeInfo.getMaxValue(); if (max == ColorManipulationDefaults.DOUBLE_NULL) { max = stx.getMaximum(); } break; case ColorManipulationDefaults.OPTION_RANGE_FROM_DATA: min = stx.getMinimum(); max = stx.getMaximum(); break; case ColorManipulationDefaults.OPTION_RANGE_FROM_PALETTE: min = colorPaletteDef.getMinDisplaySample(); max = colorPaletteDef.getMaxDisplaySample(); break; default: min = stx.getMinimum(); max = stx.getMaximum(); break; } boolean logScaled = getLogScaledFromScheme(configuration, colorSchemeInfo, colorPaletteDef); if (colorPaletteDef != null) { productSceneView.getImageInfo().setColorPaletteDef(colorPaletteDef, min, max, true, //colorPaletteDef.isAutoDistribute(), colorPaletteDef.isLogScaled(), logScaled); productSceneView.getImageInfo().setLogScaled(logScaled); return true; } return false; } public static Path getColorPalettesAuxDataDir() { return SystemUtils.getAuxDataPath().resolve(ColorManipulationDefaults.DIR_NAME_COLOR_PALETTES); } public static Path getColorSchemesAuxDataDir() { return SystemUtils.getAuxDataPath().resolve(ColorManipulationDefaults.DIR_NAME_COLOR_SCHEMES); } public static Path getRgbProfilesAuxDataDir() { return SystemUtils.getAuxDataPath().resolve(ColorManipulationDefaults.DIR_NAME_RGB_PROFILES); } }
16,796
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorUtils.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; /** * Utility class containing methods to the Color Manipulation Tool. * * @author Jean Coravu * @author Daniel Knowles (NASA) */ // OCT 2019 - Knowles // - Added methods to perform numerical checks which return a boolean with the additional option to display // the error message in the GUI status bar. public class ColorUtils { /** * Private constructor to avoid creating new objects. */ private ColorUtils() { } /** * Returns the RGB color as int. * * @param red the red component * @param green the green component * @param blue the blue component * @return the RGB color as int */ public static int rgba(int red, int green, int blue) { int rgba = 255; rgba = (rgba << 8) + red; rgba = (rgba << 8) + green; rgba = (rgba << 8) + blue; return rgba; } /** * Returns the alpha component. * * @param color the RGB color * @return the alpha component */ public static int alpha(int color) { return color >> 24 & 0x0FF; } /** * Returns the red component. * * @param color the RGB color * @return the red component */ public static int red(int color) { return color >> 16 & 0x0FF; } /** * Returns the green component. * * @param color the RGB color * @return the green component */ public static int green(int color) { return color >> 8 & 0x0FF; } /** * Returns the blue component. * * @param color the RGB color * @return the blue component */ public static int blue(int color) { return color & 0x0FF; } public static boolean isNumber(String string) { try { double d = Double.parseDouble(string); } catch (NumberFormatException nfe) { return false; } return true; } public static boolean isNumber(String string, String componentName, boolean showMessage) { try { double d = Double.parseDouble(string); } catch (NumberFormatException nfe) { if (showMessage) { ColorUtils.showErrorDialog("INPUT ERROR!!: \" + componentName + \"=\" + string + \" is not a number"); // SnapApp.getDefault().setStatusBarMessage("INPUT ERROR!!: " + componentName + "=" + string + " is not a number"); } return false; } return true; } public static boolean checkRangeCompatibility(String minStr, String maxStr) { if (!isNumber(minStr, "Min Textfield", true)) { return false; } if (!isNumber(maxStr, "Min Textfield", true)) { return false; } double min = Double.parseDouble(minStr); double max = Double.parseDouble(maxStr); if (!checkRangeCompatibility(min, max)) { return false; } return true; } public static boolean checkRangeCompatibility(double min, double max) { if (min >= max) { ColorUtils.showErrorDialog("INPUT ERROR!!: Max must be greater than Min"); return false; } return true; } public static void showErrorDialog(final String message) { if (message != null && message.trim().length() > 0) { if (SnapApp.getDefault() != null) { Dialogs.showError(message); } else { Dialogs.showError("Error", message); } } } public static boolean checkRangeCompatibility(double min, double max, boolean isLogScaled) { if (!checkRangeCompatibility(min, max)) { return false; } if (!checkLogCompatibility(min, "Min Textfield", isLogScaled)) { return false; } return true; } public static boolean checkSliderRangeCompatibility(double value, double min, double max) { if (value <= min || value >= max) { ColorUtils.showErrorDialog("INPUT ERROR!!: Slider outside range of adjacent sliders"); return false; } return true; } public static boolean checkLogCompatibility(double value, String componentName, boolean isLogScaled) { if ((isLogScaled) && value <= 0) { ColorUtils.showErrorDialog("INPUT ERROR!!: \" + componentName + \" must be greater than zero in log scaling mode"); return false; } return true; } public static boolean checkTableRangeCompatibility(double value, double min, double max) { if (value <= min || value >= max) { ColorUtils.showErrorDialog("INPUT ERROR!!: Value outside range of adjacent Table Values"); return false; } return true; } }
4,976
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Discrete1BandTabularForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/Discrete1BandTabularForm.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.colormanip; import com.bc.ceres.core.Assert; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.NamingConvention; import org.esa.snap.ui.color.ColorTableCellEditor; import org.esa.snap.ui.color.ColorTableCellRenderer; import javax.swing.AbstractButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableRowSorter; import java.awt.Color; import java.awt.Component; import java.text.NumberFormat; public class Discrete1BandTabularForm implements ColorManipulationChildForm { private static final String[] COLUMN_NAMES = new String[]{"Label", NamingConvention.COLOR_MIXED_CASE, "Value", "Frequency", "Description"}; private static final Class<?>[] COLUMN_TYPES = new Class<?>[]{String.class, Color.class, String.class, Double.class, String.class}; private final ColorManipulationForm parentForm; private JComponent contentPanel; private ImageInfoTableModel tableModel; private MoreOptionsForm moreOptionsForm; public Discrete1BandTabularForm(ColorManipulationForm parentForm) { this.parentForm = parentForm; tableModel = new ImageInfoTableModel(); moreOptionsForm = new MoreOptionsForm(this, false); final JTable table = new JTable(tableModel); table.setRowSorter(new TableRowSorter<>(tableModel)); table.setDefaultRenderer(Color.class, new ColorTableCellRenderer()); table.setDefaultEditor(Color.class, new ColorTableCellEditor()); table.getTableHeader().setReorderingAllowed(false); table.getColumnModel().getColumn(1).setPreferredWidth(140); table.getColumnModel().getColumn(3).setCellRenderer(new PercentageRenderer()); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JScrollPane tableScrollPane = new JScrollPane(table); tableScrollPane.getViewport().setPreferredSize(table.getPreferredSize()); contentPanel = tableScrollPane; } @Override public ColorManipulationForm getParentForm() { return parentForm; } @Override public void handleFormShown(ColorFormModel formModel) { updateFormModel(formModel); } @Override public void handleFormHidden(ColorFormModel formModel) { } @Override public void updateFormModel(ColorFormModel formModel) { parentForm.getStx(formModel.getRaster()); tableModel.fireTableDataChanged(); } @Override public void resetFormModel(ColorFormModel formModel) { updateFormModel(formModel); } @Override public void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster) { } @Override public AbstractButton[] getToolButtons() { return new AbstractButton[0]; } @Override public Component getContentPanel() { return contentPanel; } @Override public RasterDataNode[] getRasters() { return parentForm.getFormModel().getRasters(); } @Override public MoreOptionsForm getMoreOptionsForm() { return moreOptionsForm; } private static class PercentageRenderer extends DefaultTableCellRenderer { private final NumberFormat formatter; public PercentageRenderer() { setHorizontalAlignment(JLabel.RIGHT); formatter = NumberFormat.getPercentInstance(); formatter.setMinimumFractionDigits(3); formatter.setMaximumFractionDigits(3); } @Override public void setValue(Object value) { setText(formatter.format(value)); } } private class ImageInfoTableModel extends AbstractTableModel { private ImageInfoTableModel() { } public ImageInfo getImageInfo() { return parentForm.getFormModel().getModifiedImageInfo(); } @Override public String getColumnName(int columnIndex) { return COLUMN_NAMES[columnIndex]; } @Override public Class<?> getColumnClass(int columnIndex) { return COLUMN_TYPES[columnIndex]; } public int getColumnCount() { return COLUMN_NAMES.length; } public int getRowCount() { if (getImageInfo() == null) { return 0; } return getImageInfo().getColorPaletteDef().getNumPoints(); } public Object getValueAt(int rowIndex, int columnIndex) { if (getImageInfo() == null) { return null; } final ColorPaletteDef.Point point = getImageInfo().getColorPaletteDef().getPointAt(rowIndex); if (columnIndex == 0) { return point.getLabel(); } else if (columnIndex == 1) { final Color color = point.getColor(); return color.equals(ImageInfo.NO_COLOR) ? null : color; } else if (columnIndex == 2) { return Double.isNaN(point.getSample()) ? "Uncoded" : (int) point.getSample(); } else if (columnIndex == 3) { final RasterDataNode raster = parentForm.getFormModel().getRaster(); final Stx stx = raster.getStx(); Assert.notNull(stx, "stx"); final int[] frequencies = stx.getHistogramBins(); Assert.notNull(frequencies, "frequencies"); if (raster instanceof Band) { Band band = (Band) raster; final IndexCoding indexCoding = band.getIndexCoding(); if (indexCoding != null) { final String[] indexNames = indexCoding.getIndexNames(); if (rowIndex < indexNames.length) { final int indexValue = indexCoding.getAttributeIndex(indexCoding.getIndex(indexNames[rowIndex])); final double frequency = frequencies[indexValue]; return frequency / stx.getSampleCount(); } } } return 0.0; } else if (columnIndex == 4) { final RasterDataNode raster = parentForm.getFormModel().getRaster(); if (raster instanceof Band) { Band band = (Band) raster; final IndexCoding indexCoding = band.getIndexCoding(); if (indexCoding != null && rowIndex < indexCoding.getSampleCount()) { final String text = indexCoding.getAttributeAt(rowIndex).getDescription(); return text != null ? text : ""; } } return ""; } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { if (getImageInfo() == null) { return; } final ColorPaletteDef.Point point = getImageInfo().getColorPaletteDef().getPointAt(rowIndex); if (columnIndex == 0) { point.setLabel((String) aValue); fireTableCellUpdated(rowIndex, columnIndex); parentForm.applyChanges(); } else if (columnIndex == 1) { final Color color = (Color) aValue; point.setColor(color == null ? ImageInfo.NO_COLOR : color); fireTableCellUpdated(rowIndex, columnIndex); parentForm.applyChanges(); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0 || columnIndex == 1; } } }
8,578
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorManipulationChildForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorManipulationChildForm.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.colormanip; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.RasterDataNode; import javax.swing.AbstractButton; import java.awt.Component; public interface ColorManipulationChildForm { ColorManipulationForm getParentForm(); void handleFormShown(ColorFormModel formModel); void handleFormHidden(ColorFormModel formModel); void updateFormModel(ColorFormModel formModel); void resetFormModel(ColorFormModel formModel); void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster); Component getContentPanel(); AbstractButton[] getToolButtons(); MoreOptionsForm getMoreOptionsForm(); RasterDataNode[] getRasters(); }
1,470
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
EmptyImageInfoForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/EmptyImageInfoForm.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.colormanip; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.RasterDataNode; import javax.swing.AbstractButton; import java.awt.Component; public class EmptyImageInfoForm implements ColorManipulationChildForm { private final ColorManipulationForm parentForm; public EmptyImageInfoForm(ColorManipulationForm parentForm) { this.parentForm = parentForm; } @Override public ColorManipulationForm getParentForm() { return parentForm; } @Override public void handleFormShown(ColorFormModel formModel) { } @Override public void handleFormHidden(ColorFormModel formModel) { } @Override public void updateFormModel(ColorFormModel formModel) { } @Override public void resetFormModel(ColorFormModel formModel) { } @Override public void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster) { } @Override public AbstractButton[] getToolButtons() { return new AbstractButton[0]; } @Override public Component getContentPanel() { return parentForm.getFormModel().createEmptyContentPanel(); } @Override public RasterDataNode[] getRasters() { return new RasterDataNode[0]; } @Override public MoreOptionsForm getMoreOptionsForm() { return null; } }
2,132
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MoreOptionsPane.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/MoreOptionsPane.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.colormanip; import com.jidesoft.swing.TitledSeparator; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.SwingConstants; import javax.swing.UIManager; import java.awt.BorderLayout; import java.awt.Color; class MoreOptionsPane { private static ImageIcon[] icons; private static ImageIcon[] rolloverIcons; private final ColorManipulationForm colorManipulationForm; private final JPanel contentPanel; private final JLabel[] headerLabels; private final TitledSeparator headerSeparator; private final AbstractButton headerButton; private JComponent component; private boolean collapsed; MoreOptionsPane(ColorManipulationForm colorManipulationForm, boolean collapsed) { this.colorManipulationForm = colorManipulationForm; if (icons == null) { icons = new ImageIcon[]{ UIUtils.loadImageIcon("icons/PanelUp12.png"), UIUtils.loadImageIcon("icons/PanelDown12.png"), }; rolloverIcons = new ImageIcon[]{ ToolButtonFactory.createRolloverIcon(icons[0]), ToolButtonFactory.createRolloverIcon(icons[1]), }; } // printDefaults(UIManager.getLookAndFeelDefaults(), "UIManager.getLookAndFeelDefaults()"); headerLabels = new JLabel[]{ new JLabel("More Options"), new JLabel("Less Options"), }; Color headerLabelColor = UIManager.getLookAndFeelDefaults().getColor("TitledBorder.titleColor"); if (headerLabelColor != null) { headerLabels[0].setForeground(headerLabelColor); headerLabels[1].setForeground(headerLabelColor); } this.component = new JLabel(); // dummy this.collapsed = collapsed; headerButton = ToolButtonFactory.createButton(icons[0], false); headerButton.setName("MoreOptionsPane.headerButton"); headerButton.addActionListener(e -> setCollapsed(!isCollapsed())); final JPanel titleBar = new JPanel(new BorderLayout(2, 2)); titleBar.add(headerButton, BorderLayout.WEST); headerSeparator = new TitledSeparator(headerLabels[0], TitledSeparator.TYPE_PARTIAL_ETCHED, SwingConstants.LEFT); headerSeparator.setName("MoreOptionsPane.headerSeparator"); titleBar.add(headerSeparator, BorderLayout.CENTER); contentPanel = new JPanel(new BorderLayout(2, 2)); contentPanel.add(titleBar, BorderLayout.NORTH); contentPanel.setName("MoreOptionsPane.contentPanel"); } public JPanel getContentPanel() { return contentPanel; } public JComponent getComponent() { return component; } public void setComponent(JComponent component) { contentPanel.remove(this.component); this.component = component; updateState(); } public boolean isCollapsed() { return collapsed; } public void setCollapsed(boolean collapsed) { this.collapsed = collapsed; updateState(); } private void updateState() { if (collapsed) { contentPanel.remove(this.component); } else { contentPanel.add(this.component, BorderLayout.CENTER); } final int i = collapsed ? 0 : 1; headerSeparator.setLabelComponent(headerLabels[i]); headerButton.setIcon(icons[i]); headerButton.setRolloverIcon(rolloverIcons[i]); colorManipulationForm.revalidateToolViewPaneControl(); } }
4,469
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorManipulationForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorManipulationForm.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.Stx; import javax.swing.JPanel; import java.awt.event.ActionListener; import java.nio.file.Path; /** * @author Tonio Fincke */ public interface ColorManipulationForm { ColorFormModel getFormModel(); void installToolButtons(boolean installAllButtons); void installMoreOptions(); void revalidateToolViewPaneControl(); Stx getStx(RasterDataNode raster); void applyChanges(); Path getIODir(); JPanel getContentPanel(); ActionListener wrapWithAutoApplyActionListener(final ActionListener actionListener); }
676
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SliderPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/SliderPanel.java
package org.esa.snap.rcp.colormanip; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.basic.BasicSliderUI; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; /** * The <code>SliderPanel</code> class contains the slider and input text field components. * * @author Jean Coravu */ class SliderPanel extends JPanel { private final ChangeListener localChangeListener; private final JSlider slider; private final JTextField input; private final ChangeListener sliderChangeListener; private final JLabel titleLabel; private int previousValue; /** * Constructs a new item. * * @param title the panel title * @param sliderChangeListener the slider listener */ SliderPanel(String title, ChangeListener sliderChangeListener) { super(new BorderLayout()); int maximumNumber = 100; this.sliderChangeListener = sliderChangeListener; this.previousValue = 0; this.titleLabel = new JLabel(title, JLabel.LEFT); this.titleLabel.setBorder(new EmptyBorder(0, 0, 0, 0)); this.slider = new JSlider(JSlider.HORIZONTAL, -maximumNumber, maximumNumber, this.previousValue); this.slider.setFocusable(false); this.slider.setMajorTickSpacing(maximumNumber); this.slider.setMinorTickSpacing(0); this.slider.setPaintTicks(true); this.slider.setPaintLabels(true); MouseListener[] listeners = this.slider.getMouseListeners(); for (int i=0; i<listeners.length; i++) { this.slider.removeMouseListener(listeners[i]); } final BasicSliderUI ui = (BasicSliderUI) this.slider.getUI(); BasicSliderUI.TrackListener trackListener = ui.new TrackListener() { @Override public void mouseClicked(MouseEvent event) { if (slider.isEnabled()) { Point mousePoint = event.getPoint(); int value = ui.valueForXPosition(mousePoint.x); slider.setValue(value); } } @Override public boolean shouldScroll(int direction) { return false; } }; this.slider.addMouseListener(trackListener); this.localChangeListener = new ChangeListener() { @Override public void stateChanged(ChangeEvent event) { sliderValueChanged(event); } }; this.slider.addChangeListener(this.localChangeListener); this.input = new JTextField(5); this.input.setDocument(new NumberPlainDocument(this.slider.getMinimum(), this.slider.getMaximum())); this.input.addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent event) { if (event.getKeyCode() == KeyEvent.VK_ENTER) { int number = Integer.parseInt(input.getText()); slider.setValue(number); } } }); refreshInputValue(); JPanel panelInput = new JPanel(new FlowLayout()); panelInput.add(this.input); add(this.titleLabel, BorderLayout.WEST); add(this.slider, BorderLayout.CENTER); add(panelInput, BorderLayout.EAST); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); this.titleLabel.setEnabled(enabled); this.slider.setEnabled(enabled); this.input.setEnabled(enabled); } /** * Returns the preferred width of the title label. * * @return the preferred width of the title label */ public int getTitlePreferredWidth() { return this.titleLabel.getPreferredSize().width; } /** * Sets the preferred width of the title label. * * @param preferredWidth the width to set */ public void setTitlePreferredWidth(int preferredWidth) { Dimension size = this.titleLabel.getPreferredSize(); size.width = preferredWidth; this.titleLabel.setPreferredSize(size); } /** * Returns the slider maximum value. * * @return the slider maximum value */ public int getSliderMaximumValue() { return this.slider.getMaximum(); } /** * Returns the slider value. * * @return the slider value */ public int getSliderValue() { return this.slider.getValue(); } /** * Sets the slider value. * @param sliderValue the slider value */ public void setSliderValue(int sliderValue) { this.slider.removeChangeListener(this.localChangeListener); this.previousValue = sliderValue; this.slider.setValue(this.previousValue); refreshInputValue(); this.slider.addChangeListener(this.localChangeListener); } /** * Sets the slider value in the input text field. */ private void refreshInputValue() { String value = Integer.toString(this.slider.getValue()); this.input.setText(value); } /** * Fire the slider change event if the current slider value has changed. * @param event the slider change event */ private void sliderValueChanged(ChangeEvent event) { int currentSliderValue = slider.getValue(); if (!slider.getValueIsAdjusting() && currentSliderValue != previousValue) { previousValue = currentSliderValue; refreshInputValue(); sliderChangeListener.stateChanged(event); } } }
5,766
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorPaletteChooser.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorPaletteChooser.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.ColorPaletteDef; import org.esa.snap.core.datamodel.ImageInfo; import org.esa.snap.core.image.ImageManager; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.core.util.math.Range; import javax.swing.*; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.util.List; import java.util.Vector; /** * This class creates the color palette chooser JComboBox contained within the color manipulation tool. * * @author Brockmann Consult * @author Daniel Knowles (NASA) * @version $Revision$ $Date$ */ // DEC 2019 - Knowles // - Fixed bug where log scaled color palette would appear crunched in the selector // - Added tooltips to show which color palette is being hovered over and selected // - Added blue highlights within the renderer to show which color palette is being hovered over selected class ColorPaletteChooser extends JComboBox<ColorPaletteChooser.ColorPaletteWrapper> { private final String DERIVED_FROM = "derived from"; private final String UNNAMED = "unnamed"; private boolean discreteDisplay; private boolean log10Display; public ColorPaletteChooser() { super(getPalettes()); setRenderer(createPaletteRenderer()); setEditable(false); } public void removeUserDefinedPalette() { if (getItemCount() > 0) { final String name = getItemAt(0).name; if (UNNAMED.equals(name) || name.startsWith(DERIVED_FROM)) { removeItemAt(0); } } } public ColorPaletteDef getSelectedColorPaletteDefinition() { final int selectedIndex = getSelectedIndex(); final ComboBoxModel<ColorPaletteWrapper> model = getModel(); final ColorPaletteWrapper colorPaletteWrapper = model.getElementAt(selectedIndex); final ColorPaletteDef cpd = colorPaletteWrapper.cpd; cpd.getFirstPoint().setLabel(colorPaletteWrapper.name); return cpd; } public void setSelectedColorPaletteDefinition(ColorPaletteDef cpd) { removeUserDefinedPalette(); final ComboBoxModel<ColorPaletteWrapper> model = getModel(); for (int i = 0; i < model.getSize(); i++) { if (model.getElementAt(i).cpd.equals(cpd)) { setSelectedIndex(i); return; } } setUserDefinedPalette(cpd); } public void reloadPalettes() { setModel(new DefaultComboBoxModel<>(getPalettes())); repaint(); } private void setUserDefinedPalette(ColorPaletteDef userPalette) { final String suffix = userPalette.getFirstPoint().getLabel(); final String name; if (suffix != null && suffix.trim().length() > 0) { name = DERIVED_FROM + " " + suffix.trim(); } else { name = UNNAMED; } final ColorPaletteWrapper item = new ColorPaletteWrapper(name, userPalette); insertItemAt(item, 0); setSelectedIndex(0); } private static Vector<ColorPaletteWrapper> getPalettes() { final List<ColorPaletteDef> defList = ColorPaletteManager.getDefault().getColorPaletteDefList(); final Vector<ColorPaletteWrapper> paletteWrappers = new Vector<>(); for (ColorPaletteDef colorPaletteDef : defList) { final String nameFor = getNameForWithoutExtension(colorPaletteDef); paletteWrappers.add(new ColorPaletteWrapper(nameFor, colorPaletteDef)); } return paletteWrappers; } private static String getNameForWithoutExtension(ColorPaletteDef colorPaletteDef) { final String nameFor = ColorPaletteManager.getDefault().getNameFor(colorPaletteDef); if (nameFor.toLowerCase().endsWith(".cpd")) { return nameFor.substring(0, nameFor.length() - 4); } else { return nameFor; } } private ListCellRenderer<ColorPaletteWrapper> createPaletteRenderer() { return new ListCellRenderer<ColorPaletteWrapper>() { @Override public Component getListCellRendererComponent(JList<? extends ColorPaletteWrapper> list, ColorPaletteWrapper value, int index, boolean isSelected, boolean cellHasFocus) { final Font font = getFont(); final Font smaller = font.deriveFont(font.getSize() * 0.85f); final JLabel nameComp = new JLabel(value.name); nameComp.setFont(smaller); final ColorPaletteDef cpd = value.cpd; final JLabel rampComp = new JLabel(" ") { @Override public void paint(Graphics g) { super.paint(g); drawPalette((Graphics2D) g, cpd, g.getClipBounds().getSize(), index, isSelected); } }; final JPanel palettePanel = new JPanel(new BorderLayout(0, 2)); palettePanel.add(nameComp, BorderLayout.NORTH); palettePanel.add(rampComp, BorderLayout.CENTER); if (isSelected) { list.setToolTipText(value.name); } return palettePanel; } }; } private void drawPalette(Graphics2D g2, ColorPaletteDef colorPaletteDef, Dimension paletteDim, int index, boolean isSelected) { final int width = paletteDim.width; final int height = paletteDim.height; final ColorPaletteDef cpdCopy = colorPaletteDef.createDeepCopy(); cpdCopy.setDiscrete(discreteDisplay); cpdCopy.setNumColors(width); final ImageInfo imageInfo = new ImageInfo(cpdCopy); imageInfo.setLogScaled(log10Display); imageInfo.setLogScaled(colorPaletteDef.isLogScaled()); Color[] colorPalette = ImageManager.createColorPalette(imageInfo); g2.setStroke(new BasicStroke(1.0f)); for (int x = 0; x < width; x++) { if (isSelected && index != 0) { int edgeThickness = 1; g2.setColor(colorPalette[x]); g2.drawLine(x, (edgeThickness + 1), x, height - (edgeThickness + 1)); g2.setColor(Color.blue); g2.drawLine(x, 0, x, edgeThickness); g2.drawLine(x, height - edgeThickness, x, height); } else { g2.setColor(colorPalette[x]); g2.drawLine(x, 0, x, height); } } } public void setLog10Display(boolean log10Display) { this.log10Display = log10Display; repaint(); } public void setDiscreteDisplay(boolean discreteDisplay) { this.discreteDisplay = discreteDisplay; repaint(); } public Range getRangeFromFile() { final ComboBoxModel<ColorPaletteWrapper> model = getModel(); final int selectedIndex = getSelectedIndex(); final ColorPaletteWrapper paletteWrapper = model.getElementAt(selectedIndex); String name = paletteWrapper.name; final ColorPaletteDef cpd; if (name.startsWith(DERIVED_FROM)) { name = name.substring(DERIVED_FROM.length()).trim(); if (name.toLowerCase().endsWith(".cpd")) { name = FileUtils.getFilenameWithoutExtension(name); } cpd = findColorPalette(name); } else { cpd = paletteWrapper.cpd; } return new Range(cpd.getMinDisplaySample(), cpd.getMaxDisplaySample()); } private ColorPaletteDef findColorPalette(String name) { final ComboBoxModel<ColorPaletteWrapper> model = getModel(); for (int i = 0; i < model.getSize(); i++) { final ColorPaletteWrapper paletteWrapper = model.getElementAt(i); if (paletteWrapper.name.equals(name)) { return paletteWrapper.cpd; } } return null; } public static final class ColorPaletteWrapper { public final String name; public final ColorPaletteDef cpd; private ColorPaletteWrapper(String name, ColorPaletteDef cpd) { this.name = name; this.cpd = cpd; } } }
8,382
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
NumberPlainDocument.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/NumberPlainDocument.java
package org.esa.snap.rcp.colormanip; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import javax.swing.text.PlainDocument; /** * The <code>NumberPlainDocument</code> class can be used to allow only digits in the input text field. * * @author Jean Coravu */ public class NumberPlainDocument extends PlainDocument { private final int minimumNumber; private final int maximumNumber; /** * Constructs a new item by specifying the minimum number and the maximum number. * * @param minimumNumber the minimum number * @param maximumNumber the maximum number */ public NumberPlainDocument(int minimumNumber, int maximumNumber) { super(); this.minimumNumber = minimumNumber; this.maximumNumber = maximumNumber; } @Override public void insertString(int offs, String str, AttributeSet a) throws BadLocationException { StringBuilder text = new StringBuilder(); text.append(getText(0, offs)); text.append(str); text.append(getText(offs, getLength()-offs)); int startIndex = (text.charAt(0) == '-') ? 1 : 0; for (int i=startIndex; i<text.length(); i++) { if (!Character.isDigit(text.charAt(i))) { return; } } boolean canConvert = true; if (text.charAt(0) == '-' && text.length() == 1) { canConvert = false; } if (canConvert) { int number = Integer.parseInt(text.toString()); if (number < this.minimumNumber || number > this.maximumNumber) { return; } } super.insertString(offs, str, a); } }
1,714
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MoreOptionsForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/MoreOptionsForm.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.colormanip; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.swing.binding.Binding; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.datamodel.ImageInfo; import org.esa.snap.core.util.NamingConvention; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.color.ColorComboBox; import org.esa.snap.ui.color.ColorComboBoxAdapter; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.Color; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; public class MoreOptionsForm { static final String NO_DATA_COLOR_PROPERTY = "noDataColor"; static final String HISTOGRAM_MATCHING_PROPERTY = "histogramMatching"; private JPanel contentPanel; private GridBagConstraints constraints; private BindingContext bindingContext; private ColorManipulationChildForm childForm; private boolean hasHistogramMatching; private List<Row> contentRows; private static class Row { final JComponent label; final JComponent editor; private Row(JComponent label, JComponent editor) { this.label = label; this.editor = editor; } } MoreOptionsForm(ColorManipulationChildForm childForm, boolean hasHistogramMatching) { this.childForm = childForm; PropertyContainer propertyContainer = new PropertyContainer(); propertyContainer.addProperty(Property.create(NO_DATA_COLOR_PROPERTY, ImageInfo.NO_COLOR)); this.hasHistogramMatching = hasHistogramMatching; if (this.hasHistogramMatching) { propertyContainer.addProperty(Property.create(HISTOGRAM_MATCHING_PROPERTY, ImageInfo.HistogramMatching.None)); propertyContainer.getDescriptor(HISTOGRAM_MATCHING_PROPERTY).setNotNull(true); propertyContainer.getDescriptor(HISTOGRAM_MATCHING_PROPERTY).setValueSet( new ValueSet( new ImageInfo.HistogramMatching[]{ ImageInfo.HistogramMatching.None, ImageInfo.HistogramMatching.Equalize, ImageInfo.HistogramMatching.Normalize, } ) ); } contentPanel = new JPanel(new GridBagLayout()); contentRows = new ArrayList<>(); constraints = new GridBagConstraints(); constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.NORTHWEST; constraints.weightx = 0.5; constraints.weighty = 0.0; constraints.insets = new Insets(1, 0, 1, 0); bindingContext = new BindingContext(propertyContainer); JLabel noDataColorLabel = new JLabel("No-data " + NamingConvention.COLOR_LOWER_CASE + ": "); ColorComboBox noDataColorComboBox = new ColorComboBox(); Binding noDataColorBinding = bindingContext.bind(NO_DATA_COLOR_PROPERTY, new ColorComboBoxAdapter(noDataColorComboBox)); noDataColorBinding.addComponent(noDataColorLabel); addRow(noDataColorLabel, noDataColorComboBox); if (this.hasHistogramMatching) { JLabel histogramMatchingLabel = new JLabel("Histogram matching: "); JComboBox histogramMatchingBox = new JComboBox(); Binding histogramMatchingBinding = bindingContext.bind(HISTOGRAM_MATCHING_PROPERTY, histogramMatchingBox); histogramMatchingBinding.addComponent(histogramMatchingLabel); addRow(histogramMatchingLabel, histogramMatchingBox); } bindingContext.addPropertyChangeListener(evt -> { final ImageInfo.HistogramMatching matching = getHistogramMatching(); if (matching != null && matching != ImageInfo.HistogramMatching.None) { final String message = "<html>Histogram matching will be applied to the currently displayed image.<br/>" + "Sample values of the " + NamingConvention.COLOR_LOWER_CASE + " palette will no longer translate into<br/>" + "their associated " + NamingConvention.COLOR_LOWER_CASE + "s.</html>"; Dialogs.showInformation("Histogram Matching", message, "warningHistogramMatching"); } updateModel(); }); } private ImageInfo getImageInfo() { return getParentForm().getFormModel().getModifiedImageInfo(); } public ColorManipulationForm getParentForm() { return childForm.getParentForm(); } public ColorManipulationChildForm getChildForm() { return childForm; } public BindingContext getBindingContext() { return bindingContext; } public void insertRow(int index, JLabel label, JComponent editor) { if (contentRows != null) { contentRows.add(index, new Row(label, editor)); } else { addRowImpl(label, editor); } } public void addRow(JLabel label, JComponent editor) { if (contentRows != null) { contentRows.add(new Row(label, editor)); } else { addRowImpl(label, editor); } } public void addRow(JComponent editor) { if (contentRows != null) { contentRows.add(new Row(null, editor)); } else { addRowImpl(null, editor); } } private void addRowImpl(JComponent label, JComponent editor) { constraints.gridy++; constraints.gridx = 0; if (label == null){ constraints.gridwidth = 2; contentPanel.add(editor, constraints); } else { constraints.gridwidth = 1; contentPanel.add(label, constraints); constraints.gridx = 1; contentPanel.add(editor, constraints); } } public void updateForm() { setNoDataColor(getImageInfo().getNoDataColor()); if (hasHistogramMatching) { setHistogramMatching(getImageInfo().getHistogramMatching()); } getParentForm().getFormModel().updateMoreOptionsFromImageInfo(this); } public void updateModel() { getImageInfo().setNoDataColor(getNoDataColor()); if (hasHistogramMatching) { getImageInfo().setHistogramMatching(getHistogramMatching()); } getParentForm().getFormModel().updateImageInfoFromMoreOptions(this); getParentForm().applyChanges(); } public JPanel getContentPanel() { if (contentRows != null) { Row[] rows = contentRows.toArray(new Row[contentRows.size()]); for (Row row : rows) { addRowImpl(row.label, row.editor); } contentRows.clear(); contentRows = null; } return contentPanel; } public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener) { bindingContext.addPropertyChangeListener(propertyChangeListener); } public void addPropertyChangeListener(String propertyName, PropertyChangeListener propertyChangeListener) { bindingContext.addPropertyChangeListener(propertyName, propertyChangeListener); } private Color getNoDataColor() { return (Color) getBindingContext().getBinding(NO_DATA_COLOR_PROPERTY).getPropertyValue(); } private void setNoDataColor(Color color) { getBindingContext().getBinding(NO_DATA_COLOR_PROPERTY).setPropertyValue(color); } private ImageInfo.HistogramMatching getHistogramMatching() { Binding binding = getBindingContext().getBinding(HISTOGRAM_MATCHING_PROPERTY); return binding != null ? (ImageInfo.HistogramMatching) binding.getPropertyValue() : null; } private void setHistogramMatching(ImageInfo.HistogramMatching histogramMatching) { Binding binding = getBindingContext().getBinding(HISTOGRAM_MATCHING_PROPERTY); if (binding != null) { binding.setPropertyValue(histogramMatching); } } }
9,043
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BrightnessContrastData.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/BrightnessContrastData.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.ImageInfo; import org.esa.snap.core.datamodel.RasterDataNode; import java.util.HashMap; import java.util.Map; /** * The <code>BrightnessContrastData</code> class is used to store the initial image info of the band and slider values. * * @author Jean Coravu */ public class BrightnessContrastData { private final Map<RasterDataNode, ImageInfo> initialImageInfoMap; private ImageInfo initialImageInfo; private int brightnessSliderValue; private int contrastSliderValue; private int saturationSliderValue; /** * Constructs a new item. * * @param initialImageInfo the initial image info of the displayed band */ public BrightnessContrastData(ImageInfo initialImageInfo) { this.initialImageInfoMap = new HashMap<>(); this.initialImageInfo = initialImageInfo; this.brightnessSliderValue = 0; this.contrastSliderValue = 0; this.saturationSliderValue = 0; } public void putImageInfo(RasterDataNode rasterDataNode, ImageInfo imageInfo) { this.initialImageInfoMap.put(rasterDataNode, imageInfo); } public ImageInfo getInitialImageInfo(RasterDataNode rasterDataNode) { return this.initialImageInfoMap.get(rasterDataNode); } /** * Returns the initial image info. * * @return the initial image info, should never be <code>null</code> */ public ImageInfo getInitialImageInfo() { return initialImageInfo; } /** * Returns the brightness slider value. * * @return the brightness slider value */ public int getBrightnessSliderValue() { return brightnessSliderValue; } /** * Returns the contrast slider value. * * @return the contrast slider value */ public int getContrastSliderValue() { return contrastSliderValue; } /** * Returns the saturation slider value. * * @return the saturation slider value */ public int getSaturationSliderValue() { return saturationSliderValue; } /** * Sets the initial image info, before changing the current image info of the displayed band. * * @param initialImageInfo the initial image info */ public void setInitialImageInfo(ImageInfo initialImageInfo) { this.initialImageInfo = initialImageInfo; } /** * Sets the slider values. * * @param brightnessSliderValue the brightness slider value * @param contrastSliderValue the contrast slider value * @param saturationSliderValue the saturation slider value */ public void setSliderValues(int brightnessSliderValue, int contrastSliderValue, int saturationSliderValue) { this.brightnessSliderValue = brightnessSliderValue; this.contrastSliderValue = contrastSliderValue; this.saturationSliderValue = saturationSliderValue; } }
2,967
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorSchemeLookupInfo.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorSchemeLookupInfo.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.ColorSchemeInfo; /** * Contains all info for a color scheme lookup * * @author Daniel Knowles (NASA) * @date Jan 2020 */ public class ColorSchemeLookupInfo { private String regex; private String[] regexArray; private String scheme_id; private ColorSchemeInfo colorSchemeInfo; private String description; public ColorSchemeLookupInfo(String regex, String scheme_id, String description, ColorSchemeInfo colorSchemeInfo) { if (regex != null && scheme_id != null) { setRegex(regex); setScheme_id(scheme_id); setDescription(description); setColorSchemeInfo(colorSchemeInfo); setRegexArray(regex); } } public String getRegex() { return regex; } public void setRegex(String regex) { this.regex = regex; } public String[] getRegexArray() { return regexArray; } public void setRegexArray(String regex) { if (regex != null && regex.length() > 0) { String wildcard = ","; String regexArray[] = regex.split(wildcard); for (int i=0; i < regexArray.length-1; i++) { regexArray[i] = regexArray[i].trim(); } this.regexArray = regexArray; } else { this.regexArray = null; } } public String getScheme_id() { return scheme_id; } public void setScheme_id(String scheme_id) { this.scheme_id = scheme_id; } public ColorSchemeInfo getColorSchemeInfo() { return colorSchemeInfo; } public void setColorSchemeInfo(ColorSchemeInfo colorSchemeInfo) { this.colorSchemeInfo = colorSchemeInfo; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isMatch(String bandName, String regex) { boolean match = false; if (bandName == null || bandName.length() == 0) { return false; } if (regex == null || regex.length() == 0) { return false; } final String WILDCARD = new String("*"); regex = regex.trim(); if (bandName.equals(regex)) { match = true; } else if (regex.contains(WILDCARD)) { if (!regex.startsWith(WILDCARD) && regex.endsWith(WILDCARD)) { String basename = regex.substring(0, regex.length() - 1); if (bandName.startsWith(basename)) { match = true; } } else if (regex.startsWith(WILDCARD) && !regex.endsWith(WILDCARD)) { String basename = regex.substring(1, regex.length()); if (bandName.endsWith(basename)) { match = true; } } else if (regex.startsWith(WILDCARD) && regex.endsWith(WILDCARD)) { String basename = regex.substring(1, regex.length() - 1); if (bandName.contains(basename)) { match = true; } } else { String basename = regex; String wildcard = "\\*"; String basenameSplit[] = basename.split(wildcard); if (basenameSplit.length == 2 && basenameSplit[0].length() > 0 && basenameSplit[1].length() > 0) { if (bandName.startsWith(basenameSplit[0]) && bandName.endsWith(basenameSplit[1])) { match = true; } } } } return match; } public boolean isMatch(String bandName) { boolean match = false; if (bandName == null || bandName.length() == 0) { return false; } for (String regex: getRegexArray()) { match = isMatch(bandName, regex); if (match) { break; } } return match; } }
4,046
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageInfoEditorSupport.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ImageInfoEditorSupport.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.colormanip; import com.bc.ceres.core.runtime.internal.Platform; import org.esa.snap.core.datamodel.ColorManipulationDefaults; import org.esa.snap.core.datamodel.ColorSchemeInfo; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.ui.tool.ToolButtonFactory; import org.openide.util.ImageUtilities; import javax.swing.AbstractButton; /** * @author Brockmann Consult * @author Daniel Knowles (NASA) */ // FEB 2020 - Knowles // - Added additional autoStretch buttons // - Modified handling of the horizontal zoom with a single toggle button // - Added method and call to resetSchemeSelector() // - Added button for setting range (0,1) useful for in RGB window for reflectance bands class ImageInfoEditorSupport { final AbstractButton autoStretch1SigmaButton; final AbstractButton autoStretch2SigmaButton; final AbstractButton autoStretch3SigmaButton; final AbstractButton autoStretch95Button; final AbstractButton autoStretch100Button; final AbstractButton zoomInVButton; final AbstractButton zoomOutVButton; final AbstractButton zoomInHButton; final AbstractButton zoomOutHButton; final AbstractButton showExtraInfoButton; final AbstractButton setRGBminmax; final AbstractButton zoomHorizontalButton; final AbstractButton zoomVerticalButton; final ImageInfoEditor2 imageInfoEditor; ColorManipulationForm form; final Boolean[] horizontalZoomButtonEnabled = {true}; protected ImageInfoEditorSupport(ImageInfoEditor2 imageInfoEditor, boolean zoomDefault) { this.imageInfoEditor = imageInfoEditor; this.form = imageInfoEditor.getParentForm(); autoStretch1SigmaButton = createButton("org/esa/snap/rcp/icons/Auto1SigmaPercent24.gif"); autoStretch1SigmaButton.setName("AutoStretch1SigmaButton"); autoStretch1SigmaButton.setToolTipText("Auto-adjust to 1 sigma (68.27%) of all pixels"); autoStretch1SigmaButton.addActionListener(form.wrapWithAutoApplyActionListener(e -> compute1SigmaPercent())); autoStretch2SigmaButton = createButton("org/esa/snap/rcp/icons/Auto2SigmaPercent24.gif"); autoStretch2SigmaButton.setName("AutoStretch2SigmaButton"); autoStretch2SigmaButton.setToolTipText("Auto-adjust to 2 sigma (95.45%) of all pixels"); autoStretch2SigmaButton.addActionListener(form.wrapWithAutoApplyActionListener(e -> compute2SigmaPercent())); autoStretch3SigmaButton = createButton("org/esa/snap/rcp/icons/Auto3SigmaPercent24.gif"); autoStretch3SigmaButton.setName("AutoStretch3SigmaButton"); autoStretch3SigmaButton.setToolTipText("Auto-adjust to 3 sigma (99.73%) of all pixels"); autoStretch3SigmaButton.addActionListener(form.wrapWithAutoApplyActionListener(e -> compute3SigmaPercent())); autoStretch95Button = createButton("org/esa/snap/rcp/icons/Auto95Percent24.gif"); autoStretch95Button.setName("AutoStretch95Button"); autoStretch95Button.setToolTipText("Auto-adjust to 95% of all pixels"); autoStretch95Button.addActionListener(form.wrapWithAutoApplyActionListener(e -> compute95Percent())); autoStretch100Button = createButton("org/esa/snap/rcp/icons/Auto100Percent24.gif"); autoStretch100Button.setName("AutoStretch100Button"); autoStretch100Button.setToolTipText("Auto-adjust to 100% of all pixels"); autoStretch100Button.addActionListener(form.wrapWithAutoApplyActionListener(e -> compute100Percent())); setRGBminmax = createButton("org/esa/snap/rcp/icons/AutoPresetRange24.png"); setRGBminmax.setName("setRGBminmax"); final String optionsLocation = getOptionsLocation(); setRGBminmax.setToolTipText("<html>Set channel range with pre-set values (see " + optionsLocation + ")</html>"); /*I18N*/ setRGBminmax.addActionListener(form.wrapWithAutoApplyActionListener(e -> setRGBminmax())); zoomInVButton = createButton("org/esa/snap/rcp/icons/ZoomIn24V.gif"); zoomInVButton.setName("zoomInVButton"); zoomInVButton.setToolTipText("Stretch histogram vertically"); zoomInVButton.addActionListener(e -> imageInfoEditor.computeZoomInVertical()); zoomOutVButton = createButton("org/esa/snap/rcp/icons/ZoomOut24V.gif"); zoomOutVButton.setName("zoomOutVButton"); zoomOutVButton.setToolTipText("Shrink histogram vertically"); zoomOutVButton.addActionListener(e -> imageInfoEditor.computeZoomOutVertical()); zoomInHButton = createButton("org/esa/snap/rcp/icons/ZoomIn24H.gif"); zoomInHButton.setName("zoomInHButton"); zoomInHButton.setToolTipText("Stretch histogram horizontally"); zoomInHButton.addActionListener(e -> imageInfoEditor.computeZoomInToSliderLimits()); zoomOutHButton = createButton("org/esa/snap/rcp/icons/ZoomOut24H.gif"); zoomOutHButton.setName("zoomOutHButton"); zoomOutHButton.setToolTipText("Shrink histogram horizontally"); zoomOutHButton.addActionListener(e -> imageInfoEditor.computeZoomOutToFullHistogramm()); zoomHorizontalButton = createToggleButton("org/esa/snap/rcp/icons/ZoomHorizontal24.gif"); zoomHorizontalButton.setName("zoomHorizontalButton"); zoomHorizontalButton.setToolTipText("Expand and shrink histogram horizontally"); zoomHorizontalButton.setSelected(zoomDefault); zoomHorizontalButton.addActionListener(e -> handleHorizontalZoomButton()); zoomVerticalButton = createToggleButton("org/esa/snap/rcp/icons/ZoomVertical24.gif"); zoomVerticalButton.setName("zoomVerticalButton"); zoomVerticalButton.setToolTipText("Expand and shrink histogram vertically"); zoomVerticalButton.addActionListener(e -> handleVerticalZoom()); showExtraInfoButton = createToggleButton("org/esa/snap/rcp/icons/Information24.gif"); showExtraInfoButton.setName("ShowExtraInfoButton"); showExtraInfoButton.setToolTipText("Show extra information"); showExtraInfoButton.setSelected(imageInfoEditor.getShowExtraInfo()); showExtraInfoButton.addActionListener(e -> imageInfoEditor.setShowExtraInfo(showExtraInfoButton.isSelected())); } private void resetSchemeSelector() { ColorSchemeInfo colorSchemeNoneInfo = ColorSchemeManager.getDefault().getNoneColorSchemeInfo(); form.getFormModel().getProductSceneView().getImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); form.getFormModel().getModifiedImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); } public void handleVerticalZoom() { if (zoomVerticalButton.isSelected()) { imageInfoEditor.computeZoomInVertical(); } else { imageInfoEditor.computeZoomOutVertical(); } } public void setHorizontalZoomButtonAndCompute(boolean zoomToHistLimits) { if (zoomToHistLimits != zoomHorizontalButton.isSelected()) { boolean tmp = horizontalZoomButtonEnabled[0]; horizontalZoomButtonEnabled[0] = false; zoomHorizontalButton.setSelected(zoomToHistLimits); horizontalZoomButtonEnabled[0] = tmp;; } computeHorizontalZoom(zoomToHistLimits); } private void computeHorizontalZoom(boolean zoomToHistLimits) { if (zoomToHistLimits) { imageInfoEditor.computeZoomInToSliderLimits(); } else { imageInfoEditor.computeZoomOutToFullHistogramm(); } } public void handleHorizontalZoomButton() { if (horizontalZoomButtonEnabled[0]) { form.getFormModel().getProductSceneView().getImageInfo().setZoomToHistLimits(zoomHorizontalButton.isSelected()); form.getFormModel().getModifiedImageInfo().setZoomToHistLimits(zoomHorizontalButton.isSelected()); computeHorizontalZoom(zoomHorizontalButton.isSelected()); } } // this should get a common place. Maybe in Platform? Not sure, so it stays here for now. private String getOptionsLocation() { String optionsLocation = "Tools/Options"; final Platform currentPlatform = Platform.getCurrentPlatform(); if (currentPlatform != null && currentPlatform.getId() == Platform.ID.macosx) { optionsLocation = "App Menu/Preferences"; } return optionsLocation; } private void compute1SigmaPercent() { computePercent(68.27); } private void compute2SigmaPercent() { computePercent(95.45); } private void compute3SigmaPercent() { computePercent(99.73); } private void compute95Percent() { computePercent(95.0); } private void computePercent(double threshold) { resetSchemeSelector(); if (!imageInfoEditor.computePercent(form.getFormModel().getProductSceneView().getImageInfo().isLogScaled(), threshold)) { ColorUtils.showErrorDialog("INPUT ERROR!!: Cannot set slider value below zero with log scaling"); } } private void setRGBminmax() { PropertyMap configuration = form.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); double rgbMin = configuration.getPropertyDouble(ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_KEY, ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_DEFAULT); double rgbMax = configuration.getPropertyDouble(ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_KEY, ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_DEFAULT); imageInfoEditor.setRGBminmax(rgbMin, rgbMax); } private void compute100Percent() { resetSchemeSelector(); if (!imageInfoEditor.compute100Percent(form.getFormModel().getProductSceneView().getImageInfo().isLogScaled())) { ColorUtils.showErrorDialog("INPUT ERROR!!: Cannot set slider value below zero with log scaling"); } } public static AbstractButton createToggleButton(String s) { return ToolButtonFactory.createButton(ImageUtilities.loadImageIcon(s, false), true); } public static AbstractButton createButton(String s) { return ToolButtonFactory.createButton(ImageUtilities.loadImageIcon(s, false), false); } }
10,984
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorPaletteManager.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorPaletteManager.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.ColorPaletteDef; import org.esa.snap.core.util.SystemUtils; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; class ColorPaletteManager { static ColorPaletteManager manager = new ColorPaletteManager(); private List<ColorPaletteDef> cpdList; private List<String> cpdNames; public static ColorPaletteManager getDefault() { return manager; } ColorPaletteManager() { cpdList = new ArrayList<>(); cpdNames = new ArrayList<>(); } public void loadAvailableColorPalettes(File palettesDir) { cpdNames.clear(); cpdList.clear(); final File[] files = palettesDir.listFiles((dir, name) -> { return name.toLowerCase().endsWith(".cpd") || name.toLowerCase().endsWith(".cpt"); }); if (files != null) { for (File file : files) { try { ColorPaletteDef newCpd; if (file.getName().endsWith("cpt")) { newCpd = ColorPaletteDef.loadCpt(file); } else { newCpd = ColorPaletteDef.loadColorPaletteDef(file); } cpdList.add(newCpd); cpdNames.add(file.getName()); } catch (IOException e) { final Logger logger = SystemUtils.LOG; logger.warning("Unable to load color palette definition from file '" + file.getAbsolutePath() + "'"); logger.log(Level.INFO, e.getMessage(), e); } } } } public List<ColorPaletteDef> getColorPaletteDefList() { return Collections.unmodifiableList(cpdList); } public String getNameFor(ColorPaletteDef cpdForRaster) { for (int i = 0; i < cpdList.size(); i++) { ColorPaletteDef colorPaletteDef = cpdList.get(i); if (colorPaletteDef == cpdForRaster) return cpdNames.get(i); } return null; } }
2,223
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Continuous1BandTabularForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/Continuous1BandTabularForm.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.colormanip; import com.bc.ceres.binding.ValueRange; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.NamingConvention; import org.esa.snap.ui.color.ColorTableCellEditor; import org.esa.snap.ui.color.ColorTableCellRenderer; import javax.swing.AbstractButton; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.event.TableModelListener; import javax.swing.table.AbstractTableModel; import java.awt.Color; import java.awt.Component; /** * * @author Brockmann Consult * @author Daniel Knowles (NASA) * @author Bing Yang (NASA) */ // OCT 2019 - Knowles / Yang // - Added checks to ensure that only positive values are allowed in log scaling mode. // - Added checks to ensure that palette values are numeric. // - Added checks to ensure that value entries are numerically between the adjacent values. // FEB 2020 - Knowles // - Added call to reset the color scheme to 'none' // - Added log button public class Continuous1BandTabularForm implements ColorManipulationChildForm { private static final String[] COLUMN_NAMES = new String[]{NamingConvention.COLOR_MIXED_CASE, "Value"}; private static final Class<?>[] COLUMN_TYPES = new Class<?>[]{Color.class, String.class}; private final ColorManipulationForm parentForm; private ImageInfoTableModel tableModel; private JScrollPane contentPanel; private final MoreOptionsForm moreOptionsForm; private TableModelListener tableModelListener; private final DiscreteCheckBox discreteCheckBox; private final AbstractButton logButton; final Boolean[] logButtonClicked = {false}; public Continuous1BandTabularForm(final ColorManipulationForm parentForm) { this.parentForm = parentForm; tableModel = new ImageInfoTableModel(); tableModelListener = e -> { tableModel.removeTableModelListener(tableModelListener); parentForm.applyChanges(); tableModel.addTableModelListener(tableModelListener); }; logButton = LogDisplay.createButton(); logButton.addActionListener(e -> { if (!logButtonClicked[0]) { logButtonClicked[0] = true; applyChangesLogToggle(); logButtonClicked[0] = false; } }); moreOptionsForm = new MoreOptionsForm(this, parentForm.getFormModel().canUseHistogramMatching()); discreteCheckBox = new DiscreteCheckBox(parentForm); moreOptionsForm.addRow(discreteCheckBox); parentForm.getFormModel().modifyMoreOptionsForm(moreOptionsForm); final JTable table = new JTable(tableModel); table.setDefaultRenderer(Color.class, new ColorTableCellRenderer()); table.setDefaultEditor(Color.class, new ColorTableCellEditor()); table.getTableHeader().setReorderingAllowed(false); table.getColumnModel().getColumn(0).setPreferredWidth(140); table.getColumnModel().getColumn(1).setPreferredWidth(140); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); final JScrollPane tableScrollPane = new JScrollPane(table); tableScrollPane.getViewport().setPreferredSize(table.getPreferredSize()); contentPanel = tableScrollPane; } @Override public ColorManipulationForm getParentForm() { return parentForm; } @Override public void handleFormShown(ColorFormModel formModel) { updateFormModel(formModel); tableModel.addTableModelListener(tableModelListener); } @Override public AbstractButton[] getToolButtons() { return new AbstractButton[]{ logButton }; } @Override public void handleFormHidden(ColorFormModel formModel) { tableModel.removeTableModelListener(tableModelListener); } @Override public void updateFormModel(ColorFormModel formModel) { final ImageInfo imageInfo = formModel.getOriginalImageInfo(); final ColorPaletteDef cpd = imageInfo.getColorPaletteDef(); final boolean logScaled = imageInfo.isLogScaled(); final boolean discrete = cpd.isDiscrete(); if (logScaled != logButton.isSelected()) { logButton.setSelected(logScaled); } tableModel.fireTableDataChanged(); discreteCheckBox.setDiscreteColorsMode(parentForm.getFormModel().getModifiedImageInfo().getColorPaletteDef().isDiscrete()); } @Override public void resetFormModel(ColorFormModel formModel) { tableModel.fireTableDataChanged(); } @Override public void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster) { } @Override public Component getContentPanel() { return contentPanel; } @Override public MoreOptionsForm getMoreOptionsForm() { return moreOptionsForm; } @Override public RasterDataNode[] getRasters() { return parentForm.getFormModel().getRasters(); } private class ImageInfoTableModel extends AbstractTableModel { private ImageInfoTableModel() { } public ImageInfo getImageInfo() { return parentForm.getFormModel().getModifiedImageInfo(); } @Override public String getColumnName(int columnIndex) { return COLUMN_NAMES[columnIndex]; } @Override public Class<?> getColumnClass(int columnIndex) { return COLUMN_TYPES[columnIndex]; } public int getColumnCount() { return COLUMN_NAMES.length; } @Override public int getRowCount() { if (getImageInfo() == null) { return 0; } return getImageInfo().getColorPaletteDef().getNumPoints(); } @Override public Object getValueAt(int rowIndex, int columnIndex) { final ColorPaletteDef.Point point = getImageInfo().getColorPaletteDef().getPointAt(rowIndex); if (columnIndex == 0) { final Color color = point.getColor(); return color.equals(ImageInfo.NO_COLOR) ? null : color; } else if (columnIndex == 1) { return point.getSample(); } return null; } @Override public void setValueAt(Object aValue, int rowIndex, int columnIndex) { resetSchemeSelector(); final ColorPaletteDef.Point point = getImageInfo().getColorPaletteDef().getPointAt(rowIndex); final ValueRange valueRange; if (rowIndex == 0) { valueRange = new ValueRange(Double.NEGATIVE_INFINITY, getImageInfo().getColorPaletteDef().getPointAt(1).getSample()); } else if (rowIndex == getImageInfo().getColorPaletteDef().getNumPoints() - 1) { valueRange = new ValueRange(getImageInfo().getColorPaletteDef().getPointAt(rowIndex - 1).getSample(), Double.POSITIVE_INFINITY); } else { valueRange = new ValueRange(getImageInfo().getColorPaletteDef().getPointAt(rowIndex - 1).getSample(), getImageInfo().getColorPaletteDef().getPointAt(rowIndex + 1).getSample()); } if (columnIndex == 0) { final Color color = (Color) aValue; point.setColor(color == null ? ImageInfo.NO_COLOR : color); fireTableCellUpdated(rowIndex, columnIndex); } else if (columnIndex == 1) { if (ColorUtils.isNumber((String) aValue, "Table value", true)) { double aValueDouble = Double.parseDouble((String) aValue); if (ColorUtils.checkTableRangeCompatibility(aValueDouble, valueRange.getMin(), valueRange.getMax()) && ColorUtils.checkLogCompatibility(aValueDouble, "Value", parentForm.getFormModel().getModifiedImageInfo().isLogScaled())) { point.setSample(aValueDouble); fireTableCellUpdated(rowIndex, columnIndex); } } } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0 || columnIndex == 1; } } private void resetSchemeSelector() { ColorSchemeInfo colorSchemeNoneInfo = ColorSchemeManager.getDefault().getNoneColorSchemeInfo(); parentForm.getFormModel().getProductSceneView().getImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); parentForm.getFormModel().getModifiedImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); } private void applyChangesLogToggle() { final ImageInfo currentInfo = parentForm.getFormModel().getModifiedImageInfo(); final ColorPaletteDef currentCPD = currentInfo.getColorPaletteDef(); final boolean sourceLogScaled = currentInfo.isLogScaled(); final boolean targetLogScaled = logButton.isSelected(); final double min = currentCPD.getMinDisplaySample(); final double max = currentCPD.getMaxDisplaySample(); final ColorPaletteDef cpd = currentCPD; final boolean autoDistribute = true; if (ColorUtils.checkRangeCompatibility(min, max, targetLogScaled)) { resetSchemeSelector(); currentInfo.setColorPaletteDef(cpd, min, max, autoDistribute, sourceLogScaled, targetLogScaled); parentForm.applyChanges(); } else { logButton.setSelected(false); } } }
10,322
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorManipulationTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorManipulationTopComponent.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.colormanip; import org.esa.snap.core.datamodel.ColorManipulationDefaults; 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 java.awt.BorderLayout; @TopComponent.Description( preferredID = "ColorManipulationTopComponent", iconBase = "org/esa/snap/rcp/icons/ContrastStretch.gif", persistenceType = TopComponent.PERSISTENCE_ALWAYS ) @TopComponent.Registration( mode = "navigator", openAtStartup = true, position = 20 ) @ActionID(category = "Window", id = "org.esa.snap.rcp.colormanip.ColorManipulationTopComponent") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 40), @ActionReference(path = "Toolbars/Tool Windows") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_ColorManipulationTopComponent_Name", preferredID = "ColorManipulationTopComponent" ) @NbBundle.Messages({ "CTL_ColorManipulationTopComponent_Name=" + ColorManipulationDefaults.TOOLNAME_COLOR_MANIPULATION, "CTL_ColorManipulationTopComponent_ComponentName=" + ColorManipulationDefaults.TOOLNAME_COLOR_MANIPULATION }) /** * The color manipulation tool window. */ public class ColorManipulationTopComponent extends TopComponent implements HelpCtx.Provider { private static final String HELP_ID = "showColorManipulationWnd"; public ColorManipulationTopComponent() { setName(Bundle.CTL_ColorManipulationTopComponent_ComponentName()); ColorManipulationFormImpl cmf = new ColorManipulationFormImpl(this, new ColorFormModel()); setLayout(new BorderLayout()); add(cmf.getContentPanel(), BorderLayout.CENTER); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(HELP_ID); } }
2,677
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Continuous1BandSwitcherForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/Continuous1BandSwitcherForm.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.colormanip; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.RasterDataNode; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * * @author Brockmann Consult * @author Daniel Knowles (NASA) */ // OCT 2019 - Knowles // - Set basic mode to be the default public class Continuous1BandSwitcherForm implements ColorManipulationChildForm { private final ColorManipulationForm parentForm; private JPanel contentPanel; private ColorManipulationChildForm childForm; private JRadioButton graphicalButton; private Continuous1BandGraphicalForm graphicalPaletteEditorForm; private JRadioButton tabularButton; private Continuous1BandTabularForm tabularPaletteEditorForm; private JRadioButton basicButton; private Continuous1BandBasicForm basicPaletteEditorForm; public Boolean[] basicSwitcherIsActive = {false}; public Continuous1BandSwitcherForm(final ColorManipulationForm parentForm) { this.parentForm = parentForm; childForm = new EmptyImageInfoForm(parentForm); basicButton = new JRadioButton("Basic"); graphicalButton = new JRadioButton("Sliders"); tabularButton = new JRadioButton("Table"); final ButtonGroup editorGroup = new ButtonGroup(); editorGroup.add(basicButton); editorGroup.add(graphicalButton); editorGroup.add(tabularButton); basicButton.setSelected(true); final SwitcherActionListener switcherActionListener = new SwitcherActionListener(); basicButton.addActionListener(switcherActionListener); graphicalButton.addActionListener(switcherActionListener); tabularButton.addActionListener(switcherActionListener); final JPanel editorSwitcherPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 2, 2)); editorSwitcherPanel.add(new JLabel("Editor:")); editorSwitcherPanel.add(basicButton); editorSwitcherPanel.add(graphicalButton); editorSwitcherPanel.add(tabularButton); final JPanel northPanel = new JPanel(new BorderLayout(2, 2)); northPanel.add(editorSwitcherPanel, BorderLayout.WEST); contentPanel = new JPanel(new BorderLayout()); contentPanel.add(northPanel, BorderLayout.NORTH); } @Override public ColorManipulationForm getParentForm() { return parentForm; } @Override public void handleFormShown(ColorFormModel formModel) { switchForm(); } @Override public void handleFormHidden(ColorFormModel formModel) { childForm.handleFormHidden(formModel); } @Override public void updateFormModel(ColorFormModel formModel) { childForm.updateFormModel(formModel); } @Override public void resetFormModel(ColorFormModel formModel) { childForm.resetFormModel(formModel); } @Override public void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster) { childForm.handleRasterPropertyChange(event, raster); } @Override public MoreOptionsForm getMoreOptionsForm() { return childForm.getMoreOptionsForm(); } @Override public RasterDataNode[] getRasters() { return childForm.getRasters(); } private void switchForm() { final ColorManipulationChildForm oldForm = childForm; final ColorManipulationChildForm newForm; if (tabularButton.isSelected()) { if (tabularPaletteEditorForm == null) { tabularPaletteEditorForm = new Continuous1BandTabularForm(parentForm); } newForm = tabularPaletteEditorForm; } else if (basicButton.isSelected()) { if (basicPaletteEditorForm == null) { basicPaletteEditorForm = new Continuous1BandBasicForm(parentForm, basicSwitcherIsActive); } newForm = basicPaletteEditorForm; } else { if (graphicalPaletteEditorForm == null) { graphicalPaletteEditorForm = new Continuous1BandGraphicalForm(parentForm); } newForm = graphicalPaletteEditorForm; } if (oldForm != newForm) { oldForm.handleFormHidden(parentForm.getFormModel()); childForm = newForm; childForm.handleFormShown(parentForm.getFormModel()); contentPanel.remove(oldForm.getContentPanel()); contentPanel.add(childForm.getContentPanel(), BorderLayout.CENTER); boolean installAllButtons = !(newForm instanceof Continuous1BandGraphicalForm || newForm instanceof Continuous3BandGraphicalForm); parentForm.installToolButtons(installAllButtons); parentForm.installMoreOptions(); parentForm.revalidateToolViewPaneControl(); } else { childForm.updateFormModel(parentForm.getFormModel()); } } @Override public AbstractButton[] getToolButtons() { return childForm.getToolButtons(); } @Override public Component getContentPanel() { return contentPanel; } private class SwitcherActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { basicSwitcherIsActive[0] = true; switchForm(); basicSwitcherIsActive[0] = false; } } }
6,385
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BrightnessContrastPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/BrightnessContrastPanel.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.*; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.product.ProductSceneView; import org.netbeans.api.annotations.common.NonNull; import javax.swing.*; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeListener; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeListener; import java.util.HashMap; import java.util.Map; /** * Created by jcoravu on 9/27/2016. */ class BrightnessContrastPanel extends JPanel { private final ColorManipulationForm parentForm; private SliderPanel brightnessPanel; private SliderPanel contrastPanel; private SliderPanel saturationPanel; private PropertyChangeListener imageInfoChangeListener; private Map<ProductSceneView, BrightnessContrastData> visibleProductScenes; BrightnessContrastPanel(ColorManipulationForm parentForm) { super(new BorderLayout()); this.parentForm = parentForm; ChangeListener sliderChangeListener = event -> applySliderValues(); this.brightnessPanel = new SliderPanel("Brightness", sliderChangeListener); this.contrastPanel = new SliderPanel("Contrast", sliderChangeListener); this.saturationPanel = new SliderPanel("Saturation", sliderChangeListener); int maximumPreferredWidth = Math.max(this.brightnessPanel.getTitlePreferredWidth(), this.contrastPanel.getTitlePreferredWidth()); maximumPreferredWidth = Math.max(maximumPreferredWidth, this.saturationPanel.getTitlePreferredWidth()); this.saturationPanel.setTitlePreferredWidth(maximumPreferredWidth); this.contrastPanel.setTitlePreferredWidth(maximumPreferredWidth); this.saturationPanel.setTitlePreferredWidth(maximumPreferredWidth); this.visibleProductScenes = new HashMap<>(); this.imageInfoChangeListener = event -> { ImageInfo modifiedImageInfo = (ImageInfo) event.getNewValue(); ProductSceneView selectedSceneView = (ProductSceneView)event.getSource(); sceneImageInfoChangedOutside(selectedSceneView, modifiedImageInfo); }; JPanel colorsPanel = new JPanel(new GridLayout(3, 1, 0, 15)); colorsPanel.setBorder(new EmptyBorder(5, 5, 0, 0)); colorsPanel.add(this.brightnessPanel); colorsPanel.add(this.contrastPanel); colorsPanel.add(this.saturationPanel); JButton resetButton = new JButton("Reset"); resetButton.setFocusable(false); resetButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent event) { resetSliderValues(); } }); JPanel componentsPanel = new JPanel(); componentsPanel.setLayout(new BoxLayout(componentsPanel, BoxLayout.Y_AXIS)); componentsPanel.add(colorsPanel); componentsPanel.add(resetButton); JScrollPane scrollPane = new JScrollPane(componentsPanel); scrollPane.setBorder(new EmptyBorder(0, 0, 0, 0)); add(scrollPane, BorderLayout.NORTH); } public void productSceneViewSelected(@NonNull ProductSceneView selectedSceneView) { selectedSceneView.addPropertyChangeListener(ProductSceneView.PROPERTY_NAME_IMAGE_INFO, this.imageInfoChangeListener); BrightnessContrastData brightnessContrastData = this.visibleProductScenes.get(selectedSceneView); if (brightnessContrastData == null) { RasterDataNode[] rasterDataNodes = selectedSceneView.getSceneImage().getRasters(); ImageInfo initialImageInfo = selectedSceneView.getImageInfo().clone(); brightnessContrastData = new BrightnessContrastData(initialImageInfo); for (int i=0; i<rasterDataNodes.length; i++) { ImageInfo nodeImageInfo = rasterDataNodes[i].getImageInfo().clone(); brightnessContrastData.putImageInfo(rasterDataNodes[i], nodeImageInfo); } this.visibleProductScenes.put(selectedSceneView, brightnessContrastData); } RGBChannelDef initialRGBChannelDef = brightnessContrastData.getInitialImageInfo().getRgbChannelDef(); boolean enableSaturationPanel = (initialRGBChannelDef != null); this.saturationPanel.setEnabled(enableSaturationPanel); refreshSliderValues(brightnessContrastData); } public void productSceneViewDeselected(@NonNull ProductSceneView deselectedSceneView) { deselectedSceneView.removePropertyChangeListener(ProductSceneView.PROPERTY_NAME_IMAGE_INFO, this.imageInfoChangeListener); } private void resetSliderValues() { ProductSceneView selectedSceneView = getSelectedProductSceneView(); BrightnessContrastData brightnessContrastData = this.visibleProductScenes.get(selectedSceneView); brightnessContrastData.setSliderValues(0, 0, 0); refreshSliderValues(brightnessContrastData); applySliderValues(); } private void refreshSliderValues(BrightnessContrastData brightnessContrastData) { this.brightnessPanel.setSliderValue(brightnessContrastData.getBrightnessSliderValue()); this.contrastPanel.setSliderValue(brightnessContrastData.getContrastSliderValue()); this.saturationPanel.setSliderValue(brightnessContrastData.getSaturationSliderValue()); } private void sceneImageInfoChangedOutside(ProductSceneView selectedSceneView, ImageInfo modifiedImageInfo) { BrightnessContrastData brightnessContrastData = this.visibleProductScenes.get(selectedSceneView); ImageInfo initialImageInfo = modifiedImageInfo.clone(); brightnessContrastData.setInitialImageInfo(initialImageInfo); brightnessContrastData.setSliderValues(0, 0, 0); refreshSliderValues(brightnessContrastData); } private ProductSceneView getSelectedProductSceneView() { return SnapApp.getDefault().getSelectedProductSceneView(); } private void applySliderValues() { ProductSceneView selectedSceneView = getSelectedProductSceneView(); int brightnessValue = this.brightnessPanel.getSliderValue(); int contrastValue = this.contrastPanel.getSliderValue(); int saturationValue = this.saturationPanel.getSliderValue(); BrightnessContrastData brightnessContrastData = this.visibleProductScenes.get(selectedSceneView); brightnessContrastData.setSliderValues(brightnessValue, contrastValue, saturationValue); // recompute the slider values before applying them to the colors brightnessValue = computeSliderValueToApply(brightnessValue, this.brightnessPanel.getSliderMaximumValue(), 255); contrastValue = computeSliderValueToApply(contrastValue, this.contrastPanel.getSliderMaximumValue(), 255); saturationValue = computeSliderValueToApply(saturationValue, this.saturationPanel.getSliderMaximumValue(), 100); ImageInfo sceneImageInfo = this.parentForm.getFormModel().getModifiedImageInfo(); RasterDataNode[] rasterDataNodes = selectedSceneView.getSceneImage().getRasters(); RGBChannelDef initialRGBChannelDef = brightnessContrastData.getInitialImageInfo().getRgbChannelDef(); if (initialRGBChannelDef == null) { ColorPaletteDef colorPaletteDef = sceneImageInfo.getColorPaletteDef(); for (int k=0; k<rasterDataNodes.length; k++) { RasterDataNode currentDataNode = rasterDataNodes[k]; ColorPaletteDef initialColorPaletteDef = brightnessContrastData.getInitialImageInfo(currentDataNode).getColorPaletteDef(); int pointCount = initialColorPaletteDef.getNumPoints(); for (int i=0; i<pointCount; i++) { ColorPaletteDef.Point initialPoint = initialColorPaletteDef.getPointAt(i); Color newColor = computeColor(initialPoint.getColor(), brightnessValue, contrastValue, saturationValue); ColorPaletteDef.Point currentPoint = colorPaletteDef.getPointAt(i); currentPoint.setColor(newColor); } } } else { RGBChannelDef rgbChannelDef = sceneImageInfo.getRgbChannelDef(); for (int i=0; i<rasterDataNodes.length; i++) { RasterDataNode currentDataNode = rasterDataNodes[i]; if (currentDataNode instanceof Band) { ColorPaletteDef initialColorPaletteDef = brightnessContrastData.getInitialImageInfo(currentDataNode).getColorPaletteDef(); Color initialFirstColor = initialColorPaletteDef.getFirstPoint().getColor(); Color newInitialFirstColor = computeColor(initialFirstColor, brightnessValue, contrastValue, saturationValue); float firstPercent = computePercent(initialFirstColor, newInitialFirstColor); double min = initialRGBChannelDef.getMinDisplaySample(i); min = min + (min * firstPercent); rgbChannelDef.setMinDisplaySample(i, min); Color initialLastColor = initialColorPaletteDef.getLastPoint().getColor(); Color newInitialLastColor = computeColor(initialLastColor, brightnessValue, contrastValue, saturationValue); float lastPercent = computePercent(initialLastColor, newInitialLastColor); double max = initialRGBChannelDef.getMaxDisplaySample(i); max = max + (max * lastPercent); rgbChannelDef.setMaxDisplaySample(i, max); } } } selectedSceneView.removePropertyChangeListener(ProductSceneView.PROPERTY_NAME_IMAGE_INFO, this.imageInfoChangeListener); try { this.parentForm.applyChanges(); for (int i=0; i<rasterDataNodes.length; i++) { RasterDataNode currentDataNode = rasterDataNodes[i]; currentDataNode.getProduct().setModified(true); } } finally { selectedSceneView.addPropertyChangeListener(ProductSceneView.PROPERTY_NAME_IMAGE_INFO, this.imageInfoChangeListener); } } private static Color computeColor(Color color, int brightnessValue, int contrastValue, int saturationValue) { int newRgb = computePixelBrightness(color.getRGB(), brightnessValue); newRgb = computePixelContrast(newRgb, contrastValue); newRgb = computePixelSaturation(newRgb, saturationValue); return new Color(newRgb); } private static int computeSliderValueToApply(int visibleSliderValue, int maximumVisibleSliderValue, int maximumAllowedValue) { float visiblePercent = (float)visibleSliderValue / (float) maximumVisibleSliderValue; float percent = Math.round(visiblePercent * maximumAllowedValue); return (int)percent; } private static float computePercent(Color initialColor, Color currentColor) { float initialRedPercent = (float)initialColor.getRed() / 255.0f; float initialGreenPercent = (float)initialColor.getGreen() / 255.0f; float initialBluePercent = (float)initialColor.getBlue() / 255.0f; float currentRedPercent = (float)currentColor.getRed() / 255.0f; float currentGreenPercent = (float)currentColor.getGreen() / 255.0f; float currentBluePercent = (float)currentColor.getBlue() / 255.0f; float redPercent = initialRedPercent - currentRedPercent; float greenPercent = initialGreenPercent - currentGreenPercent; float bluePercent = initialBluePercent - currentBluePercent; return (redPercent + greenPercent + bluePercent) / 3.0f; } private static int checkRGBValue(int v) { if (v > 255) { return 255; } if (v < 0) { return 0; } return v; } private static int computePixelBrightness(int pixel, int sliderValue) { int red = ColorUtils.red(pixel) + sliderValue; int green = ColorUtils.green(pixel) + sliderValue; int blue = ColorUtils.blue(pixel) + sliderValue; return ColorUtils.rgba(checkRGBValue(red), checkRGBValue(green), checkRGBValue(blue)); } private static int computePixelSaturation(int pixel, int sliderValue) { int red = ColorUtils.red(pixel); int green = ColorUtils.green(pixel); int blue = ColorUtils.blue(pixel); float[] hsb = new float[3]; Color.RGBtoHSB(red, green, blue, hsb); hsb[1] += (sliderValue * 0.01f); if (hsb[1] > 1.0f) { hsb[1] = 1.0f; } else if (hsb[1] < 0.0f) { hsb[1] = 0.0f; } return Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]); } private static int computePixelContrast(int pixel, int sliderValue) { float factor = (259.0f * (sliderValue + 255.0f)) / (255.0f * (259.0f - sliderValue)); int red = ColorUtils.red(pixel); int green = ColorUtils.green(pixel); int blue = ColorUtils.blue(pixel); int newRed = (int)(factor * (red - 128) + 128); int newGreen = (int)(factor * (green - 128) + 128); int newBlue = (int)(factor * (blue - 128) + 128); return ColorUtils.rgba(checkRGBValue(newRed), checkRGBValue(newGreen), checkRGBValue(newBlue)); } }
13,391
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorSchemeManager.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorSchemeManager.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.ColorSchemeInfo; import org.esa.snap.core.datamodel.ColorManipulationDefaults; import org.esa.snap.core.util.PropertyMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import javax.swing.*; import javax.swing.plaf.basic.BasicComboBoxRenderer; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.*; import java.io.*; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.*; /** * Manages all the color schemes * * @author Daniel Knowles (NASA) * @author Bing Yang (NASA) * @date Jan 2020 */ public class ColorSchemeManager { private ArrayList<ColorSchemeInfo> colorSchemeStoredInfos = new ArrayList<ColorSchemeInfo>(); private ArrayList<ColorSchemeInfo> colorSchemeOrganizedInfos = new ArrayList<ColorSchemeInfo>(); private ArrayList<ColorSchemeLookupInfo> colorSchemeLookupInfos = new ArrayList<ColorSchemeLookupInfo>(); private File colorSchemesFile = null; private File colorSchemeLutFile = null; private JComboBox jComboBox = null; private boolean jComboBoxShouldFire = true; private final String COLOR_SCHEME_NONE_LABEL = "-- none --"; private String jComboBoxNoneEntryName = null; private ColorSchemeInfo noneColorSchemeInfo = null; private ColorSchemeInfo dividerPrimarySchemes = null; private ColorSchemeInfo dividerAdditionalSchemes = null; private File colorPaletteAuxDir = null; private File colorSchemesAuxDir = null; private boolean verbose = true; private boolean showDisabled = false; private boolean sortComboBox = false; private boolean splitComboBox = false; private boolean initialized = false; private ColorSchemeInfo currentSelection = null; static ColorSchemeManager manager = new ColorSchemeManager(); public static ColorSchemeManager getDefault() { return manager; } public ColorSchemeManager() { init(); } public void init() { if (!initialized) { setjComboBoxShouldFire(false); Path getColorSchemesAuxDir = ColorSchemeUtils.getColorSchemesAuxDataDir(); if (getColorSchemesAuxDir != null) { this.colorSchemesAuxDir = getColorSchemesAuxDir.toFile(); if (!colorSchemesAuxDir.exists()) { return; } } else { return; } Path getColorPalettesAuxDir = ColorSchemeUtils.getColorPalettesAuxDataDir(); if (getColorPalettesAuxDir != null) { this.colorPaletteAuxDir = getColorPalettesAuxDir.toFile(); if (!colorPaletteAuxDir.exists()) { return; } } else { return; } colorSchemesFile = new File(this.colorSchemesAuxDir, ColorManipulationDefaults.COLOR_SCHEMES_FILENAME); colorSchemeLutFile = new File(this.colorSchemesAuxDir, ColorManipulationDefaults.COLOR_SCHEME_LOOKUP_FILENAME); if (colorSchemesFile.exists() && colorSchemeLutFile.exists()) { createPrimaryAndAdditionalColorSchemeInfos(); setjComboBoxNoneEntryName(COLOR_SCHEME_NONE_LABEL); setNoneColorSchemeInfo(new ColorSchemeInfo(getjComboBoxNoneEntryName(), false, false, getjComboBoxNoneEntryName(), null, null, 0, 0, false, true, null, null, null, colorPaletteAuxDir)); dividerPrimarySchemes = new ColorSchemeInfo("-- Primary Schemes --", true, true, "-- Primary Schemes --", null, null, 0, 0, false, false, null, null, null, colorPaletteAuxDir); dividerAdditionalSchemes = new ColorSchemeInfo("-- Additional Schemes --", true, true, "-- Additional Schemes --", null, null, 0, 0, false, false, null, null, null, colorPaletteAuxDir); initComboBox(); initColorSchemeLookup(); reset(); } initialized = true; setjComboBoxShouldFire(true); } } private void addSchemeOrganizedInfos(boolean useAll, boolean primary, boolean sort, boolean verbose) { ArrayList<ColorSchemeInfo> tmpInfos = new ArrayList<ColorSchemeInfo>(); for (ColorSchemeInfo colorSchemeInfo : colorSchemeStoredInfos) { if (!colorSchemeInfo.isDivider()) { if (useAll || primary == colorSchemeInfo.isPrimary()) { tmpInfos.add(colorSchemeInfo); } } } if (sort) { Collections.sort(tmpInfos, new Comparator<ColorSchemeInfo>() { public int compare(ColorSchemeInfo s1, ColorSchemeInfo s2) { return s1.toString(verbose).compareToIgnoreCase(s2.toString(verbose)); } }); } for (ColorSchemeInfo colorSchemeInfo : tmpInfos) { colorSchemeOrganizedInfos.add(colorSchemeInfo); } } private void updateOrganizedColorSchemeInfo(boolean dual, boolean verbose, boolean sort) { colorSchemeOrganizedInfos.clear(); colorSchemeOrganizedInfos.add(getNoneColorSchemeInfo()); if (dual) { colorSchemeOrganizedInfos.add(dividerPrimarySchemes); addSchemeOrganizedInfos(false, true, sort, verbose); colorSchemeOrganizedInfos.add(dividerAdditionalSchemes); addSchemeOrganizedInfos(false, false, sort, verbose); } else { addSchemeOrganizedInfos(true, false, sort, verbose); } } public void checkPreferences(PropertyMap configuration) { boolean updateSchemeSelector = false; boolean useDisplayName = configuration.getPropertyBool(PROPERTY_SCHEME_VERBOSE_KEY, PROPERTY_SCHEME_VERBOSE_DEFAULT); if (isVerbose() != useDisplayName) { setVerbose(useDisplayName); updateSchemeSelector = true; } boolean sortComboBox = configuration.getPropertyBool(PROPERTY_SCHEME_SORT_KEY, PROPERTY_SCHEME_SORT_DEFAULT); if (isSortComboBox() != sortComboBox) { setSortComboBox(sortComboBox); updateSchemeSelector = true; } boolean splitComboBox = configuration.getPropertyBool(PROPERTY_SCHEME_CATEGORIZE_DISPLAY_KEY, PROPERTY_SCHEME_CATEGORIZE_DISPLAY_DEFAULT); if (isSplitComboBox() != splitComboBox) { setSplitComboBox(splitComboBox); updateSchemeSelector = true; } boolean showDisabled = configuration.getPropertyBool(PROPERTY_SCHEME_SHOW_DISABLED_KEY, PROPERTY_SCHEME_SHOW_DISABLED_DEFAULT); if (isShowDisabled() != showDisabled) { setShowDisabled(showDisabled); updateSchemeSelector = true; } if (updateSchemeSelector) { refreshComboBox(); } ColorSchemeManager.getDefault().validateSelection(); } private boolean isShowDisabled() { return showDisabled; } private void setShowDisabled(boolean showDisabled) { if (this.showDisabled != showDisabled) { this.showDisabled = showDisabled; } } private boolean isSortComboBox() { return sortComboBox; } private void setSortComboBox(boolean sortComboBox) { if (this.sortComboBox != sortComboBox) { this.sortComboBox = sortComboBox; } } private void refreshComboBox() { boolean shouldFire = isjComboBoxShouldFire(); setjComboBoxShouldFire(false); ColorSchemeInfo selectedColorSchemeInfo = (ColorSchemeInfo) jComboBox.getSelectedItem(); if (selectedColorSchemeInfo != null && selectedColorSchemeInfo.isEnabled()) { setCurrentSelection(selectedColorSchemeInfo); } jComboBox.removeAllItems(); populateComboBox(); if (getCurrentSelection() != null) { ColorManipulationDefaults.debug("Setting selected to stored value=" + getCurrentSelection()); setSelected(getCurrentSelection()); } jComboBox.repaint(); setjComboBoxShouldFire(shouldFire); } // If user selects an invalid scheme then use the current selection, otherwise update to the selected scheme private void validateSelection() { ColorManipulationDefaults.debug("Checking validation"); if (jComboBox != null) { ColorSchemeInfo selectedColorSchemeInfo = (ColorSchemeInfo) jComboBox.getSelectedItem(); if (selectedColorSchemeInfo != null && selectedColorSchemeInfo != getCurrentSelection()) { if (selectedColorSchemeInfo.isEnabled()) { ColorManipulationDefaults.debug("Validated Selected"); setCurrentSelection(selectedColorSchemeInfo); } else if (getCurrentSelection() != null) { ColorManipulationDefaults.debug("Setting to prior selection"); setSelected(getCurrentSelection()); } } } ColorManipulationDefaults.debug("Finished Checking validation"); } private void populateComboBox() { updateOrganizedColorSchemeInfo(isSplitComboBox(), isVerbose(), isSortComboBox()); final String[] toolTipsArray = new String[colorSchemeOrganizedInfos.size()]; final Boolean[] enabledArray = new Boolean[colorSchemeOrganizedInfos.size()]; final Boolean[] dividerArray = new Boolean[colorSchemeOrganizedInfos.size()]; final Boolean[] duplicateArray = new Boolean[colorSchemeOrganizedInfos.size()]; int i = 0; for (ColorSchemeInfo colorSchemeInfo : colorSchemeOrganizedInfos) { if (colorSchemeInfo.isEnabled() || (!colorSchemeInfo.isEnabled() && (showDisabled || colorSchemeInfo.isDivider()))) { toolTipsArray[i] = colorSchemeInfo.getDescription(); enabledArray[i] = colorSchemeInfo.isEnabled(); dividerArray[i] = colorSchemeInfo.isDivider(); duplicateArray[i] = colorSchemeInfo.isDuplicateEntry(); jComboBox.addItem(colorSchemeInfo); i++; } } final MyComboBoxRenderer myComboBoxRenderer = new MyComboBoxRenderer(); myComboBoxRenderer.setTooltipList(toolTipsArray); myComboBoxRenderer.setEnabledList(enabledArray); myComboBoxRenderer.setDividerList(dividerArray); myComboBoxRenderer.setDuplicateList(duplicateArray); jComboBox.setRenderer(myComboBoxRenderer); } private void initComboBox() { jComboBox = new JComboBox(); jComboBox.setEditable(false); if (colorSchemeLutFile != null) { jComboBox.setToolTipText("To modify see file: " + colorSchemesAuxDir + "/" + colorSchemesFile.getName()); } jComboBox.setMaximumRowCount(15); populateComboBox(); } private Document getFileDocument(File file) { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); Document dom = null; try { DocumentBuilder db = dbf.newDocumentBuilder(); dom = db.parse(new FileInputStream(file)); } catch (ParserConfigurationException pce) { pce.printStackTrace(); } catch (SAXException se) { se.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return dom; } private boolean createPrimaryAndAdditionalColorSchemeInfos() { Document dom = getFileDocument(colorSchemesFile); Element rootElement = dom.getDocumentElement(); NodeList schemeNodeList = rootElement.getElementsByTagName("Scheme"); if (schemeNodeList != null && schemeNodeList.getLength() > 0) { for (int i = 0; i < schemeNodeList.getLength(); i++) { Element schemeElement = (Element) schemeNodeList.item(i); if (schemeElement != null) { String id = schemeElement.getAttribute("name"); String description = getTextValue(schemeElement, "DESCRIPTION"); String displayName = getTextValue(schemeElement, "VERBOSE_NAME"); String colorBarLabels = getTextValue(schemeElement, "COLORBAR_LABELS"); String colorBarTitle = getTextValue(schemeElement, "COLORBAR_TITLE"); String minStr = getTextValue(schemeElement, "MIN"); String maxStr = getTextValue(schemeElement, "MAX"); String logScaledStr = getTextValue(schemeElement, "LOG_SCALE"); String standardCpdFilename = getTextValue(schemeElement, "STANDARD_FILENAME"); String universalCpdFilename = getTextValue(schemeElement, "UNIVERSAL_FILENAME"); String dividerString = getTextValue(schemeElement, "DIVIDER"); String primarySchemeString = getTextValue(schemeElement, "PRIMARY"); boolean validEntry = true; boolean fieldsInitialized = false; Double min; Double max; boolean logScaled; File standardCpdFile; File colorBlindCpdFile; boolean enabled; boolean divider; boolean primaryScheme; if (minStr != null && minStr.length() > 0) { min = Double.valueOf(minStr); } else { min = ColorManipulationDefaults.DOUBLE_NULL; } if (maxStr != null && maxStr.length() > 0) { max = Double.valueOf(maxStr); } else { max = ColorManipulationDefaults.DOUBLE_NULL; } logScaled = false; if (logScaledStr != null && logScaledStr.length() > 0 && logScaledStr.toLowerCase().equals("true")) { logScaled = true; } divider = false; if (dividerString != null && dividerString.length() > 0 && dividerString.toLowerCase().equals("true")) { divider = true; } primaryScheme = false; if (primarySchemeString != null && primarySchemeString.length() > 0 && primarySchemeString.toLowerCase().equals("true")) { primaryScheme = true; } if (id != null && id.length() > 0) { fieldsInitialized = true; } if (fieldsInitialized) { if (!testMinMax(min, max, logScaled)) { validEntry = false; } if (validEntry) { if (standardCpdFilename != null) { standardCpdFile = new File(colorPaletteAuxDir, standardCpdFilename); if (standardCpdFile == null || !standardCpdFile.exists()) { validEntry = false; } } else { validEntry = false; } } if (validEntry) { if (universalCpdFilename != null) { colorBlindCpdFile = new File(colorPaletteAuxDir, universalCpdFilename); if (colorBlindCpdFile == null || !colorBlindCpdFile.exists()) { validEntry = false; } } else { validEntry = false; } } ColorSchemeInfo colorSchemeInfo = null; enabled = validEntry; colorSchemeInfo = new ColorSchemeInfo(id, primaryScheme, divider, displayName, description, standardCpdFilename, min, max, logScaled, enabled, universalCpdFilename, colorBarTitle, colorBarLabels, colorPaletteAuxDir); if (!colorSchemeInfo.isEnabled()) { description = checkScheme(colorSchemeInfo); colorSchemeInfo.setDescription(description); } if (colorSchemeInfo != null) { // determine if this is a duplicate entry if (!colorSchemeInfo.isDuplicateEntry()) { for (ColorSchemeInfo storedColorSchemeInfo : colorSchemeStoredInfos) { if (id.equals(storedColorSchemeInfo.getName())) { colorSchemeInfo.setDuplicateEntry(true); break; } } } if (colorSchemeInfo.isDuplicateEntry()) { colorSchemeInfo.setDescription("WARNING!: duplicate scheme entry"); } colorSchemeStoredInfos.add(colorSchemeInfo); } } } } } return true; } private void initColorSchemeLookup() { Document dom = getFileDocument(colorSchemeLutFile); Element rootElement = dom.getDocumentElement(); NodeList keyNodeList = rootElement.getElementsByTagName("KEY"); if (keyNodeList != null && keyNodeList.getLength() > 0) { for (int i = 0; i < keyNodeList.getLength(); i++) { boolean checksOut = true; Element schemeElement = (Element) keyNodeList.item(i); if (schemeElement != null) { String regex = schemeElement.getAttribute("REGEX"); String schemeId = getTextValue(schemeElement, "SCHEME_ID"); String description = getTextValue(schemeElement, "DESCRIPTION"); if (regex == null || regex.length() == 0) { checksOut = false; } if (schemeId == null || schemeId.length() == 0) { schemeId = regex; } if (schemeId == null || schemeId.length() == 0) { checksOut = false; } ColorSchemeInfo colorSchemeInfo = getColorSchemeInfoBySchemeId(schemeId); if (colorSchemeInfo == null) { checksOut = false; } if (checksOut) { ColorSchemeLookupInfo colorSchemeLookupInfo = new ColorSchemeLookupInfo(regex, schemeId, description, colorSchemeInfo); if (colorSchemeLookupInfo != null) { colorSchemeLookupInfos.add(colorSchemeLookupInfo); } } } } } } public ColorSchemeInfo getColorSchemeInfoBySchemeId(String schemeId) { if (schemeId != null && schemeId.length() > 0) { for (ColorSchemeInfo colorSchemeInfo : colorSchemeStoredInfos) { if (colorSchemeInfo != null && colorSchemeInfo.getName() != null) { if (schemeId.toLowerCase().equals(colorSchemeInfo.getName().toLowerCase())) { return colorSchemeInfo; } } } } return null; } private boolean testMinMax(double min, double max, boolean isLogScaled) { boolean checksOut = true; if (min != ColorManipulationDefaults.DOUBLE_NULL && max != ColorManipulationDefaults.DOUBLE_NULL) { if (min >= max) { checksOut = false; } } if (min != ColorManipulationDefaults.DOUBLE_NULL && max != ColorManipulationDefaults.DOUBLE_NULL) { if (isLogScaled && min == 0) { checksOut = false; } } return checksOut; } // don't allow to fire public void setSelected(ColorSchemeInfo colorSchemeInfo) { boolean shouldFire = isjComboBoxShouldFire(); setjComboBoxShouldFire(false); setCurrentSelection(colorSchemeInfo); // loop through and find rootScheme if (jComboBox != null) { if (colorSchemeInfo != null) { jComboBox.setSelectedItem(colorSchemeInfo); } else { reset(); } } setjComboBoxShouldFire(shouldFire); } public void reset() { setSelected(getNoneColorSchemeInfo()); } public boolean isSchemeSet() { if (jComboBox != null && getNoneColorSchemeInfo() != jComboBox.getSelectedItem()) { return true; } return false; } public static String getTextValue(Element ele, String tagName) { String textVal = null; NodeList nl = ele.getElementsByTagName(tagName); if (nl != null && nl.getLength() > 0) { Element el = (Element) nl.item(0); if (el.hasChildNodes()) { textVal = el.getFirstChild().getNodeValue(); } } return textVal; } public JComboBox getjComboBox() { return jComboBox; } public ArrayList<ColorSchemeLookupInfo> getColorSchemeLookupInfos() { return colorSchemeLookupInfos; } private boolean isVerbose() { return verbose; } private void setVerbose(boolean verbose) { this.verbose = verbose; for (ColorSchemeInfo colorSchemeInfo : colorSchemeStoredInfos) { colorSchemeInfo.setUseDisplayName(verbose); } } public ColorSchemeInfo getNoneColorSchemeInfo() { return noneColorSchemeInfo; } public void setNoneColorSchemeInfo(ColorSchemeInfo noneColorSchemeInfo) { this.noneColorSchemeInfo = noneColorSchemeInfo; } public ColorSchemeInfo getCurrentSelection() { return currentSelection; } public void setCurrentSelection(ColorSchemeInfo currentSelection) { if (currentSelection == null) { currentSelection = noneColorSchemeInfo; } ColorManipulationDefaults.debug("Setting currentSelection=" + currentSelection.toString()); this.currentSelection = currentSelection; } public boolean isSplitComboBox() { return splitComboBox; } public void setSplitComboBox(boolean splitComboBox) { this.splitComboBox = splitComboBox; } class MyComboBoxRenderer extends BasicComboBoxRenderer { private String[] tooltips; private Boolean[] enabledList; private Boolean[] dividerList; private Boolean[] duplicateList; public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { // if (index >= 0) { // if (index < enabledList.length) { // setEnabled(enabledList[index]); // setFocusable(enabledList[index]); // } // // if (index < deviderList.length && deviderList[index]) { // setEnabled(true); // setFocusable(false); // } // } if (index >= 0 && dividerList != null && index < dividerList.length && dividerList[index]) { setBackground(Color.lightGray); setForeground(Color.black); } else { if (isSelected) { setBackground(Color.blue); setForeground(Color.white); if (index >= 0 && enabledList != null && index < enabledList.length && !enabledList[index]) { setForeground(Color.gray); } if (index >= 0 && tooltips != null && index < tooltips.length) { list.setToolTipText(tooltips[index]); } } else { setBackground(Color.white); setForeground(Color.black); if (index >= 0 && duplicateList != null && index < duplicateList.length && duplicateList[index]) { setForeground(Color.red); } else if (index >= 0 && enabledList != null && index < enabledList.length && !enabledList[index]) { setForeground(Color.gray); } } } if (index == 0) { setBackground(Color.white); setForeground(Color.black); } setFont(list.getFont()); setText((value == null) ? "" : value.toString()); return this; } public void setTooltipList(String[] tooltipList) { this.tooltips = tooltipList; } public void setEnabledList(Boolean[] enabledList) { this.enabledList = enabledList; } public void setDividerList(Boolean[] dividerList) { this.dividerList = dividerList; } public void setDuplicateList(Boolean[] duplicateList) { this.duplicateList = duplicateList; } } public String getjComboBoxNoneEntryName() { return jComboBoxNoneEntryName; } private void setjComboBoxNoneEntryName(String jComboBoxNoneEntryName) { this.jComboBoxNoneEntryName = jComboBoxNoneEntryName; } public boolean isNoneScheme(ColorSchemeInfo colorSchemeInfo) { return (noneColorSchemeInfo != null && noneColorSchemeInfo == colorSchemeInfo) ? true : false; } public String checkScheme(ColorSchemeInfo colorSchemeInfo) { String message = ""; if (colorSchemeInfo != null) { String standardFileMessage = ""; String universalFileMessage = ""; String message_head = "WARNING!: Configuration issue for scheme = '" + colorSchemeInfo.getName() + "':<br>"; String standardFilename = colorSchemeInfo.getCpdFilename(false); if (standardFilename != null && standardFilename.length() > 0) { File standardFile = new File(colorPaletteAuxDir, standardFilename); if (standardFile == null || !standardFile.exists()) { standardFileMessage = "Scheme standard file '" + standardFilename + "' does not exist<br>"; } } else { standardFileMessage = "Scheme does not contain a standard file<br>"; } String universalFilename = colorSchemeInfo.getCpdFilename(true); if (universalFilename != null && universalFilename.length() > 0) { File universalFile = new File(colorPaletteAuxDir, universalFilename); if (universalFile == null || !universalFile.exists()) { universalFileMessage = "Scheme universal file '" + universalFilename + "' does not exist<br>"; } } else { universalFileMessage = "Scheme does not contain a universal file<br>"; } String minMaxIssue = ""; if (!testMinMax(colorSchemeInfo.getMinValue(), colorSchemeInfo.getMaxValue(), colorSchemeInfo.isLogScaled())) { minMaxIssue = "Issue with min, max values: min= '" + colorSchemeInfo.getMinValue() + "', max= '" + colorSchemeInfo.getMaxValue() + "' <br>"; } message = "<html>" + message_head + standardFileMessage + universalFileMessage + minMaxIssue + "</html>"; } else { message = "Configuration Error"; } return message; } public boolean isjComboBoxShouldFire() { return jComboBoxShouldFire; } public void setjComboBoxShouldFire(boolean jComboBoxShouldFire) { this.jComboBoxShouldFire = jComboBoxShouldFire; } }
28,906
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Continuous1BandGraphicalForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/Continuous1BandGraphicalForm.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.colormanip; import com.bc.ceres.core.ProgressMonitor; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.ui.ImageInfoEditorModel; import javax.swing.AbstractButton; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Component; import java.util.ArrayList; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.*; /** * @author Brockmann Consult * @author Daniel Knowles (NASA) * @author Bing Yang (NASA) */ // OCT 2019 - Knowles / Yang // - Fixes log scaling bug where the log scaling was not affecting the palette values. This was achieved // by tracking the source and target log scaling and passing this information to the method // setColorPaletteDef() in the class ImageInfo. // - Set computeZoomInToSliderLimits() to be the default display behavior of the histogram display // FEB 2020 - Knowles // - Added call to reset the color scheme to 'none' // - Added optional tool buttons for retrieving 98%, and 90% of the histogram range public class Continuous1BandGraphicalForm implements ColorManipulationChildForm { public static final Scaling POW10_SCALING = new Pow10Scaling(); private final ColorManipulationForm parentForm; private final ImageInfoEditor2 imageInfoEditor; private final ImageInfoEditorSupport imageInfoEditorSupport; private final JPanel contentPanel; private final AbstractButton logDisplayButton; private final AbstractButton evenDistButton; private final MoreOptionsForm moreOptionsForm; private final DiscreteCheckBox discreteCheckBox; final Boolean[] listenToLogDisplayButtonEnabled = {true}; private boolean zoomToHistLimits; private ProductNode currProductNode; Continuous1BandGraphicalForm(final ColorManipulationForm parentForm) { this.parentForm = parentForm; this.currProductNode = parentForm.getFormModel().getProductSceneView().getProductNode(); PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); zoomToHistLimits = configuration.getPropertyBool(PROPERTY_SLIDERS_ZOOM_IN_KEY, PROPERTY_SLIDERS_ZOOM_IN_DEFAULT); parentForm.getFormModel().getProductSceneView().getImageInfo().setZoomToHistLimits(zoomToHistLimits); parentForm.getFormModel().getModifiedImageInfo().setZoomToHistLimits(zoomToHistLimits); imageInfoEditor = new ImageInfoEditor2(parentForm); imageInfoEditorSupport = new ImageInfoEditorSupport(imageInfoEditor, zoomToHistLimits); contentPanel = new JPanel(new BorderLayout(2, 2)); contentPanel.add(imageInfoEditor, BorderLayout.CENTER); moreOptionsForm = new MoreOptionsForm(this, parentForm.getFormModel().canUseHistogramMatching()); discreteCheckBox = new DiscreteCheckBox(parentForm); moreOptionsForm.addRow(discreteCheckBox); parentForm.getFormModel().modifyMoreOptionsForm(moreOptionsForm); logDisplayButton = LogDisplay.createButton(); logDisplayButton.addActionListener(e -> { if (listenToLogDisplayButtonEnabled[0]) { listenToLogDisplayButtonEnabled[0] = false; logDisplayButton.setSelected(!logDisplayButton.isSelected()); applyChangesLogToggle(); listenToLogDisplayButtonEnabled[0] = true; } }); evenDistButton = ImageInfoEditorSupport.createButton("org/esa/snap/rcp/icons/EvenDistribution24.gif"); evenDistButton.setName("evenDistButton"); evenDistButton.setToolTipText("Distribute sliders evenly between first and last slider"); evenDistButton.addActionListener(parentForm.wrapWithAutoApplyActionListener(e -> distributeSlidersEvenly())); } @Override public Component getContentPanel() { return contentPanel; } @Override public ColorManipulationForm getParentForm() { return parentForm; } @Override public void handleFormShown(ColorFormModel formModel) { updateFormModel(formModel); } @Override public void handleFormHidden(ColorFormModel formModel) { if (imageInfoEditor.getModel() != null) { imageInfoEditor.setModel(null); } } @Override public void updateFormModel(ColorFormModel formModel) { final ImageInfoEditorModel oldModel = imageInfoEditor.getModel(); final ImageInfo imageInfo = parentForm.getFormModel().getModifiedImageInfo(); final ImageInfoEditorModel newModel = new ImageInfoEditorModel1B(imageInfo); imageInfoEditor.setModel(newModel); final RasterDataNode raster = formModel.getRaster(); setLogarithmicDisplay(raster, newModel.getImageInfo().isLogScaled()); if (oldModel != null) { newModel.setHistogramViewGain(oldModel.getHistogramViewGain()); newModel.setMinHistogramViewSample(oldModel.getMinHistogramViewSample()); newModel.setMaxHistogramViewSample(oldModel.getMaxHistogramViewSample()); } if (parentForm.getFormModel().getProductSceneView().getImageInfo().getZoomToHistLimits() == null) { // New product window opened so set zoomToHistLimits PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); zoomToHistLimits = configuration.getPropertyBool(PROPERTY_SLIDERS_ZOOM_IN_KEY, PROPERTY_SLIDERS_ZOOM_IN_DEFAULT); parentForm.getFormModel().getProductSceneView().getImageInfo().setZoomToHistLimits(zoomToHistLimits); parentForm.getFormModel().getModifiedImageInfo().setZoomToHistLimits(zoomToHistLimits); } else { // Changed to existing product window so get zoomToHistLimits zoomToHistLimits = parentForm.getFormModel().getProductSceneView().getImageInfo().getZoomToHistLimits(); } imageInfoEditorSupport.setHorizontalZoomButtonAndCompute(zoomToHistLimits); imageInfoEditor.updateShowExtraInformationFromPreferences(); discreteCheckBox.setDiscreteColorsMode(imageInfo.getColorPaletteDef().isDiscrete()); logDisplayButton.setSelected(newModel.getImageInfo().isLogScaled()); imageInfoEditor.setLogScaled(newModel.getImageInfo().isLogScaled()); parentForm.revalidateToolViewPaneControl(); } @Override public void resetFormModel(ColorFormModel formModel) { updateFormModel(formModel); parentForm.revalidateToolViewPaneControl(); } @Override public void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster) { final ImageInfoEditorModel model = imageInfoEditor.getModel(); if (model != null) { if (event.getPropertyName().equals(RasterDataNode.PROPERTY_NAME_STX)) { updateFormModel(parentForm.getFormModel()); } else { setLogarithmicDisplay(raster, model.getImageInfo().isLogScaled()); } } } @Override public RasterDataNode[] getRasters() { return parentForm.getFormModel().getRasters(); } @Override public MoreOptionsForm getMoreOptionsForm() { return moreOptionsForm; } private void setLogarithmicDisplay(final RasterDataNode raster, final boolean logarithmicDisplay) { final ImageInfoEditorModel model = imageInfoEditor.getModel(); if (logarithmicDisplay) { final StxFactory stxFactory = new StxFactory(); final Stx stx = stxFactory .withHistogramBinCount(raster.getStx().getHistogramBinCount()) .withLogHistogram(logarithmicDisplay) .withResolutionLevel(raster.getSourceImage().getModel().getLevelCount() - 1) .create(raster, ProgressMonitor.NULL); model.setDisplayProperties(raster.getName(), raster.getUnit(), stx, POW10_SCALING); } else { model.setDisplayProperties(raster.getName(), raster.getUnit(), raster.getStx(), Scaling.IDENTITY); } model.getImageInfo().setLogScaled(logarithmicDisplay); } private void distributeSlidersEvenly() { resetSchemeSelector(); imageInfoEditor.distributeSlidersEvenly(); } private void resetSchemeSelector() { ColorSchemeInfo colorSchemeNoneInfo = ColorSchemeManager.getDefault().getNoneColorSchemeInfo(); parentForm.getFormModel().getProductSceneView().getImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); parentForm.getFormModel().getModifiedImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); } @Override public AbstractButton[] getToolButtons() { PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); boolean range100 = configuration.getPropertyBool(PROPERTY_100_PERCENT_BUTTON_KEY, PROPERTY_100_PERCENT_BUTTON_DEFAULT); boolean range95 = configuration.getPropertyBool(PROPERTY_95_PERCENT_BUTTON_KEY, PROPERTY_95_PERCENT_BUTTON_DEFAULT); boolean range1Sigma = configuration.getPropertyBool(PROPERTY_1_SIGMA_BUTTON_KEY, PROPERTY_1_SIGMA_BUTTON_DEFAULT); boolean range2Sigma = configuration.getPropertyBool(PROPERTY_2_SIGMA_BUTTON_KEY, PROPERTY_2_SIGMA_BUTTON_DEFAULT); boolean range3Sigma = configuration.getPropertyBool(PROPERTY_3_SIGMA_BUTTON_KEY, PROPERTY_3_SIGMA_BUTTON_DEFAULT); boolean showZoomVerticalButtons = configuration.getPropertyBool(PROPERTY_ZOOM_VERTICAL_BUTTONS_KEY, PROPERTY_ZOOM_VERTICAL_BUTTONS_DEFAULT); boolean showExtraInformationButtons = configuration.getPropertyBool(PROPERTY_INFORMATION_BUTTON_KEY, PROPERTY_INFORMATION_BUTTON_DEFAULT); ArrayList<AbstractButton> abstractButtonArrayList = new ArrayList<AbstractButton>(); abstractButtonArrayList.add(logDisplayButton); if (range1Sigma) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch1SigmaButton); } if (range2Sigma) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch2SigmaButton); } if (range3Sigma) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch3SigmaButton); } if (range95) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch95Button); } if (range100) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch100Button); } abstractButtonArrayList.add(evenDistButton); if (showZoomVerticalButtons) { abstractButtonArrayList.add(imageInfoEditorSupport.zoomInVButton); abstractButtonArrayList.add(imageInfoEditorSupport.zoomOutVButton); } // abstractButtonArrayList.add(imageInfoEditorSupport.zoomVerticalButton); abstractButtonArrayList.add(imageInfoEditorSupport.zoomHorizontalButton); if (showExtraInformationButtons) { abstractButtonArrayList.add(imageInfoEditorSupport.showExtraInfoButton); } final AbstractButton[] abstractButtonArray = new AbstractButton[abstractButtonArrayList.size()]; int i = 0; for (AbstractButton abstractButton : abstractButtonArrayList) { abstractButtonArray[i] = abstractButton; i++; } return abstractButtonArray; } static void setDisplayProperties(ImageInfoEditorModel model, RasterDataNode raster) { model.setDisplayProperties(raster.getName(), raster.getUnit(), raster.getStx(), raster.isLog10Scaled() ? POW10_SCALING : Scaling.IDENTITY); } private static class Log10Scaling implements Scaling { @Override public final double scale(double value) { return value > 1.0E-9 ? Math.log10(value) : -9.0; } @Override public final double scaleInverse(double value) { return value < -9.0 ? 1.0E-9 : Math.pow(10.0, value); } } private static class Pow10Scaling implements Scaling { private final Scaling log10Scaling = new Log10Scaling(); @Override public double scale(double value) { return log10Scaling.scaleInverse(value); } @Override public double scaleInverse(double value) { return log10Scaling.scale(value); } } private void applyChangesLogToggle() { final ImageInfo currentInfo = parentForm.getFormModel().getModifiedImageInfo(); final ColorPaletteDef currentCPD = currentInfo.getColorPaletteDef(); final double min; final double max; final boolean isSourceLogScaled; final boolean isTargetLogScaled; final ColorPaletteDef cpd; final boolean autoDistribute; isSourceLogScaled = currentInfo.isLogScaled(); isTargetLogScaled = !currentInfo.isLogScaled(); min = currentCPD.getMinDisplaySample(); max = currentCPD.getMaxDisplaySample(); cpd = currentCPD; autoDistribute = true; if (ColorUtils.checkRangeCompatibility(min, max, isTargetLogScaled)) { resetSchemeSelector(); currentInfo.setColorPaletteDef(cpd, min, max, autoDistribute, isSourceLogScaled, isTargetLogScaled); currentInfo.setLogScaled(isTargetLogScaled); imageInfoEditor.setLogScaled(currentInfo.isLogScaled()); parentForm.applyChanges(); } } }
14,334
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorManipulationFormImpl.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorManipulationFormImpl.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.colormanip; import com.bc.ceres.core.Assert; import com.bc.ceres.core.ProgressMonitor; import eu.esa.snap.netbeans.docwin.WindowUtilities; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.ColorManipulationDefaults; import org.esa.snap.core.datamodel.ColorPaletteDef; import org.esa.snap.core.datamodel.ColorSchemeInfo; import org.esa.snap.core.datamodel.ImageInfo; 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.ProductNodeListener; import org.esa.snap.core.datamodel.ProductNodeListenerAdapter; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.Stx; import org.esa.snap.core.util.NamingConvention; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.ResourceInstaller; 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.AbstractDialog; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.SnapFileChooser; import org.esa.snap.ui.help.HelpDisplayer; import org.esa.snap.ui.product.BandChooser; import org.esa.snap.ui.product.ProductSceneView; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Cursor; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.Insets; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static org.esa.snap.core.util.NamingConvention.COLOR_LOWER_CASE; /** * The GUI for the color manipulation tool window. * * @author Brockmann Consult * @author Daniel Knowles (NASA) * @author Bing Yang (NASA) * @version $Revision$ $Date$ */ // NOV 2019 - Knowles / Yang // - Added color scheme logic which enables setting of the parameters based on the band name or desired color scheme. // DEC 2019 - Knowles / Yang // - Added capability to export color palette in cpt and pal formats. // JAN 2020 - Yang // - Fixed cpd import button // JAN 2020 - Knowles // - Added installers for the xml files in the color_schemes auxdata directory // - Minor color scheme revisions // FEB 2020 - Knowles // - Wrapped this tool in a JScrollPane // - Changed arrangement of tool buttons to single column // MAR 2020 - Fixed bug where More Options would not update when changing between 3band, 1band, and 1DiscreteBand forms // - Added installation of rgb_profiles auxdata @NbBundle.Messages({ "CTL_ColorManipulationForm_TitlePrefix=" + ColorManipulationDefaults.TOOLNAME_COLOR_MANIPULATION }) class ColorManipulationFormImpl implements SelectionSupport.Handler<ProductSceneView>, ColorManipulationForm { private final static String PREFERENCES_KEY_IO_DIR = "snap.color_palettes.dir"; private final static String FILE_EXTENSION_CPD = "cpd"; private final static String FILE_EXTENSION_PAL = "pal"; private final static String FILE_EXTENSION_CPT = "cpt"; private final static String FILE_EXTENSION_RGB_PROFILES = "rgb"; private AbstractButton resetButton; private AbstractButton multiApplyButton; private AbstractButton importButton; private AbstractButton exportButton; private final TopComponent toolView; private final ColorFormModel formModel; private Band[] bandsToBeModified; private SnapFileFilter snapFileFilter; private SnapFileFilter palFileFilter; private SnapFileFilter cptFileFilter; private final ProductNodeListener productNodeListener; private boolean colorPalettesAuxFilesInstalled; private boolean colorSchemesAuxFilesInstalled; private boolean rgbProfilesFilesInstalled; private JPanel contentPanel; private JPanel innerContentPanel; private ColorManipulationChildForm childForm; private ColorManipulationChildForm continuous1BandSwitcherForm; private ColorManipulationChildForm discrete1BandTabularForm; private ColorManipulationChildForm continuous3BandGraphicalForm; private JPanel toolButtonsPanel; private AbstractButton helpButton; private Path ioDir; private JPanel editorPanel; private MoreOptionsPane moreOptionsPane; private SceneViewImageInfoChangeListener sceneViewChangeListener; private String titlePrefix; private ColorManipulationChildForm emptyForm; private BrightnessContrastPanel brightnessContrastPanel; private JTabbedPane tabbedPane; ColorManipulationFormImpl(TopComponent colorManipulationToolView, ColorFormModel formModel) { Assert.notNull(colorManipulationToolView); Assert.notNull(formModel); this.toolView = colorManipulationToolView; this.formModel = formModel; productNodeListener = new ColorManipulationPNL(); sceneViewChangeListener = new SceneViewImageInfoChangeListener(); titlePrefix = this.formModel.getTitlePrefix(); emptyForm = new EmptyImageInfoForm(this); } @Override public ColorFormModel getFormModel() { return formModel; } @Override public JPanel getContentPanel() { if (contentPanel == null) { initContentPanel(); } if (!colorPalettesAuxFilesInstalled) { ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(new InstallColorPalettesAuxFiles()); } if (!colorSchemesAuxFilesInstalled) { ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(new InstallColorSchemesAuxFiles()); } if (!rgbProfilesFilesInstalled) { ExecutorService executorService = Executors.newSingleThreadExecutor(); executorService.submit(new InstallRGBAuxFiles()); } return contentPanel; } public void revalidateToolViewPaneControl() { getToolViewPaneControl().invalidate(); getToolViewPaneControl().validate(); getToolViewPaneControl().repaint(); updateToolButtons(); } private static AbstractButton createButton(final String iconPath) { return ImageInfoEditorSupport.createButton(iconPath); } private Component getToolViewPaneControl() { return toolView; } private void setProductSceneView(final ProductSceneView productSceneView) { ProductSceneView productSceneViewOld = getFormModel().getProductSceneView(); if (productSceneViewOld != null) { Product product = productSceneViewOld.getProduct(); if (product != null) { // Product may already been gone. product.removeProductNodeListener(productNodeListener); } productSceneViewOld.removePropertyChangeListener(sceneViewChangeListener); } getFormModel().setProductSceneView(productSceneView); if (getFormModel().isValid()) { getFormModel().getProductSceneView().getProduct().addProductNodeListener(productNodeListener); getFormModel().getProductSceneView().addPropertyChangeListener(sceneViewChangeListener); if (getFormModel().isContinuous3BandImage() || getFormModel().isDiscrete1BandImage()) { getFormModel().setModifiedImageInfo(getFormModel().getOriginalImageInfo()); } else { PropertyMap configuration = productSceneView.getSceneImage().getConfiguration(); if (productSceneView.getImageInfo().getColorSchemeInfo() == null) { ColorManipulationDefaults.debug("In ColorManipulationFormImpl: colorSchemeInfo =null (setToDefault)"); ColorSchemeUtils.setImageInfoToDefaultColor(configuration, createDefaultImageInfo(), productSceneView, false); } else { ColorManipulationDefaults.debug("In ColorManipulationFormImpl: colorSchemeInfo =" + productSceneView.getImageInfo().getColorSchemeInfo().toString()); } ColorManipulationDefaults.debug("In ColorManipulationFormImpl: about to do setModifiedImageInfo "); getFormModel().setModifiedImageInfo(getFormModel().getProductSceneView().getImageInfo()); ColorManipulationDefaults.debug("In ColorManipulationFormImpl: finished setModifiedImageInfo "); } } installChildForm(); updateTitle(); updateToolButtons(); ColorManipulationDefaults.debug("In ColorManipulationFormImpl: about to do updateMultiApplyState "); updateMultiApplyState(); ColorManipulationDefaults.debug("In ColorManipulationFormImpl: finished updateMultiApplyState "); if (getFormModel().isValid()) { ColorManipulationDefaults.debug("In ColorManipulationFormImpl: apply changes"); applyChanges(); } } private void installChildForm() { final ColorManipulationChildForm oldForm = getChildForm(); ColorManipulationChildForm newForm = emptyForm; if (getFormModel().isValid()) { if (getFormModel().isContinuous3BandImage()) { if (oldForm instanceof Continuous3BandGraphicalForm) { newForm = oldForm; } else { newForm = getContinuous3BandGraphicalForm(); } } else if (getFormModel().isContinuous1BandImage()) { if (oldForm instanceof Continuous1BandSwitcherForm) { newForm = oldForm; } else { newForm = getContinuous1BandSwitcherForm(); } } else if (getFormModel().isDiscrete1BandImage()) { if (oldForm instanceof Discrete1BandTabularForm) { newForm = oldForm; } else { newForm = getDiscrete1BandTabularForm(); } } else { if (oldForm instanceof Continuous1BandSwitcherForm) { newForm = oldForm; } else { newForm = getContinuous1BandSwitcherForm(); } } } if (newForm != oldForm) { setChildForm(newForm); updateMoreOptions(); boolean installAllButtons = !(newForm instanceof Continuous1BandGraphicalForm || newForm instanceof Continuous3BandGraphicalForm); installToolButtons(installAllButtons); installMoreOptions(); editorPanel.removeAll(); editorPanel.add(getChildForm().getContentPanel(), BorderLayout.CENTER); if (!(getChildForm() instanceof EmptyImageInfoForm)) { editorPanel.add(moreOptionsPane.getContentPanel(), BorderLayout.SOUTH); } revalidateToolViewPaneControl(); if (oldForm != null) { oldForm.handleFormHidden(getFormModel()); } getChildForm().handleFormShown(getFormModel()); } else { getChildForm().updateFormModel(getFormModel()); } } private void updateTitle() { String titlePostfix = ""; if (getFormModel().isValid()) { titlePostfix = " - " + getFormModel().getModelName(); } toolView.setDisplayName(titlePrefix + titlePostfix); } private void updateToolButtons() { resetButton.setEnabled(getFormModel().isValid()); importButton.setEnabled(getFormModel().isValid() && !getFormModel().isContinuous3BandImage()); exportButton.setEnabled(getFormModel().isValid() && !getFormModel().isContinuous3BandImage()); } private ColorManipulationChildForm getContinuous3BandGraphicalForm() { if (continuous3BandGraphicalForm == null) { continuous3BandGraphicalForm = new Continuous3BandGraphicalForm(this); } return continuous3BandGraphicalForm; } private ColorManipulationChildForm getContinuous1BandSwitcherForm() { if (continuous1BandSwitcherForm == null) { continuous1BandSwitcherForm = new Continuous1BandSwitcherForm(this); } return continuous1BandSwitcherForm; } private ColorManipulationChildForm getDiscrete1BandTabularForm() { if (discrete1BandTabularForm == null) { discrete1BandTabularForm = new Discrete1BandTabularForm(this); } return discrete1BandTabularForm; } @Override public ActionListener wrapWithAutoApplyActionListener(final ActionListener actionListener) { return e -> { actionListener.actionPerformed(e); applyChanges(); }; } private void initContentPanel() { this.moreOptionsPane = new MoreOptionsPane(this, formModel.isMoreOptionsFormCollapsedOnInit()); this.brightnessContrastPanel = new BrightnessContrastPanel(this); resetButton = createButton("org/esa/snap/rcp/icons/Undo24.gif"); resetButton.setName("ResetButton"); resetButton.setToolTipText("Reset to defaults"); /*I18N*/ resetButton.addActionListener(wrapWithAutoApplyActionListener(e -> resetToDefaults())); multiApplyButton = createButton("org/esa/snap/rcp/icons/MultiAssignBands24.gif"); multiApplyButton.setName("MultiApplyButton"); multiApplyButton.setToolTipText("Apply to other bands"); /*I18N*/ multiApplyButton.addActionListener(e -> applyMultipleColorPaletteDef()); importButton = createButton("tango/22x22/actions/document-open.png"); importButton.setName("ImportButton"); importButton.setToolTipText("Import " + NamingConvention.COLOR_LOWER_CASE + " palette from text file."); /*I18N*/ importButton.addActionListener(e -> { importColorPaletteDef(); applyChanges(); }); importButton.setEnabled(true); exportButton = createButton("tango/22x22/actions/document-save-as.png"); exportButton.setName("ExportButton"); exportButton.setToolTipText("Save " + NamingConvention.COLOR_LOWER_CASE + " palette to text file."); /*I18N*/ exportButton.addActionListener(e -> { exportColorPaletteDef(); getChildForm().updateFormModel(getFormModel()); }); exportButton.setEnabled(true); helpButton = createButton("tango/22x22/apps/help-browser.png"); helpButton.setToolTipText("Help."); /*I18N*/ helpButton.setName("helpButton"); helpButton.addActionListener(e -> HelpDisplayer.show(toolView.getHelpCtx())); editorPanel = new JPanel(new BorderLayout(4, 4)); editorPanel.add(moreOptionsPane.getContentPanel(), BorderLayout.SOUTH); toolButtonsPanel = GridBagUtils.createPanel(); innerContentPanel = new JPanel(new BorderLayout(4, 4)); innerContentPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); innerContentPanel.setPreferredSize(new Dimension(280, 275)); innerContentPanel.add(editorPanel, BorderLayout.CENTER); innerContentPanel.add(toolButtonsPanel, BorderLayout.EAST); JScrollPane jScrollPane = new JScrollPane(innerContentPanel); contentPanel = new JPanel(new BorderLayout(4, 4)); contentPanel.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); contentPanel.setPreferredSize(new Dimension(280, 200)); contentPanel.add(jScrollPane, BorderLayout.CENTER); setProductSceneView(SnapApp.getDefault().getSelectedProductSceneView()); SnapApp.getDefault().getSelectionSupport(ProductSceneView.class).addHandler(this); } private void updateMultiApplyState() { multiApplyButton.setEnabled(getFormModel().isValid() && !getFormModel().isContinuous3BandImage()); } @Override public void installToolButtons(boolean installAllButtons) { toolButtonsPanel.removeAll(); GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.weightx = 1.0; gbc.gridy = 0; gbc.insets.bottom = 2; gbc.gridwidth = 1; toolButtonsPanel.add(resetButton, gbc); gbc.gridy += 1; AbstractButton[] additionalButtons = getChildForm().getToolButtons(); for (int i = 0; i < additionalButtons.length; i++) { AbstractButton button = additionalButtons[i]; toolButtonsPanel.add(button, gbc); gbc.gridy += 1; } if (installAllButtons) { toolButtonsPanel.add(multiApplyButton, gbc); gbc.gridy += 1; toolButtonsPanel.add(importButton, gbc); gbc.gridy += 1; toolButtonsPanel.add(exportButton, gbc); gbc.gridy += 1; } gbc.fill = GridBagConstraints.VERTICAL; gbc.weighty = 1.0; toolButtonsPanel.add(new JLabel(" "), gbc); // filler gbc.fill = GridBagConstraints.NONE; gbc.weighty = 0.0; gbc.gridwidth = 1; gbc.gridy += 1; toolButtonsPanel.add(helpButton, gbc); } // @Override // public void installToolButtons(boolean installAllButtons) { // // boolean singleColumn = true; // otherwise 2 columns // // toolButtonsPanel.removeAll(); // GridBagConstraints gbc = new GridBagConstraints(); // gbc.anchor = GridBagConstraints.CENTER; // gbc.fill = GridBagConstraints.NONE; // gbc.weightx = 1.0; // gbc.gridy = 0; // gbc.insets.bottom = 2; // gbc.gridwidth = 1; // // toolButtonsPanel.add(resetButton, gbc); // // // if (installAllButtons) { // if (singleColumn) { // gbc.gridy += 1; // } // // toolButtonsPanel.add(multiApplyButton, gbc); // gbc.gridy += 1; // // toolButtonsPanel.add(importButton, gbc); // if (singleColumn) { // gbc.gridy += 1; // } // // toolButtonsPanel.add(exportButton, gbc); // gbc.gridy += 1; // } else { // gbc.gridy += 1; // } // // AbstractButton[] additionalButtons = getChildForm().getToolButtons(); // for (int i = 0; i < additionalButtons.length; i++) { // AbstractButton button = additionalButtons[i]; // toolButtonsPanel.add(button, gbc); // if (singleColumn || (i % 2 == 1)) { // gbc.gridy += 1; // } // } // // gbc.gridy += 1; // gbc.fill = GridBagConstraints.VERTICAL; // gbc.weighty = 1.0; // // gbc.gridwidth = (singleColumn) ? 1 : 2; // toolButtonsPanel.add(new JLabel(" "), gbc); // filler // gbc.fill = GridBagConstraints.NONE; // gbc.weighty = 0.0; // gbc.gridwidth = 1; // gbc.gridy += 1; // gbc.gridx = 0; // toolButtonsPanel.add(helpButton, gbc); // } @Override public void installMoreOptions() { final MoreOptionsForm moreOptionsForm = getChildForm().getMoreOptionsForm(); if (moreOptionsForm != null) { moreOptionsForm.updateForm(); if (this.tabbedPane == null) { this.tabbedPane = new JTabbedPane(); this.tabbedPane.addTab("Histogram", moreOptionsForm.getContentPanel()); this.tabbedPane.addTab("Brightness/Contrast", this.brightnessContrastPanel); } this.moreOptionsPane.setComponent(this.tabbedPane); } } public void updateMoreOptions() { final MoreOptionsForm moreOptionsForm = getChildForm().getMoreOptionsForm(); if (moreOptionsForm != null) { if (this.tabbedPane != null) { this.tabbedPane.setComponentAt(0, moreOptionsForm.getContentPanel()); this.tabbedPane.repaint(); } } } @Override public void applyChanges() { ColorManipulationDefaults.debug("Applying changes in ColorManipulationFormImpl"); updateMultiApplyState(); if (getFormModel().isValid()) { try { getToolViewPaneControl().setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); if (getFormModel().isContinuous3BandImage()) { getFormModel().setRasters(getChildForm().getRasters()); } else { getFormModel().getRaster().setImageInfo(getFormModel().getModifiedImageInfo()); } getFormModel().applyModifiedImageInfo(); } finally { getToolViewPaneControl().setCursor(Cursor.getDefaultCursor()); } } updateMultiApplyState(); } private void resetToDefaults() { if (getFormModel().isValid()) { PropertyMap configuration = getFormModel().getProductSceneView().getSceneImage().getConfiguration(); ColorSchemeUtils.setImageInfoToDefaultColor(configuration, createDefaultImageInfo(), getFormModel().getProductSceneView(), true); getFormModel().setModifiedImageInfo(getFormModel().getProductSceneView().getImageInfo()); getChildForm().resetFormModel(getFormModel()); } } private void applyMultipleColorPaletteDef() { if (!getFormModel().isValid()) { return; } final Product selectedProduct = getFormModel().getProduct(); final ProductManager productManager = selectedProduct.getProductManager(); final RasterDataNode[] protectedRasters = getFormModel().getRasters(); final ArrayList<Band> availableBandList = new ArrayList<>(); for (int i = 0; i < productManager.getProductCount(); i++) { final Product product = productManager.getProduct(i); final Band[] bands = product.getBands(); for (final Band band : bands) { boolean validBand = false; if (band.getImageInfo() != null) { validBand = true; for (RasterDataNode protectedRaster : protectedRasters) { if (band == protectedRaster) { validBand = false; } } } if (validBand) { availableBandList.add(band); } } } final Band[] availableBands = new Band[availableBandList.size()]; availableBandList.toArray(availableBands); availableBandList.clear(); if (availableBands.length == 0) { AbstractDialog.showWarningDialog(getToolViewPaneControl(), "No other bands available.", titlePrefix); return; } final BandChooser bandChooser = new BandChooser(SwingUtilities.getWindowAncestor(toolView), "Apply to other bands", toolView.getHelpCtx().getHelpID(), availableBands, bandsToBeModified, false); final Set<RasterDataNode> modifiedRasters = new HashSet<>(availableBands.length); if (bandChooser.show() == BandChooser.ID_OK) { bandsToBeModified = bandChooser.getSelectedBands(); for (final Band band : bandsToBeModified) { applyColorPaletteDef(getFormModel().getModifiedImageInfo().getColorPaletteDef(), band, band.getImageInfo()); modifiedRasters.add(band); } } // This code replaces visatApp.updateImages(rasters) from BEAM code. WindowUtilities.getOpened(ProductSceneViewTopComponent.class).forEach(tc -> { final ProductSceneView view = tc.getView(); for (RasterDataNode raster : view.getRasters()) { if (modifiedRasters.contains(raster)) { view.updateImage(); return; } } }); } private void setIODir(final File dir) { ioDir = dir.toPath(); Config.instance().preferences().put(PREFERENCES_KEY_IO_DIR, ioDir.toString()); } @Override public Path getIODir() { if (ioDir == null) { ioDir = Paths.get(Config.instance().preferences().get(PREFERENCES_KEY_IO_DIR, getColorPalettesAuxDataDir().toString())); } return ioDir; } private SnapFileFilter getOrCreateCpdFileFilter() { if (snapFileFilter == null) { final String formatName = "COLOR_PALETTE_DEFINITION_FILE"; final String description = FILE_EXTENSION_CPD.toUpperCase() + " - Default " + COLOR_LOWER_CASE + " palette format (*" + FILE_EXTENSION_CPD + ")"; /*I18N*/ snapFileFilter = new SnapFileFilter(formatName, "." + FILE_EXTENSION_CPD, description); } return snapFileFilter; } private SnapFileFilter getOrCreatePalFileFilter() { if (palFileFilter == null) { final String formatName = "GENERIC_COLOR_PALETTE_FILE"; final String description = FILE_EXTENSION_PAL.toUpperCase() + " - Generic 256 point " + COLOR_LOWER_CASE + " palette format (*." + FILE_EXTENSION_PAL + ")"; /*I18N*/ palFileFilter = new SnapFileFilter(formatName, "." + FILE_EXTENSION_PAL, description); } return palFileFilter; } private SnapFileFilter getOrCreateCptFileFilter() { if (cptFileFilter == null) { final String formatName = "CPT_COLOR_PALETTE_FILE"; final String description = FILE_EXTENSION_CPT.toUpperCase() + " - Generic mapping tools format (*." + FILE_EXTENSION_CPT + ")"; /*I18N*/ cptFileFilter = new SnapFileFilter(formatName, "." + FILE_EXTENSION_CPT, description); } return cptFileFilter; } private void importColorPaletteDef() { final ImageInfo targetImageInfo = getFormModel().getModifiedImageInfo(); if (targetImageInfo == null) { // Normally this code is unreachable because, the export Button // is disabled if the _contrastStretchPane has no ImageInfo. return; } final SnapFileChooser fileChooser = new SnapFileChooser(); fileChooser.setDialogTitle("Import " + NamingConvention.COLOR_MIXED_CASE + " Palette"); /*I18N*/ fileChooser.setFileFilter(getOrCreateCpdFileFilter()); fileChooser.addChoosableFileFilter(getOrCreateCptFileFilter()); fileChooser.setCurrentDirectory(getIODir().toFile()); final JPanel optionsPanel = new JPanel(new GridLayout(2, 1)); optionsPanel.setBorder(BorderFactory.createTitledBorder("CPT Options")); JRadioButton buttonSourceLogScaled = new JRadioButton("Source Log Scaled"); buttonSourceLogScaled.setSelected(false); buttonSourceLogScaled.setEnabled(false); buttonSourceLogScaled.setToolTipText("The source cpt values are log scaled"); JRadioButton buttonCptValue = new JRadioButton("Use CPT Value"); buttonCptValue.setSelected(false); buttonCptValue.setEnabled(false); buttonCptValue.setToolTipText("The use cpt values instead of current min/max range settings"); optionsPanel.add(buttonSourceLogScaled); optionsPanel.add(buttonCptValue); optionsPanel.setEnabled(false); fileChooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, evt -> { final SnapFileFilter snapFileFilter = fileChooser.getSnapFileFilter(); // snapFileFilter.getFileSelectionMode().getValue(); if (snapFileFilter != null) { String format = snapFileFilter.getFormatName(); System.out.println("FORMAT=" + format); boolean cptEnabled = "CPT_COLOR_PALETTE_FILE".equals(snapFileFilter.getFormatName()); System.out.println("enabled=" + cptEnabled); buttonSourceLogScaled.setEnabled(cptEnabled); buttonCptValue.setEnabled(cptEnabled); optionsPanel.setEnabled(cptEnabled); } }); JComponent commentsPanel = new JLabel(""); // commentsPanel.setBorder(BorderFactory.createTitledBorder("Comments")); /*I18N*/ // commentsPanel.setToolTipText("Some comments"); final JPanel accessory = new JPanel(new GridBagLayout()); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = 0; gbc.gridx = 0; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.weighty = .5; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.insets = new Insets(3, 3, 3, 3); // accessory.setLayout(new BoxLayout(accessory, BoxLayout.Y_AXIS)); accessory.add(optionsPanel, gbc); gbc.gridy = 1; gbc.weighty = 1; gbc.fill = GridBagConstraints.BOTH; accessory.add(commentsPanel, gbc); fileChooser.setAccessory(accessory); final int result = fileChooser.showOpenDialog(getToolViewPaneControl()); final File file = fileChooser.getSelectedFile(); if (file != null && file.getParentFile() != null) { setIODir(file.getParentFile()); } if (result == JFileChooser.APPROVE_OPTION) { if (file != null && file.canRead()) { try { ColorPaletteDef colorPaletteDef; if (file.getName().endsWith(FILE_EXTENSION_CPT)) { colorPaletteDef = ColorPaletteDef.loadCpt(file); } else { colorPaletteDef = ColorPaletteDef.loadColorPaletteDef(file); } final ColorPaletteDef currentCPD = targetImageInfo.getColorPaletteDef(); final double min = currentCPD.getMinDisplaySample(); final double max = currentCPD.getMaxDisplaySample(); final boolean isSourceLogScaled = buttonSourceLogScaled.isSelected(); // final boolean isSourceLogScaled = colorPaletteDef.isLogScaled(); final boolean isTargetLogScaled = targetImageInfo.isLogScaled(); final boolean autoDistribute = !buttonCptValue.isSelected(); // final boolean autoDistribute = true; if (ColorUtils.checkRangeCompatibility(min, max, isTargetLogScaled)) { targetImageInfo.setColorPaletteDef(colorPaletteDef, min, max, autoDistribute, isSourceLogScaled, isTargetLogScaled); ColorSchemeInfo colorSchemeInfo = ColorSchemeManager.getDefault().getNoneColorSchemeInfo(); targetImageInfo.setColorSchemeInfo(colorSchemeInfo); } currentCPD.getFirstPoint().setLabel(file.getName()); getFormModel().setModifiedImageInfo(targetImageInfo); getFormModel().applyModifiedImageInfo(); getChildForm().updateFormModel(getFormModel()); updateMultiApplyState(); } catch (IOException e) { showErrorDialog("Failed to import " + NamingConvention.COLOR_LOWER_CASE + " palette:\n" + e.getMessage()); } } } } private void applyColorPaletteDef(ColorPaletteDef colorPaletteDef, RasterDataNode targetRaster, ImageInfo targetImageInfo) { if (isIndexCoded(targetRaster)) { targetImageInfo.setColors(colorPaletteDef.getColors()); } else { Stx stx = targetRaster.getStx(false, ProgressMonitor.NULL); Boolean autoDistribute = getAutoDistribute(colorPaletteDef); if (autoDistribute == null) { return; } targetImageInfo.setColorPaletteDef(colorPaletteDef, stx.getMinimum(), stx.getMaximum(), autoDistribute); } } private Boolean getAutoDistribute(ColorPaletteDef colorPaletteDef) { if (colorPaletteDef.isAutoDistribute()) { return Boolean.TRUE; } int answer = JOptionPane.showConfirmDialog(getToolViewPaneControl(), "Automatically distribute points of\n" + NamingConvention.COLOR_LOWER_CASE + " palette between min/max?", "Import " + NamingConvention.COLOR_MIXED_CASE + " Palette", JOptionPane.YES_NO_CANCEL_OPTION ); if (answer == JOptionPane.YES_OPTION) { return Boolean.TRUE; } else if (answer == JOptionPane.NO_OPTION) { return Boolean.FALSE; } else { return null; } } private boolean isIndexCoded(RasterDataNode targetRaster) { return targetRaster instanceof Band && ((Band) targetRaster).getIndexCoding() != null; } private void exportColorPaletteDef() { final ImageInfo imageInfo = getFormModel().getModifiedImageInfo(); if (imageInfo == null) { // Normally this code is unreachable because, the export Button should be // disabled if the color manipulation form has no ImageInfo. return; } final SnapFileChooser fileChooser = new SnapFileChooser(); fileChooser.setDialogTitle("Export " + NamingConvention.COLOR_MIXED_CASE + " Palette"); /*I18N*/ fileChooser.setFileFilter(getOrCreateCpdFileFilter()); fileChooser.addChoosableFileFilter(getOrCreatePalFileFilter()); fileChooser.addChoosableFileFilter(getOrCreateCptFileFilter()); fileChooser.setCurrentDirectory(getIODir().toFile()); final int result = fileChooser.showSaveDialog(getToolViewPaneControl()); File file = fileChooser.getSelectedFile(); if (file != null && file.getParentFile() != null) { setIODir(file.getParentFile()); } if (result == JFileChooser.APPROVE_OPTION) { if (file != null) { if (Boolean.TRUE.equals(Dialogs.requestOverwriteDecision(titlePrefix, file))) { // file = FileUtils.ensureExtension(file, FILE_EXTENSION); try { final ColorPaletteDef colorPaletteDef = imageInfo.getColorPaletteDef(); String path = file.getPath(); if (path.endsWith("." + FILE_EXTENSION_PAL)) { ColorPaletteDef.storePal(colorPaletteDef, file); } else if (path.endsWith("." + FILE_EXTENSION_CPT)) { ColorPaletteDef.storeCpt(colorPaletteDef, file); } else { file = FileUtils.ensureExtension(file, "." + FILE_EXTENSION_CPD); ColorPaletteDef.storeColorPaletteDef(colorPaletteDef, file); } } catch (IOException e) { showErrorDialog("Failed to export " + NamingConvention.COLOR_LOWER_CASE + " palette:\n" + e.getMessage()); /*I18N*/ } } } } } private void showErrorDialog(final String message) { if (message != null && message.trim().length() > 0) { if (SnapApp.getDefault() != null) { Dialogs.showError(message); } else { Dialogs.showError("Error", message); } } } public ColorManipulationChildForm getChildForm() { return childForm; } public void setChildForm(ColorManipulationChildForm childForm) { this.childForm = childForm; } // Installs the color palette files resources private class InstallColorPalettesAuxFiles implements Runnable { private InstallColorPalettesAuxFiles() { } @Override public void run() { try { Path auxdataDir = getColorPalettesAuxDataDir(); Path sourceDirPath = getColorPalettesAuxDataSourceDir(); final ResourceInstaller resourceInstaller = new ResourceInstaller(sourceDirPath, auxdataDir); resourceInstaller.install(".*." + FILE_EXTENSION_CPD, ProgressMonitor.NULL); resourceInstaller.install(".*." + FILE_EXTENSION_CPT, ProgressMonitor.NULL); // these file get overwritten as we do not encourage that these standard files to be altered resourceInstaller.install(".*oceancolor_.*." + FILE_EXTENSION_CPD, ProgressMonitor.NULL); colorPalettesAuxFilesInstalled = true; } catch (IOException e) { SnapApp.getDefault().handleError("Unable to install auxdata/" + ColorManipulationDefaults.DIR_NAME_COLOR_PALETTES, e); } } } // Installs the color scheme xml files resources private class InstallColorSchemesAuxFiles implements Runnable { private InstallColorSchemesAuxFiles() { } @Override public void run() { try { Path auxdataDir = getColorSchemesAuxDataDir(); Path sourceDirPath = getColorSchemesAuxDataSourceDir(); final ResourceInstaller resourceInstaller = new ResourceInstaller(sourceDirPath, auxdataDir); resourceInstaller.install(".*." + ColorManipulationDefaults.COLOR_SCHEMES_FILENAME, ProgressMonitor.NULL); resourceInstaller.install(".*" + ColorManipulationDefaults.COLOR_SCHEME_LOOKUP_FILENAME, ProgressMonitor.NULL); colorSchemesAuxFilesInstalled = true; } catch (IOException e) { SnapApp.getDefault().handleError("Unable to install auxdata/" + ColorManipulationDefaults.DIR_NAME_COLOR_SCHEMES, e); } } } // Installs the RGB profile resources private class InstallRGBAuxFiles implements Runnable { private InstallRGBAuxFiles() { } @Override public void run() { try { Path auxdataDir = getRgbProfilesAuxDataDir(); Path sourceDirPath = getRgbProfilesAuxDataSourceDir(); final ResourceInstaller resourceInstaller = new ResourceInstaller(sourceDirPath, auxdataDir); resourceInstaller.install(".*." + FILE_EXTENSION_RGB_PROFILES, ProgressMonitor.NULL); rgbProfilesFilesInstalled = true; } catch (IOException e) { SnapApp.getDefault().handleError("Unable to install auxdata/" + ColorManipulationDefaults.DIR_NAME_RGB_PROFILES, e); } } } public Path getColorPalettesAuxDataSourceDir() { Path sourceBasePath = ResourceInstaller.findModuleCodeBasePath(GridBagUtils.class); Path auxdirSource = sourceBasePath.resolve(ColorManipulationDefaults.DIR_NAME_AUX_DATA); return auxdirSource.resolve(ColorManipulationDefaults.DIR_NAME_COLOR_PALETTES); } public Path getColorSchemesAuxDataSourceDir() { Path sourceBasePath = ResourceInstaller.findModuleCodeBasePath(GridBagUtils.class); Path auxdirSource = sourceBasePath.resolve(ColorManipulationDefaults.DIR_NAME_AUX_DATA); return auxdirSource.resolve(ColorManipulationDefaults.DIR_NAME_COLOR_SCHEMES); } public Path getRgbProfilesAuxDataSourceDir() { Path sourceBasePath = ResourceInstaller.findModuleCodeBasePath(GridBagUtils.class); Path auxdirSource = sourceBasePath.resolve(ColorManipulationDefaults.DIR_NAME_AUX_DATA); return auxdirSource.resolve(ColorManipulationDefaults.DIR_NAME_RGB_PROFILES); } private Path getColorPalettesAuxDataDir() { return ColorSchemeUtils.getColorPalettesAuxDataDir(); } private Path getColorSchemesAuxDataDir() { return ColorSchemeUtils.getColorSchemesAuxDataDir(); } private Path getRgbProfilesAuxDataDir() { return ColorSchemeUtils.getRgbProfilesAuxDataDir(); } private ImageInfo createDefaultImageInfo() { try { return ProductUtils.createImageInfo(getFormModel().getRasters(), false, ProgressMonitor.NULL); } catch (Exception e) { JOptionPane.showMessageDialog(getContentPanel(), "Failed to create default image settings:\n" + e.getMessage(), "I/O Error", JOptionPane.ERROR_MESSAGE); return null; } } @Override public Stx getStx(RasterDataNode raster) { return raster.getStx(false, ProgressMonitor.NULL); } private class ColorManipulationPNL extends ProductNodeListenerAdapter { @Override public void nodeChanged(final ProductNodeEvent event) { final RasterDataNode[] rasters = getChildForm().getRasters(); RasterDataNode raster = null; for (RasterDataNode dataNode : rasters) { if (event.getSourceNode() == dataNode) { raster = (RasterDataNode) event.getSourceNode(); } } if (raster != null) { final String propertyName = event.getPropertyName(); if (ProductNode.PROPERTY_NAME_NAME.equalsIgnoreCase(propertyName)) { updateTitle(); getChildForm().handleRasterPropertyChange(event, raster); } else if (RasterDataNode.PROPERTY_NAME_ANCILLARY_VARIABLES.equalsIgnoreCase(propertyName)) { updateTitle(); getChildForm().handleRasterPropertyChange(event, raster); } else if (RasterDataNode.PROPERTY_NAME_UNIT.equalsIgnoreCase(propertyName)) { getChildForm().handleRasterPropertyChange(event, raster); } else if (RasterDataNode.PROPERTY_NAME_STX.equalsIgnoreCase(propertyName)) { getChildForm().handleRasterPropertyChange(event, raster); } else if (RasterDataNode.isValidMaskProperty(propertyName)) { getStx(raster); } } } } @Override public void selectionChange(ProductSceneView oldValue, ProductSceneView newValue) { if (getFormModel().getProductSceneView() == oldValue) { setProductSceneView(null); } setProductSceneView(newValue); if (this.brightnessContrastPanel != null) { if (oldValue != null) { this.brightnessContrastPanel.productSceneViewDeselected(oldValue); } if (newValue != null) { this.brightnessContrastPanel.productSceneViewSelected(newValue); } } } private class SceneViewImageInfoChangeListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { if (ProductSceneView.PROPERTY_NAME_IMAGE_INFO.equals(evt.getPropertyName())) { boolean correctFormForRaster = (getFormModel().getRaster() == getFormModel().getProductSceneView().getRaster()); if (correctFormForRaster) { ImageInfo modifiedImageInfo = (ImageInfo) evt.getNewValue(); getFormModel().setModifiedImageInfo(modifiedImageInfo); getChildForm().updateFormModel(getFormModel()); } } } } }
45,347
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ImageInfoEditor2.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ImageInfoEditor2.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.colormanip; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import com.bc.ceres.swing.ActionLabel; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.math.MathUtils; import org.esa.snap.ui.ImageInfoEditor; import org.esa.snap.ui.ImageInfoEditorModel; import org.esa.snap.ui.UIUtils; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.SwingWorker; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Color; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.text.DecimalFormat; /** * * @author Brockmann Consult * @author Daniel Knowles (NASA) * @author Bing Yang (NASA) */ // OCT 2019 - Knowles / Yang // - Added method to override abstract method "checkSliderRangeCompatibility". // - Added method to override abstract method "checkLogCompatibility". // Feb 2020 - Knowles // - Added calls to reset the color scheme selector class ImageInfoEditor2 extends ImageInfoEditor { private final ColorManipulationForm parentForm; private boolean showExtraInfo; ImageInfoEditor2(final ColorManipulationForm parentForm) { this.parentForm = parentForm; setLayout(new BorderLayout()); PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); boolean showExtraInformation = configuration.getPropertyBool(ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_KEY, ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_DEFAULT); setShowExtraInfo(showExtraInformation); addPropertyChangeListener("model", new ModelChangeHandler()); } public boolean getShowExtraInfo() { return showExtraInfo; } public ColorManipulationForm getParentForm() { return parentForm; } public void setShowExtraInfo(boolean showExtraInfo) { boolean oldValue = this.showExtraInfo; if (oldValue != showExtraInfo) { this.showExtraInfo = showExtraInfo; updateStxOverlayComponent(); firePropertyChange("showExtraInfo", oldValue, this.showExtraInfo); } } private void updateStxOverlayComponent() { removeAll(); add(createStxOverlayComponent(), BorderLayout.NORTH); revalidate(); repaint(); } private JPanel createStxOverlayComponent() { JPanel stxOverlayComponent = new JPanel(new FlowLayout(FlowLayout.RIGHT)); stxOverlayComponent.setOpaque(false); final ImageInfoEditorModel model = getModel(); if (!showExtraInfo || model == null) { return stxOverlayComponent; } stxOverlayComponent.setBorder(new EmptyBorder(4, 0, 0, 8)); JComponent labels = new JComponent() { @Override protected void paintComponent(Graphics g) { g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); } }; labels.setBorder(new EmptyBorder(0, 2, 0, 2)); labels.setLayout(new GridLayout(-1, 1)); labels.setBackground(new Color(255, 255, 255, 127)); stxOverlayComponent.add(labels); labels.add(new JLabel("Name: " + model.getParameterName())); labels.add(new JLabel("Unit: " + model.getParameterUnit())); final Stx stx = model.getSampleStx(); if (stx == null) { return stxOverlayComponent; } labels.add(new JLabel("Min: " + getValueForDisplay(model.getMinSample()))); labels.add(new JLabel("Max: " + getValueForDisplay(model.getMaxSample()))); if (stx.getResolutionLevel() > 0 && model.getSampleScaling() == Scaling.IDENTITY) { final ActionLabel label = new ActionLabel("Rough statistics!"); label.setToolTipText("Click to compute accurate statistics."); label.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { askUser(); } }); labels.add(label); } return stxOverlayComponent; } private String getValueForDisplay(double value) { if (!Double.isNaN(value)) { // prevents NaN to be converted to zero if (value < 0.001 && value > -0.001 && value != 0.0) { return new DecimalFormat("0.##E0").format(value); } value = MathUtils.round(value, 1000.0); } return "" + value; } void askUser() { final int i = JOptionPane.showConfirmDialog(this, "Compute accurate statistics?\n" + "Note that this action may take some time.", "Question", JOptionPane.YES_NO_OPTION); if (i == JOptionPane.YES_OPTION) { SwingWorker sw = new StxComputer(); sw.execute(); } } public void updateShowExtraInformationFromPreferences() { PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); boolean showExtraInformation = configuration.getPropertyBool(ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_KEY, ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_DEFAULT); setShowExtraInfo(showExtraInformation); } @Override protected void applyChanges() { resetColorSchemeSelector(); updateShowExtraInformationFromPreferences(); parentForm.applyChanges(); } private class ModelChangeHandler implements PropertyChangeListener, ChangeListener { @Override public void stateChanged(ChangeEvent e) { updateStxOverlayComponent(); } @Override public void propertyChange(PropertyChangeEvent evt) { if (!"model".equals(evt.getPropertyName())) { return; } final ImageInfoEditorModel oldModel = (ImageInfoEditorModel) evt.getOldValue(); final ImageInfoEditorModel newModel = (ImageInfoEditorModel) evt.getNewValue(); if (oldModel != null) { oldModel.removeChangeListener(this); } if (newModel != null) { newModel.addChangeListener(this); } updateStxOverlayComponent(); } } private class StxComputer extends ProgressMonitorSwingWorker { private StxComputer() { super(ImageInfoEditor2.this, "Computing statistics"); } @Override protected Object doInBackground(ProgressMonitor pm) throws Exception { UIUtils.setRootFrameWaitCursor(ImageInfoEditor2.this); if (parentForm.getFormModel().isValid()) { final RasterDataNode[] rasters = parentForm.getFormModel().getRasters(); try { pm.beginTask("Computing statistics", rasters.length); for (RasterDataNode raster : rasters) { raster.getStx(true, SubProgressMonitor.create(pm, 1)); } } finally { pm.done(); } } return null; } @Override protected void done() { UIUtils.setRootFrameDefaultCursor(ImageInfoEditor2.this); } } @Override protected boolean checkLogCompatibility(double value, String componentName, boolean isLogScaled) { return ColorUtils.checkLogCompatibility(value, componentName, isLogScaled); } @Override protected boolean checkSliderRangeCompatibility(double value, double min, double max) { return ColorUtils.checkSliderRangeCompatibility (value, min, max); } private void resetColorSchemeSelector() { ColorSchemeInfo colorSchemeNoneInfo = ColorSchemeManager.getDefault().getNoneColorSchemeInfo(); parentForm.getFormModel().getProductSceneView().getImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); parentForm.getFormModel().getModifiedImageInfo().setColorSchemeInfo(colorSchemeNoneInfo); } }
9,550
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Continuous3BandGraphicalForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/Continuous3BandGraphicalForm.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.colormanip; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.ValueRange; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.ColorPaletteDef; import org.esa.snap.core.datamodel.ImageInfo; 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.util.PropertyMap; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.ImageInfoEditorModel; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.JComboBox; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import java.awt.BorderLayout; import java.awt.Component; import java.awt.FlowLayout; import java.beans.PropertyChangeEvent; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.*; import static org.esa.snap.core.datamodel.ColorManipulationDefaults.PROPERTY_ZOOM_VERTICAL_BUTTONS_DEFAULT; public class Continuous3BandGraphicalForm implements ColorManipulationChildForm { private final ColorManipulationForm parentForm; private final ImageInfoEditor2 imageInfoEditor; private final ImageInfoEditorSupport imageInfoEditorSupport; private final JPanel contentPanel; private final ImageInfoEditorModel3B[] models; private final RasterDataNode[] initialChannelSources; private final RasterDataNode[] currentChannelSources; private final List<RasterDataNode> channelSourcesList; private final MoreOptionsForm moreOptionsForm; private int channel; private static final String GAMMA_PROPERTY = "gamma"; double gamma = 1.0; private static final String CHANNEL_SOURCE_NAME_PROPERTY = "channelSourceName"; String channelSourceName = ""; public Continuous3BandGraphicalForm(final ColorManipulationForm parentForm) { this.parentForm = parentForm; imageInfoEditor = new ImageInfoEditor2(parentForm); imageInfoEditorSupport = new ImageInfoEditorSupport(imageInfoEditor, false); moreOptionsForm = new MoreOptionsForm(this, parentForm.getFormModel().canUseHistogramMatching()); models = new ImageInfoEditorModel3B[3]; initialChannelSources = new RasterDataNode[3]; currentChannelSources = new RasterDataNode[3]; channelSourcesList = new ArrayList<>(32); channel = 0; final Property channelSourceNameModel = Property.createForField(this, CHANNEL_SOURCE_NAME_PROPERTY, ""); JComboBox channelSourceNameBox = new JComboBox(); channelSourceNameBox.setEditable(false); final Property gammaModel = Property.createForField(this, GAMMA_PROPERTY, 1.0); gammaModel.getDescriptor().setValueRange(new ValueRange(1.0 / 10.0, 10.0)); gammaModel.getDescriptor().setDefaultValue(1.0); JTextField gammaField = new JTextField(); gammaField.setColumns(6); gammaField.setHorizontalAlignment(JTextField.RIGHT); moreOptionsForm.getBindingContext().getPropertySet().addProperty(channelSourceNameModel); moreOptionsForm.getBindingContext().bind(CHANNEL_SOURCE_NAME_PROPERTY, channelSourceNameBox); moreOptionsForm.getBindingContext().getPropertySet().addProperty(gammaModel); moreOptionsForm.getBindingContext().bind(GAMMA_PROPERTY, gammaField); moreOptionsForm.addRow(new JLabel("Source band: "), channelSourceNameBox); moreOptionsForm.addRow(new JLabel("Gamma non-linearity: "), gammaField); final PropertyContainer propertyContainer = new PropertyContainer(); propertyContainer.addProperty(Property.createForField(this, "channel", 0)); propertyContainer.getProperty("channel").getDescriptor().setValueSet(new ValueSet(new Integer[]{0, 1, 2})); final BindingContext bindingContext = new BindingContext(propertyContainer); JRadioButton rChannelButton = new JRadioButton("Red"); JRadioButton gChannelButton = new JRadioButton("Green"); JRadioButton bChannelButton = new JRadioButton("Blue"); rChannelButton.setName("rChannelButton"); gChannelButton.setName("gChannelButton"); bChannelButton.setName("bChannelButton"); final ButtonGroup channelButtonGroup = new ButtonGroup(); channelButtonGroup.add(rChannelButton); channelButtonGroup.add(gChannelButton); channelButtonGroup.add(bChannelButton); bindingContext.bind("channel", channelButtonGroup); bindingContext.addPropertyChangeListener("channel", evt -> acknowledgeChannel()); final JPanel channelButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); channelButtonPanel.add(rChannelButton); channelButtonPanel.add(gChannelButton); channelButtonPanel.add(bChannelButton); contentPanel = new JPanel(new BorderLayout(2, 2)); contentPanel.add(channelButtonPanel, BorderLayout.NORTH); contentPanel.add(imageInfoEditor, BorderLayout.CENTER); moreOptionsForm.getBindingContext().addPropertyChangeListener(GAMMA_PROPERTY, evt -> handleGammaChanged()); moreOptionsForm.getBindingContext().addPropertyChangeListener(CHANNEL_SOURCE_NAME_PROPERTY, this::handleChannelSourceNameChanged); } public Component getContentPanel() { return contentPanel; } @Override public ColorManipulationForm getParentForm() { return parentForm; } @Override public void handleFormShown(ColorFormModel formModel) { RasterDataNode[] rasters = formModel.getRasters(); initialChannelSources[0] = rasters[0]; initialChannelSources[1] = rasters[1]; initialChannelSources[2] = rasters[2]; updateFormModel(formModel); parentForm.revalidateToolViewPaneControl(); } @Override public void handleFormHidden(ColorFormModel formModel) { imageInfoEditor.setModel(null); channelSourcesList.clear(); Arrays.fill(models, null); Arrays.fill(initialChannelSources, null); Arrays.fill(currentChannelSources, null); } @Override public void updateFormModel(ColorFormModel formModel) { RasterDataNode[] rasters = formModel.getRasters(); currentChannelSources[0] = rasters[0]; currentChannelSources[1] = rasters[1]; currentChannelSources[2] = rasters[2]; final Band[] availableBands = formModel.getProduct().getBands(); channelSourcesList.clear(); appendToChannelSources(currentChannelSources); appendToChannelSources(initialChannelSources); appendToChannelSources(availableBands); for (int i = 0; i < models.length; i++) { ImageInfoEditorModel3B oldModel = models[i]; models[i] = new ImageInfoEditorModel3B(parentForm.getFormModel().getModifiedImageInfo(), i); Continuous1BandGraphicalForm.setDisplayProperties(models[i], currentChannelSources[i]); if (oldModel != null) { models[i].setHistogramViewGain(oldModel.getHistogramViewGain()); models[i].setMinHistogramViewSample(oldModel.getMinHistogramViewSample()); models[i].setMaxHistogramViewSample(oldModel.getMaxHistogramViewSample()); } } final String[] sourceNames = new String[channelSourcesList.size()]; for (int i = 0; i < channelSourcesList.size(); i++) { sourceNames[i] = channelSourcesList.get(i).getName(); } moreOptionsForm.getBindingContext().getPropertySet().getProperty(CHANNEL_SOURCE_NAME_PROPERTY).getDescriptor().setValueSet(new ValueSet(sourceNames)); acknowledgeChannel(); } private void appendToChannelSources(RasterDataNode[] rasterDataNodes) { for (RasterDataNode channelSource : rasterDataNodes) { if (!channelSourcesList.contains(channelSource)) { channelSourcesList.add(channelSource); } } } @Override public void resetFormModel(ColorFormModel formModel) { updateFormModel(formModel); imageInfoEditor.computeZoomOutToFullHistogramm(); } @Override public void handleRasterPropertyChange(ProductNodeEvent event, RasterDataNode raster) { ImageInfoEditorModel model = imageInfoEditor.getModel(); if (model != null) { Continuous1BandGraphicalForm.setDisplayProperties(model, raster); } if (event.getPropertyName().equals(RasterDataNode.PROPERTY_NAME_STX)) { acknowledgeChannel(); } } @Override public RasterDataNode[] getRasters() { return currentChannelSources.clone(); } @Override public MoreOptionsForm getMoreOptionsForm() { return moreOptionsForm; } @Override public AbstractButton[] getToolButtons() { PropertyMap configuration = parentForm.getFormModel().getProductSceneView().getSceneImage().getConfiguration(); boolean range100 = configuration.getPropertyBool(PROPERTY_100_PERCENT_BUTTON_KEY, PROPERTY_100_PERCENT_BUTTON_DEFAULT); boolean range95 = configuration.getPropertyBool(PROPERTY_95_PERCENT_BUTTON_KEY, PROPERTY_95_PERCENT_BUTTON_DEFAULT); boolean range1Sigma = configuration.getPropertyBool(PROPERTY_1_SIGMA_BUTTON_KEY, PROPERTY_1_SIGMA_BUTTON_DEFAULT); boolean range2Sigma = configuration.getPropertyBool(PROPERTY_2_SIGMA_BUTTON_KEY, PROPERTY_2_SIGMA_BUTTON_DEFAULT); boolean range3Sigma = configuration.getPropertyBool(PROPERTY_3_SIGMA_BUTTON_KEY, PROPERTY_3_SIGMA_BUTTON_DEFAULT); boolean showZoomVerticalButtons = configuration.getPropertyBool(PROPERTY_ZOOM_VERTICAL_BUTTONS_KEY, PROPERTY_ZOOM_VERTICAL_BUTTONS_DEFAULT); boolean showExtraInformationButtons = configuration.getPropertyBool(PROPERTY_INFORMATION_BUTTON_KEY, PROPERTY_INFORMATION_BUTTON_DEFAULT); ArrayList<AbstractButton> abstractButtonArrayList = new ArrayList<AbstractButton>(); if (range1Sigma) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch1SigmaButton); } if (range2Sigma) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch2SigmaButton); } if (range3Sigma) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch3SigmaButton); } if (range95) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch95Button); } if (range100) { abstractButtonArrayList.add(imageInfoEditorSupport.autoStretch100Button); } abstractButtonArrayList.add(imageInfoEditorSupport.setRGBminmax); if (showZoomVerticalButtons) { abstractButtonArrayList.add(imageInfoEditorSupport.zoomInVButton); abstractButtonArrayList.add(imageInfoEditorSupport.zoomOutVButton); } abstractButtonArrayList.add(imageInfoEditorSupport.zoomHorizontalButton); if (showExtraInformationButtons) { abstractButtonArrayList.add(imageInfoEditorSupport.showExtraInfoButton); } final AbstractButton[] abstractButtonArray = new AbstractButton[abstractButtonArrayList.size()]; int i = 0; for (AbstractButton abstractButton : abstractButtonArrayList) { abstractButtonArray[i] = abstractButton; i++; } return abstractButtonArray; } private void acknowledgeChannel() { RasterDataNode channelSource = currentChannelSources[channel]; final ImageInfoEditorModel3B model = models[channel]; Continuous1BandGraphicalForm.setDisplayProperties(model, channelSource); imageInfoEditor.setModel(model); moreOptionsForm.getBindingContext().getBinding(CHANNEL_SOURCE_NAME_PROPERTY).setPropertyValue(channelSource.getName()); moreOptionsForm.getBindingContext().getBinding(GAMMA_PROPERTY).setPropertyValue(gamma); } private void handleGammaChanged() { imageInfoEditor.getModel().setGamma(gamma); parentForm.applyChanges(); } private void handleChannelSourceNameChanged(PropertyChangeEvent evt) { RasterDataNode newChannelSource = null; for (RasterDataNode rasterDataNode : channelSourcesList) { if (rasterDataNode.getName().equals(channelSourceName)) { newChannelSource = rasterDataNode; break; } } if (newChannelSource == null) { AbstractDialog.showErrorDialog(contentPanel, MessageFormat.format("Unknown band: ''{0}''", channelSourceName), "Error"); return; } final RasterDataNode oldChannelSource = currentChannelSources[channel]; if (newChannelSource != oldChannelSource) { final Stx stx = parentForm.getStx(newChannelSource); if (stx != null) { currentChannelSources[channel] = newChannelSource; final ImageInfo imageInfo = parentForm.getFormModel().getModifiedImageInfo(); imageInfo.getRgbChannelDef().setSourceName(channel, channelSourceName); final ImageInfo info = newChannelSource.getImageInfo(com.bc.ceres.core.ProgressMonitor.NULL); final ColorPaletteDef def = info.getColorPaletteDef(); if (def != null) { imageInfo.getRgbChannelDef().setMinDisplaySample(channel, def.getMinDisplaySample()); imageInfo.getRgbChannelDef().setMaxDisplaySample(channel, def.getMaxDisplaySample()); } models[channel] = new ImageInfoEditorModel3B(imageInfo, channel); Continuous1BandGraphicalForm.setDisplayProperties(models[channel], newChannelSource); acknowledgeChannel(); parentForm.applyChanges(); } else { final Object value = evt.getOldValue(); moreOptionsForm.getBindingContext().getBinding(CHANNEL_SOURCE_NAME_PROPERTY).setPropertyValue(value == null ? "" : value); } } } }
15,256
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorFormModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/colormanip/ColorFormModel.java
package org.esa.snap.rcp.colormanip; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.util.NamingConvention; import org.esa.snap.ui.product.ProductSceneView; import javax.swing.JLabel; import javax.swing.SwingConstants; import java.awt.Component; /** * @author Norman Fomferra */ public class ColorFormModel { private ProductSceneView productSceneView; private ImageInfo modifiedImageInfo; public String getTitlePrefix() { return Bundle.CTL_ColorManipulationTopComponent_Name(); } public ProductSceneView getProductSceneView() { return productSceneView; } public void setProductSceneView(ProductSceneView productSceneView) { this.productSceneView = productSceneView; } public RasterDataNode getRaster() { return getProductSceneView().getRaster(); } public RasterDataNode[] getRasters() { return getProductSceneView().getRasters(); } public void setRasters(RasterDataNode[] rasters) { getProductSceneView().setRasters(rasters); } public ImageInfo getOriginalImageInfo() { return getProductSceneView().getImageInfo(); } /** * @return The image info being edited. */ public ImageInfo getModifiedImageInfo() { return modifiedImageInfo; } /** * Sets modifiedImageInfo to a copy of the given imageInfo. * @param imageInfo The image info from which a copy is made which will then be edited. */ public void setModifiedImageInfo(ImageInfo imageInfo) { this.modifiedImageInfo = imageInfo.createDeepCopy(); } public void applyModifiedImageInfo() { getProductSceneView().setImageInfo(getModifiedImageInfo()); } public String getModelName() { return getProductSceneView().getSceneName(); } public Product getProduct() { return getProductSceneView().getProduct(); } public boolean isValid() { return getProductSceneView() != null; } public boolean isContinuous3BandImage() { return isValid() && getProductSceneView().isRGB(); } public boolean isContinuous1BandImage() { return isValid() && !getProductSceneView().isRGB() && getRaster() instanceof Band && !((Band) getRaster()).isIndexBand(); } public boolean isDiscrete1BandImage() { return isValid() && !getProductSceneView().isRGB() && getRaster() instanceof Band && ((Band) getRaster()).isIndexBand(); } public boolean canUseHistogramMatching() { return true; } public boolean isMoreOptionsFormCollapsedOnInit() { return true; } void modifyMoreOptionsForm(MoreOptionsForm moreOptionsForm) { } void updateMoreOptionsFromImageInfo(MoreOptionsForm moreOptionsForm) { } void updateImageInfoFromMoreOptions(MoreOptionsForm moreOptionsForm) { } public Component createEmptyContentPanel() { return new JLabel("<html>This tool window is used to manipulate the<br>" + "<b>" + NamingConvention.COLOR_LOWER_CASE + "ing of images</b> shown in an image view.<br>" + " Right now, there is no selected image view.", SwingConstants.CENTER); } }
3,240
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SnapUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/scripting/SnapUtils.java
package org.esa.snap.rcp.scripting; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.util.Exceptions; import org.openide.windows.Mode; import org.openide.windows.TopComponent; import org.openide.windows.WindowManager; import javax.swing.Action; import java.io.IOException; /** * Provides various utility functions allowing scripting clients to register actions and windows * for the SNAP Desktop application. * <p> * The following methods can be used to dynamically add/remove actions and action references to/from * the SNAP Desktop application: * <ul> * <li>{@link SnapUtils#addAction(Action, String)}</li> * <li>{@link SnapUtils#removeAction(FileObject)}</li> * </ul> * The {@code addAction()} methods all return "file objects" which live in the NetBeans * Platform's virtual file system. * These object can be used to create references to the actions they represent in various places * such as menus and tool bars: * <ul> * <li>{@link SnapUtils#addActionReference(FileObject, String, Integer)}</li> * <li>{@link SnapUtils#removeActionReference(FileObject)}</li> * </ul> * <p> * To open a new window in the SNAP Desktop application, the following methods can be used: * <ul> * <li>{@link SnapUtils#openWindow(TopComponent)}</li> * <li>{@link SnapUtils#openWindow(TopComponent, boolean)}</li> * <li>{@link SnapUtils#openWindow(TopComponent, String)}</li> * <li>{@link SnapUtils#openWindow(TopComponent, String, boolean)}</li> * </ul> * * @author Norman Fomferra */ public class SnapUtils { private static final String INSTANCE_PREFIX = "TransientAction-"; private static final String INSTANCE_SUFFIX = ".instance"; private static final String SHADOW_SUFFIX = ".shadow"; /** * Adds an action into the folder {@code Menu/Tools} of the SNAP Desktop / NetBeans file system. * * @param action The action. * @return The file object representing the action. */ public synchronized static FileObject addAction(Action action) { return addAction(action, "Menu/Tools"); } /** * Adds an action into the folder given by {@code path} of the SNAP Desktop / NetBeans file system. * * @param action The action. * @param path The folder path. * @return The file object representing the action. */ public synchronized static FileObject addAction(Action action, String path) { return addAction(action, path, null); } /** * Adds an action into the folder given by {@code path} of the SNAP Desktop / NetBeans file system at the given {@code position}. * * @param action The action. * @param path The folder path. * @param position The position within the folder. May be {@code null}. * @return The file object representing the action. */ public synchronized static FileObject addAction(Action action, String path, Integer position) { FileObject configRoot = FileUtil.getConfigRoot(); try { FileObject actionFile = FileUtil.createData(configRoot, getActionDataPath(path, action)); actionFile.setAttribute("instanceCreate", new TransientAction(action, actionFile.getPath())); if (position != null) { actionFile.setAttribute("position", position); } return actionFile; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; } /** * Adds an action references into the folder given by {@code path} of the SNAP Desktop / NetBeans file system at the given {@code position}. * The following are standard folders in SNAP Desktop/NetBeans where actions and action references may be placed to * become visible: * <ol> * <li>{@code Menu/*} - the main menu</li> * <li>{@code Toolbars/*} - the main tool bar</li> * </ol> * * @param instanceFile The file object representing an action instance. * @param path The folder path. * @param position The position within the folder. May be {@code null}. * @return The file object representing the action reference. */ public synchronized static FileObject addActionReference(FileObject instanceFile, String path, Integer position) { Action actualAction = TransientAction.getAction(instanceFile.getPath()); if (actualAction == null) { return null; } String shadowId = instanceFile.getName() + SHADOW_SUFFIX; FileObject configRoot = FileUtil.getConfigRoot(); try { FileObject actionFile = FileUtil.createData(configRoot, path + "/" + shadowId); actionFile.setAttribute("originalFile", instanceFile.getPath()); if (position != null) { actionFile.setAttribute("position", position); } return actionFile; } catch (IOException ex) { Exceptions.printStackTrace(ex); } return null; } public synchronized static boolean removeAction(FileObject actionFile) { if (TransientAction.hasAction(actionFile.getPath())) { try { actionFile.delete(); TransientAction.removeAction(actionFile.getPath()); return true; } catch (IOException ex) { Exceptions.printStackTrace(ex); } } return false; } public synchronized static boolean removeActionReference(FileObject actionReferenceFile) { Object originalFile = actionReferenceFile.getAttribute("originalFile"); if (originalFile != null) { String originalPath = originalFile.toString(); int slashPos = originalPath.lastIndexOf('/'); if (slashPos > 0 && originalPath.substring(slashPos + 1).startsWith(INSTANCE_PREFIX) && originalPath.endsWith(INSTANCE_SUFFIX)) { try { actionReferenceFile.delete(); return true; } catch (IOException ex) { Exceptions.printStackTrace(ex); } } } return false; } /** * Opens a new window in SNAP Desktop in the "explorer" location. * * @param window The window which must must be an instance of {@link TopComponent}. * @see #openWindow(TopComponent, String, boolean) */ public static void openWindow(TopComponent window) { openWindow(window, false); } /** * Opens a new window in SNAP Desktop in the "explorer" location. * * @param window The window which must must be an instance of {@link TopComponent}. * @param requestActive {@code true} if a request will be made to activate the window after opening it. * @see #openWindow(TopComponent, String, boolean) */ public static void openWindow(TopComponent window, boolean requestActive) { openWindow(window, "explorer", requestActive); } /** * Opens a new window in SNAP Desktop at the given location. * * @param window The window which must must be an instance of {@link TopComponent}. * @param location The location where the window should appear when it is first opened. * @see #openWindow(TopComponent, String, boolean) */ public static void openWindow(TopComponent window, String location) { openWindow(window, location, false); } /** * Opens a new window in SNAP Desktop. * * @param window The window which must must be an instance of {@link TopComponent}. * @param location The location where the window should appear when it is first opened. * Possible docking areas are * "explorer" (upper left), "navigator" (lower left), "properties" (upper right), * "output" (bottom). You may choose "floating" to not dock the window at all. Note * that this mode requires explicitly setting the window's position and size. * @param requestActive {@code true} if a request will be made to activate the window after opening it. */ public static void openWindow(TopComponent window, String location, boolean requestActive) { WindowManager.getDefault().invokeWhenUIReady(() -> { Mode mode = WindowManager.getDefault().findMode(location); if (mode != null) { mode.dockInto(window); } window.open(); if (requestActive) { window.requestActive(); } }); } private static String getActionDataPath(String folderPath, Action delegate) { return folderPath + "/" + getActionInstanceName(delegate); } private static String getActionInstanceName(Action delegate) { Object commandKey = delegate.getValue(Action.ACTION_COMMAND_KEY); String id; if (commandKey != null && !commandKey.toString().isEmpty()) { id = commandKey.toString(); } else { id = delegate.getClass().getName(); } id = id.replace('/', '-').replace('.', '-').replace('$', '-'); if (!id.startsWith(INSTANCE_PREFIX)) { id = INSTANCE_PREFIX + id; } if (!id.endsWith(INSTANCE_SUFFIX)) { id += INSTANCE_SUFFIX; } return id; } }
9,471
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TransientTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/scripting/TransientTopComponent.java
package org.esa.snap.rcp.scripting; import org.openide.util.Lookup; import org.openide.windows.TopComponent; /** * The {@code TransientTopComponent} is a convenience base class for SNAP Desktop * windows that are registered through scripts. * <p> * Script programmers may use this class as a base class for their windows * in order to avoid serialisation errors caused by the NetBeans Platform. * The serialisation of windows occurs in order store and restore window state. * <p> * A {@code TransientTopComponent} differs from the "normal" {@link TopComponent} class * only in that it overrides the {@link TopComponent#getPersistenceType()} to always return * {@link TopComponent#PERSISTENCE_NEVER}. * * @author Norman Fomferra */ public class TransientTopComponent extends TopComponent { public TransientTopComponent() { this(null); } public TransientTopComponent(Lookup lookup) { super(lookup); } @Override public final int getPersistenceType() { return PERSISTENCE_NEVER; } }
1,049
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TransientAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/scripting/TransientAction.java
package org.esa.snap.rcp.scripting; import com.bc.ceres.core.Assert; import org.esa.snap.core.util.SystemUtils; import javax.swing.Action; import java.awt.event.ActionEvent; import java.beans.PropertyChangeListener; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * A proxy action which can be used to programmatically register delegate actions which will *not* be serialized * into the NetBeans filesystem. * The proxy protects the delegate action from being serialized/deserialized by the NetBeans Platform * by putting the delegate into a static hash table. On serialisation request only the file system path is serialized * and used to look up the delegate action later on deserialisation request. * * @author Norman Fomferra */ public class TransientAction implements Action, Serializable { private static final long serialVersionUID = 3069372659219673560L; private static final Map<String, Action> DELEGATES = new HashMap<>(); private String path; private Action delegate; TransientAction(Action delegate, String path) { Assert.notNull(delegate, "delegate"); Assert.notNull(path, "path"); Assert.argument(path.endsWith(".instance"), "path"); Assert.argument(path.contains("/"), "path"); this.path = path; this.delegate = delegate; Action oldDelegate = DELEGATES.put(path, delegate); if (oldDelegate != null) { SystemUtils.LOG.info(String.format("Proxy action %s registered once more. Replacing the old action.%n", this.path)); } SystemUtils.LOG.info(String.format("Proxy action added as %s%n", this.path)); } static Action getAction(String path1) { return DELEGATES.get(path1); } static boolean hasAction(String path) { return DELEGATES.containsKey(path); } static Action removeAction(String path1) { return DELEGATES.remove(path1); } public Action getDelegate() { return delegate; } public String getPath() { return path; } @Override public Object getValue(String key) { return delegate.getValue(key); } @Override public void putValue(String key, Object value) { delegate.putValue(key, value); } @Override public void setEnabled(boolean b) { delegate.setEnabled(b); } @Override public boolean isEnabled() { return delegate.isEnabled(); } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { delegate.addPropertyChangeListener(listener); } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { delegate.removePropertyChangeListener(listener); } @Override public void actionPerformed(ActionEvent e) { delegate.actionPerformed(e); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { String path = in.readUTF(); Action delegate = DELEGATES.get(path); if (delegate == null) { throw new IOException(String.format("Action delegate not found for file %s.\n" + "Please make sure to call removeAction() before SNAP shuts down.", path)); } this.path = path; this.delegate = delegate; SystemUtils.LOG.info(String.format("Deserialized proxy action %s%n", this.path)); } private void writeObject(ObjectOutputStream out) throws IOException { out.writeUTF(path); SystemUtils.LOG.info(String.format("Serialized proxy action %s%n", this.path)); } }
3,793
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MagicWandModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/magicwand/MagicWandModel.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.magicwand; import com.bc.ceres.core.Assert; import com.bc.ceres.glevel.MultiLevelImage; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.converters.SingleValueConverter; 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.dataop.barithm.BandArithmetic; import org.esa.snap.core.dataop.barithm.RasterDataSymbol; import org.esa.snap.core.gpf.common.resample.Resample; import org.esa.snap.core.jexp.ParseException; import org.esa.snap.core.jexp.Term; import org.esa.snap.core.util.ObjectUtils; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.core.util.StringUtils; import org.esa.snap.rcp.util.MultiSizeIssue; import javax.media.jai.Interpolation; import java.awt.*; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Utilities for the magic wand tool (interactor). * * @author Norman Fomferra * @since BEAM 4.10 */ public class MagicWandModel implements Cloneable { public enum PickMode { SINGLE, PLUS, MINUS, } public enum SpectrumTransform { INTEGRAL, IDENTITY, DERIVATIVE, } public enum PixelTest { DISTANCE, AVERAGE, LIMITS, } public static final String MAGIC_WAND_MASK_NAME = "magic_wand"; private double tolerance; private double minTolerance; private double maxTolerance; private ArrayList<String> bandNames; private SpectrumTransform spectrumTransform; private PixelTest pixelTest; private boolean normalize; private PickMode pickMode; private ArrayList<double[]> plusSpectra; private ArrayList<double[]> minusSpectra; private transient ArrayList<Listener> listeners; public MagicWandModel() { pickMode = PickMode.SINGLE; pixelTest = PixelTest.DISTANCE; spectrumTransform = SpectrumTransform.IDENTITY; bandNames = new ArrayList<>(); plusSpectra = new ArrayList<>(); minusSpectra = new ArrayList<>(); tolerance = 0.1; minTolerance = 0.0; maxTolerance = 1.0; } public void addListener(Listener listener) { if (listeners == null) { listeners = new ArrayList<>(); } listeners.add(listener); } public void removeListeners() { if (listeners != null) { listeners.clear(); listeners = null; } } public void fireModelChanged(boolean recomputeMask) { if (listeners != null) { for (Listener listener : listeners) { listener.modelChanged(this, recomputeMask); } } } @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException") @Override public MagicWandModel clone() { try { MagicWandModel clone = (MagicWandModel) super.clone(); clone.bandNames = new ArrayList<>(bandNames); clone.plusSpectra = new ArrayList<>(plusSpectra); clone.minusSpectra = new ArrayList<>(minusSpectra); clone.listeners = null; return clone; } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } } public void assign(MagicWandModel other) { pixelTest = other.pixelTest; spectrumTransform = other.spectrumTransform; pickMode = other.pickMode; tolerance = other.tolerance; minTolerance = other.minTolerance; maxTolerance = other.maxTolerance; bandNames = new ArrayList<>(other.bandNames); plusSpectra = new ArrayList<>(other.plusSpectra); minusSpectra = new ArrayList<>(other.minusSpectra); fireModelChanged(true); } int getSpectrumCount() { return plusSpectra.size() + minusSpectra.size(); } int getPlusSpectrumCount() { return plusSpectra.size(); } int getMinusSpectrumCount() { return minusSpectra.size(); } int getBandCount() { return bandNames.size(); } void addSpectrum(double... spectrum) { Assert.argument(spectrum.length == bandNames.size(), "spectrum size does not match # selected bands"); if (pickMode == PickMode.SINGLE) { plusSpectra.clear(); minusSpectra.clear(); plusSpectra.add(spectrum); } else if (pickMode == PickMode.PLUS) { plusSpectra.add(spectrum); } else if (pickMode == PickMode.MINUS) { minusSpectra.add(spectrum); } fireModelChanged(true); } void clearSpectra() { plusSpectra.clear(); minusSpectra.clear(); fireModelChanged(true); } public List<String> getBandNames() { return Collections.unmodifiableList(bandNames); } public void setBandNames(String... bandNames) { setBandNames(Arrays.asList(bandNames)); } public void setBandNames(List<String> bandNames) { plusSpectra.clear(); minusSpectra.clear(); this.bandNames = new ArrayList<>(bandNames); fireModelChanged(true); } public PickMode getPickMode() { return pickMode; } public void setPickMode(PickMode pickMode) { this.pickMode = pickMode; fireModelChanged(false); } public PixelTest getPixelTest() { return pixelTest; } public void setPixelTest(PixelTest pixelTest) { this.pixelTest = pixelTest; fireModelChanged(false); } public SpectrumTransform getSpectrumTransform() { return spectrumTransform; } public void setSpectrumTransform(SpectrumTransform spectrumTransform) { this.spectrumTransform = spectrumTransform; fireModelChanged(false); } public double getTolerance() { return tolerance; } public void setTolerance(double tolerance) { this.tolerance = tolerance; fireModelChanged(true); } public double getMinTolerance() { return minTolerance; } public void setMinTolerance(double minTolerance) { this.minTolerance = minTolerance; fireModelChanged(false); } public double getMaxTolerance() { return maxTolerance; } public void setMaxTolerance(double maxTolerance) { this.maxTolerance = maxTolerance; fireModelChanged(false); } public void setNormalize(boolean normalize) { this.normalize = normalize; fireModelChanged(false); } public void setSpectralBandNames(Product product) { List<Band> bands = getSpectralBands(product); List<String> bandNames = new ArrayList<>(); for (Band band : bands) { bandNames.add(band.getName()); } if (!bandNames.isEmpty()) { setBandNames(bandNames.toArray(new String[bandNames.size()])); } } public static List<Band> getSpectralBands(Product product) { List<Band> bands = new ArrayList<>(); for (Band band : product.getBands()) { if (band.getSpectralWavelength() > 0.0 || band.getSpectralBandIndex() >= 0) { bands.add(band); } } Collections.sort(bands, new SpectralBandComparator()); return bands; } List<Band> getBands(Product product) { List<String> names = getBandNames(); List<Band> bands = new ArrayList<>(names.size()); for (String name : names) { Band band = product.getBand(name); if (band == null) { return null; } bands.add(band); } return bands; } static void setMagicWandMask(Product product, String expression) { String validMaskExpression; try { validMaskExpression = BandArithmetic.getValidMaskExpression(expression, product, null); } catch (ParseException e) { validMaskExpression = null; } if (validMaskExpression != null) { expression = "(" + validMaskExpression + ") && (" + expression + ")"; } // Current mask final Mask magicWandMask = product.getMaskGroup().get(MAGIC_WAND_MASK_NAME); if (magicWandMask != null) { // The magic wand mask exists. // One must check the rasters size defined in the expression vs the current magic wand mask (in case of multi-size product). try { // Decipher the expression to get the rasters. At this stage we know the rasters have the same size. Term term = BandArithmetic.parseExpression(expression, product); RasterDataSymbol[] rasterDS = BandArithmetic.getRefRasterDataSymbols(term); if (rasterDS.length > 0) { int rastersWidth = rasterDS[0].getRaster().getRasterWidth(); int rastersHeight = rasterDS[0].getRaster().getRasterHeight(); // Current mask = same resolution as bands in expression if (magicWandMask.getRasterWidth() == rastersWidth && magicWandMask.getRasterHeight() == rastersHeight){ // set the new expression to the magicwand mask magicWandMask.getImageConfig().setValue("expression", expression); // TODO compute mask with other resolutions than magicWandMask by resampling //test String mask20Name = MAGIC_WAND_MASK_NAME + "_20"; Mask mask20 = product.getMaskGroup().get(mask20Name); if (mask20 != null) product.getMaskGroup().remove(mask20); MultiLevelImage multiLevel20m = Resample.createInterpolatedMultiLevelImage(magicWandMask.getSourceImage(), magicWandMask.getNoDataValue(), magicWandMask.getImageToModelTransform(), 5490,5490, new Dimension(512,512), product.getBand("B5").getMultiLevelModel(), Interpolation.getInstance(Interpolation.INTERP_NEAREST)); mask20 = new Mask(mask20Name,5490,5490, magicWandMask.getImageType()); ProductUtils.copyGeoCoding(product.getBand("B5"), mask20); mask20.setSourceImage(multiLevel20m); product.addMask(mask20); } else { // Resolution of bands in expression different from current mask // // To avoid false alarm, as at creation mask has product resolution // if (!magicWandMask.getImageConfig().getProperty("expression").getValue().equals("0")) { // MultiSizeIssue.warningMaskForBandsWithDifferentSize(); // } // Delete the current magicWandMask (not the same resolution as bands defined in the expression) product.getMaskGroup().remove(magicWandMask); // Create the mask with the current expression Mask mask = product.addMask(MAGIC_WAND_MASK_NAME, expression, "Magic wand mask", Color.RED, 0.5); // TODO must compute masks with other resolutions than the new magicWandMask by resampling // //test // MultiLevelImage multiLevel10m = Resample.createInterpolatedMultiLevelImage(mask.getSourceImage(),mask.getNoDataValue(),mask.getImageToModelTransform(), // 10980,10980,new Dimension(512,512),product.getBand("B2").getMultiLevelModel(), Interpolation.getInstance(Interpolation.INTERP_NEAREST)); // Mask mask10 = new Mask("test10",10980,10980,mask.getImageType()); // mask10.setSourceImage(multiLevel10m); // ProductUtils.copyGeoCoding(product.getBand("B2"),mask10); // scaleMultiLevelImage(MultiLevelImage masterImage, MultiLevelImage sourceImage, // float[] scalings, GeneralFilterFunction filterFunction, RenderingHints renderingHints, // double noDataValue, Interpolation interpolation) // Set the expression to the new magic wand mask Mask newMagicWandMask = product.getMaskGroup().get(MAGIC_WAND_MASK_NAME); newMagicWandMask.getImageConfig().setValue("expression", expression); } } // if the expression defines no valid raster: do nothing } catch (ParseException pe) { final String msg = String.format("Expression '%s' is invalid.\n", expression); throw new IllegalArgumentException(msg, pe); } } else { // First time : create magic_wand mask with product resolution by default Mask mask = product.addMask(MAGIC_WAND_MASK_NAME, expression, "Magic wand mask", Color.RED, 0.5); // //test // MultiLevelImage multiLevel10m = Resample.createInterpolatedMultiLevelImage(mask.getSourceImage(),mask.getNoDataValue(),mask.getImageToModelTransform(), // 10980,10980,new Dimension(512,512),product.getBand("B2").getMultiLevelModel(), Interpolation.getInstance(Interpolation.INTERP_NEAREST)); // Mask mask10 = new Mask(MAGIC_WAND_MASK_NAME + "_10",10980,10980,mask.getImageType()); // ProductUtils.copyGeoCoding(product.getBand("B2"),mask10); // mask10.setSourceImage(multiLevel10m); // product.addMask(mask10); } } String createMaskExpression() { final String plusPart; final String minusPart; if (getPixelTest() == PixelTest.DISTANCE) { plusPart = getDistancePart(bandNames, spectrumTransform, plusSpectra, tolerance, normalize); minusPart = getDistancePart(bandNames, spectrumTransform, minusSpectra, tolerance, normalize); } else if (getPixelTest() == PixelTest.AVERAGE) { plusPart = getAveragePart(bandNames, spectrumTransform, plusSpectra, tolerance, normalize); minusPart = getAveragePart(bandNames, spectrumTransform, minusSpectra, tolerance, normalize); } else if (getPixelTest() == PixelTest.LIMITS) { plusPart = getLimitsPart(bandNames, spectrumTransform, plusSpectra, tolerance, normalize); minusPart = getLimitsPart(bandNames, spectrumTransform, minusSpectra, tolerance, normalize); } else { throw new IllegalStateException("Unhandled method " + getPixelTest()); } if (plusPart != null && minusPart != null) { return String.format("(%s) && !(%s)", plusPart, minusPart); } else if (plusPart != null) { return plusPart; } else if (minusPart != null) { return String.format("!(%s)", minusPart); } else { return "0"; } } private static String getDistancePart(List<String> bandNames, SpectrumTransform spectrumTransform, List<double[]> spectra, double tolerance, boolean normalize) { if (spectra.isEmpty()) { return null; } final StringBuilder part = new StringBuilder(); for (int i = 0; i < spectra.size(); i++) { double[] spectrum = getSpectrum(spectra.get(i), normalize); if (i > 0) { part.append(" || "); } part.append(getDistanceSubPart(bandNames, spectrumTransform, spectrum, tolerance, normalize)); } return part.toString(); } private static String getAveragePart(List<String> bandNames, SpectrumTransform spectrumTransform, List<double[]> spectra, double tolerance, boolean normalize) { if (spectra.isEmpty()) { return null; } double[] avgSpectrum = getAvgSpectrum(bandNames.size(), spectra, normalize); return getDistanceSubPart(bandNames, spectrumTransform, avgSpectrum, tolerance, normalize); } private static String getLimitsPart(List<String> bandNames, SpectrumTransform spectrumTransform, List<double[]> spectra, double tolerance, boolean normalize) { if (spectra.isEmpty()) { return null; } double[] minSpectrum = getMinSpectrum(bandNames.size(), spectra, tolerance, normalize); double[] maxSpectrum = getMaxSpectrum(bandNames.size(), spectra, tolerance, normalize); return getLimitsSubPart(bandNames, spectrumTransform, minSpectrum, maxSpectrum, normalize); } private static double[] getSpectrum(double[] spectrum, boolean normalize) { if (normalize) { double[] normSpectrum = new double[spectrum.length]; for (int i = 0; i < spectrum.length; i++) { normSpectrum[i] = getSpectrumValue(spectrum, i, true); } return normSpectrum; } else { return spectrum; } } private static double[] getAvgSpectrum(int numBands, List<double[]> spectra, boolean normalize) { double[] avgSpectrum = new double[numBands]; for (double[] spectrum : spectra) { for (int i = 0; i < spectrum.length; i++) { double value = getSpectrumValue(spectrum, i, normalize); avgSpectrum[i] += value; } } for (int i = 0; i < avgSpectrum.length; i++) { avgSpectrum[i] /= spectra.size(); } return avgSpectrum; } private static double[] getMinSpectrum(int numBands, List<double[]> spectra, double tolerance, boolean normalize) { double[] minSpectrum = new double[numBands]; Arrays.fill(minSpectrum, +Double.MAX_VALUE); for (double[] spectrum : spectra) { for (int i = 0; i < spectrum.length; i++) { double value = getSpectrumValue(spectrum, i, normalize); minSpectrum[i] = Math.min(minSpectrum[i], value - tolerance); } } return minSpectrum; } private static double[] getMaxSpectrum(int numBands, List<double[]> spectra, double tolerance, boolean normalize) { double[] maxSpectrum = new double[numBands]; Arrays.fill(maxSpectrum, -Double.MAX_VALUE); for (double[] spectrum : spectra) { for (int i = 0; i < spectrum.length; i++) { double value = getSpectrumValue(spectrum, i, normalize); maxSpectrum[i] = Math.max(maxSpectrum[i], value + tolerance); } } return maxSpectrum; } private static double getSpectrumValue(double[] spectrum, int i, boolean normalize) { return normalize ? spectrum[i] / spectrum[0] : spectrum[i]; } private static String getDistanceSubPart(List<String> bandNames, SpectrumTransform spectrumTransform, double[] spectrum, double tolerance, boolean normalize) { if (bandNames.isEmpty()) { return "0"; } final StringBuilder arguments = new StringBuilder(); appendSpectrumBandNames(bandNames, normalize, arguments); appendSpectrumBandValues(spectrum, arguments); String functionName; if (spectrumTransform == SpectrumTransform.IDENTITY) { functionName = "distance"; } else if (spectrumTransform == SpectrumTransform.DERIVATIVE) { functionName = "distance_deriv"; } else if (spectrumTransform == SpectrumTransform.INTEGRAL) { functionName = "distance_integ"; } else { throw new IllegalStateException("unhandled operator " + spectrumTransform); } if (bandNames.size() == 1) { return String.format("%s(%s) < %s", functionName, arguments, tolerance); } else { return String.format("%s(%s)/%s < %s", functionName, arguments, bandNames.size(), tolerance); } } private static String getLimitsSubPart(List<String> bandNames, SpectrumTransform spectrumTransform, double[] minSpectrum, double[] maxSpectrum, boolean normalize) { if (bandNames.isEmpty()) { return "0"; } final StringBuilder arguments = new StringBuilder(); appendSpectrumBandNames(bandNames, normalize, arguments); appendSpectrumBandValues(minSpectrum, arguments); appendSpectrumBandValues(maxSpectrum, arguments); String functionName; if (spectrumTransform == SpectrumTransform.IDENTITY) { functionName = "inrange"; } else if (spectrumTransform == SpectrumTransform.DERIVATIVE) { functionName = "inrange_deriv"; } else if (spectrumTransform == SpectrumTransform.INTEGRAL) { functionName = "inrange_integ"; } else { throw new IllegalStateException("unhandled operator " + spectrumTransform); } return String.format("%s(%s)", functionName, arguments); } private static void appendSpectrumBandNames(List<String> bandNames, boolean normalize, StringBuilder arguments) { String firstName = BandArithmetic.createExternalName(bandNames.get(0)); for (int i = 0; i < bandNames.size(); i++) { if (i > 0) { arguments.append(","); } String name = BandArithmetic.createExternalName(bandNames.get(i)); if (normalize) { arguments.append(name).append("/").append(firstName); } else { arguments.append(name); } } } private static void appendSpectrumBandValues(double[] spectrum, StringBuilder arguments) { for (double value : spectrum) { arguments.append(","); arguments.append(value); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MagicWandModel that = (MagicWandModel) o; if (Double.compare(that.maxTolerance, maxTolerance) != 0) return false; if (Double.compare(that.minTolerance, minTolerance) != 0) return false; if (normalize != that.normalize) return false; if (Double.compare(that.tolerance, tolerance) != 0) return false; if (pixelTest != that.pixelTest) return false; if (pickMode != that.pickMode) return false; if (spectrumTransform != that.spectrumTransform) return false; if (!ObjectUtils.equalObjects(bandNames, that.bandNames)) return false; if (!ObjectUtils.equalObjects(plusSpectra.toArray(), that.plusSpectra.toArray())) return false; if (!ObjectUtils.equalObjects(minusSpectra.toArray(), that.minusSpectra.toArray())) return false; return true; } @Override public int hashCode() { int result; long temp; result = pickMode.hashCode(); result = 31 * result + spectrumTransform.hashCode(); result = 31 * result + pixelTest.hashCode(); result = 31 * result + plusSpectra.hashCode(); result = 31 * result + minusSpectra.hashCode(); result = 31 * result + bandNames.hashCode(); temp = tolerance != +0.0d ? Double.doubleToLongBits(tolerance) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); result = 31 * result + (normalize ? 1 : 0); temp = minTolerance != +0.0d ? Double.doubleToLongBits(minTolerance) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); temp = maxTolerance != +0.0d ? Double.doubleToLongBits(maxTolerance) : 0L; result = 31 * result + (int) (temp ^ (temp >>> 32)); return result; } public static MagicWandModel fromXml(String xml) { return (MagicWandModel) createXStream().fromXML(xml); } public String toXml() { return createXStream().toXML(this); } private static XStream createXStream() { final XStream xStream = new XStream(); xStream.alias("magicWandSettings", MagicWandModel.class); xStream.registerConverter(new SingleValueConverter() { @Override public boolean canConvert(Class type) { return type.equals(double[].class); } @Override public String toString(Object obj) { return StringUtils.arrayToString(obj, ","); } @Override public Object fromString(String str) { return StringUtils.toDoubleArray(str, ","); } }); return xStream; } public static interface Listener { void modelChanged(MagicWandModel model, boolean recomputeMask); } }
25,708
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SpectralBandComparator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/magicwand/SpectralBandComparator.java
package org.esa.snap.rcp.magicwand; import org.esa.snap.core.datamodel.Band; import java.util.Comparator; /** * Created by Norman on 07.03.14. */ class SpectralBandComparator implements Comparator<Band> { @Override public int compare(Band b1, Band b2) { float deltaWl = b1.getSpectralWavelength() - b2.getSpectralWavelength(); if (Math.abs(deltaWl) > 1e-05) { return deltaWl < 0 ? -1 : 1; } int deltaSi = b1.getSpectralBandIndex() - b2.getSpectralBandIndex(); if (deltaSi != 0) { return deltaSi < 0 ? -1 : 1; } return b1.getName().compareTo(b2.getName()); } }
655
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MagicWandForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/magicwand/MagicWandForm.java
package org.esa.snap.rcp.magicwand; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.undo.support.DefaultUndoContext; import com.thoughtworks.xstream.XStream; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.tango.TangoIcons; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.product.BandChooser; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.ui.tool.ToolButtonFactory; import org.openide.util.ImageUtilities; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JSlider; import javax.swing.JTextField; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import java.awt.GridLayout; import java.awt.Insets; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.prefs.Preferences; import static com.bc.ceres.swing.TableLayout.*; /** * @author Norman Fomferra * @since BEAM 4.10 */ class MagicWandForm { public static final int TOLERANCE_SLIDER_RESOLUTION = 1000; public static final String PREFERENCES_KEY_LAST_DIR = "beam.magicWandTool.lastDir"; private MagicWandInteractor interactor; private JSlider toleranceSlider; boolean adjustingSlider; private DefaultUndoContext undoContext; private AbstractButton redoButton; private AbstractButton undoButton; private BindingContext bindingContext; private File settingsFile; private JLabel infoLabel; private AbstractButton minusButton; private AbstractButton plusButton; private AbstractButton clearButton; private AbstractButton saveButton; MagicWandForm(MagicWandInteractor interactor) { this.interactor = interactor; } public File getSettingsFile() { return settingsFile; } public BindingContext getBindingContext() { return bindingContext; } public JPanel createPanel() { undoContext = new DefaultUndoContext(this); interactor.setUndoContext(undoContext); bindingContext = new BindingContext(PropertyContainer.createObjectBacked(interactor.getModel())); bindingContext.addPropertyChangeListener("tolerance", evt -> { adjustSlider(); interactor.getModel().fireModelChanged(true); }); infoLabel = new JLabel(); infoLabel.setForeground(Color.DARK_GRAY); JLabel toleranceLabel = new JLabel("Tolerance:"); toleranceLabel.setToolTipText("Sets the maximum Euclidian distance tolerated"); JTextField toleranceField = new JTextField(10); bindingContext.bind("tolerance", toleranceField); toleranceField.setText(String.valueOf(interactor.getModel().getTolerance())); toleranceSlider = new JSlider(0, TOLERANCE_SLIDER_RESOLUTION); toleranceSlider.setSnapToTicks(false); toleranceSlider.setPaintTicks(false); toleranceSlider.setPaintLabels(false); toleranceSlider.addChangeListener(e -> { if (!adjustingSlider) { int sliderValue = toleranceSlider.getValue(); bindingContext.getPropertySet().setValue("tolerance", sliderValueToTolerance(sliderValue)); } }); JTextField minToleranceField = new JTextField(4); JTextField maxToleranceField = new JTextField(4); bindingContext.bind("minTolerance", minToleranceField); bindingContext.bind("maxTolerance", maxToleranceField); final PropertyChangeListener minMaxToleranceListener = evt -> adjustSlider(); bindingContext.addPropertyChangeListener("minTolerance", minMaxToleranceListener); bindingContext.addPropertyChangeListener("maxTolerance", minMaxToleranceListener); JPanel toleranceSliderPanel = new JPanel(new BorderLayout(2, 2)); toleranceSliderPanel.add(minToleranceField, BorderLayout.WEST); toleranceSliderPanel.add(toleranceSlider, BorderLayout.CENTER); toleranceSliderPanel.add(maxToleranceField, BorderLayout.EAST); JCheckBox normalizeCheckBox = new JCheckBox("Normalize spectra"); normalizeCheckBox.setToolTipText("Normalizes collected band sets by dividing their\n" + "individual values by the value of the first band"); bindingContext.bind("normalize", normalizeCheckBox); bindingContext.addPropertyChangeListener("normalize", evt -> interactor.getModel().fireModelChanged(true)); JLabel stLabel = new JLabel("Spectrum transformation:"); JRadioButton stButton1 = new JRadioButton("Integral"); JRadioButton stButton2 = new JRadioButton("Identity"); JRadioButton stButton3 = new JRadioButton("Derivative"); ButtonGroup stGroup = new ButtonGroup(); stGroup.add(stButton1); stGroup.add(stButton2); stGroup.add(stButton3); stButton1.setToolTipText("<html>Pixel similarity comparison is performed<br>" + "on the sums of subsequent band values"); stButton2.setToolTipText("<html>Pixel similarity comparison is performed<br>" + "on the original or normalised band values"); stButton3.setToolTipText("<html>Pixel similarity comparison is performed<br>" + "on the differences of subsequent band values"); bindingContext.bind("spectrumTransform", stGroup); bindingContext.addPropertyChangeListener("spectrumTransform", evt -> interactor.getModel().fireModelChanged(true)); JLabel ptLabel = new JLabel("Similarity metric:"); JRadioButton ptButton1 = new JRadioButton("Distance"); JRadioButton ptButton2 = new JRadioButton("Average"); JRadioButton ptButton3 = new JRadioButton("Min-Max"); ptButton1.setToolTipText("<html>Tests if the minimum of Euclidian distances of a pixel to<br>" + "each collected bands set is below the threshold"); ptButton2.setToolTipText("<html>Tests if the Euclidian distances of a pixel to<br>" + "the average of all collected bands sets is below the threshold"); ptButton3.setToolTipText("<html>Tests if a pixel is within the min/max limits<br>" + "of collected bands plus/minus tolerance"); ButtonGroup ptGroup = new ButtonGroup(); ptGroup.add(ptButton1); ptGroup.add(ptButton2); ptGroup.add(ptButton3); bindingContext.bind("pixelTest", ptGroup); bindingContext.addPropertyChangeListener("pixelTest", evt -> interactor.getModel().fireModelChanged(true)); plusButton = createToggleButton(TangoIcons.actions_list_add(TangoIcons.Res.R16)); plusButton.setToolTipText("<html>Switches to pick mode 'plus':<br>" + "collect spectra used for inclusion"); plusButton.addActionListener(e -> { if (interactor.getModel().getPickMode() != MagicWandModel.PickMode.PLUS) { interactor.getModel().setPickMode(MagicWandModel.PickMode.PLUS); } else { interactor.getModel().setPickMode(MagicWandModel.PickMode.SINGLE); } }); minusButton = createToggleButton(TangoIcons.actions_list_remove(TangoIcons.Res.R16)); minusButton.setToolTipText("<html>Switches to pick mode 'minus':<br>" + "collect spectra used for exclusion."); minusButton.addActionListener(e -> { if (interactor.getModel().getPickMode() != MagicWandModel.PickMode.MINUS) { interactor.getModel().setPickMode(MagicWandModel.PickMode.MINUS); } else { interactor.getModel().setPickMode(MagicWandModel.PickMode.SINGLE); } }); bindingContext.addPropertyChangeListener("pickMode", evt -> interactor.getModel().fireModelChanged(false)); final AbstractButton newButton = createButton(TangoIcons.actions_document_new(TangoIcons.R16)); newButton.setToolTipText("New settings"); newButton.addActionListener(e -> newSettings()); final AbstractButton openButton = createButton(TangoIcons.actions_document_open(TangoIcons.R16)); openButton.setToolTipText("Open settings"); openButton.addActionListener(e -> openSettings((Component) e.getSource())); saveButton = createButton(TangoIcons.actions_document_save(TangoIcons.R16)); saveButton.setToolTipText("Save settings"); saveButton.addActionListener(e -> saveSettings((Component) e.getSource(), settingsFile)); final AbstractButton saveAsButton = createButton(TangoIcons.actions_document_save_as(TangoIcons.R16)); saveAsButton.setToolTipText("Save settings as"); saveAsButton.addActionListener(e -> saveSettings((Component) e.getSource(), null)); undoButton = createButton(TangoIcons.actions_edit_undo(TangoIcons.R16)); undoButton.addActionListener(e -> { if (undoContext.canUndo()) { undoContext.undo(); } }); redoButton = createButton(TangoIcons.actions_edit_redo(TangoIcons.Res.R16)); redoButton.addActionListener(e -> { if (undoContext.canRedo()) { undoContext.redo(); } }); undoContext.addUndoableEditListener(e -> updateState()); clearButton = createButton(TangoIcons.actions_edit_clear(TangoIcons.Res.R16)); clearButton.setName("clearButton"); clearButton.setToolTipText("Removes all collected band ses."); /*I18N*/ clearButton.addActionListener(e -> clearSpectra()); AbstractButton filterButton = createButton(ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/Filter24.gif", false)); filterButton.setName("filterButton"); filterButton.setToolTipText("Select bands to included."); /*I18N*/ filterButton.addActionListener(e -> showBandChooser()); AbstractButton helpButton = createButton(TangoIcons.apps_help_browser(TangoIcons.Res.R16)); helpButton.setName("helpButton"); helpButton.setToolTipText("Help."); /*I18N*/ JPanel toolPanelN = new JPanel(new GridLayout(-1, 2)); toolPanelN.add(newButton); toolPanelN.add(openButton); toolPanelN.add(saveButton); toolPanelN.add(saveAsButton); toolPanelN.add(clearButton); toolPanelN.add(filterButton); toolPanelN.add(undoButton); toolPanelN.add(redoButton); toolPanelN.add(plusButton); toolPanelN.add(minusButton); JPanel toolPanelS = new JPanel(new GridLayout(-1, 2)); toolPanelS.add(new JLabel()); toolPanelS.add(helpButton); TableLayout tableLayout = new TableLayout(2); tableLayout.setTableAnchor(TableLayout.Anchor.WEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTableWeightX(1.0); tableLayout.setTablePadding(2, 2); tableLayout.setCellColspan(1, 0, tableLayout.getColumnCount()); Insets insets = new Insets(2, 10, 2, 2); //tableLayout.setRowPadding(3, insets); //tableLayout.setRowPadding(4, insets); //tableLayout.setRowPadding(5, insets); tableLayout.setCellPadding(3, 0, insets); tableLayout.setCellPadding(4, 0, insets); tableLayout.setCellPadding(5, 0, insets); tableLayout.setCellPadding(6, 0, insets); tableLayout.setCellPadding(3, 1, insets); tableLayout.setCellPadding(4, 1, insets); tableLayout.setCellPadding(5, 1, insets); JPanel subPanel = new JPanel(tableLayout); subPanel.add(toleranceLabel, cell(0, 0)); subPanel.add(toleranceField, cell(0, 1)); subPanel.add(toleranceSliderPanel, cell(1, 0)); subPanel.add(stLabel, cell(2, 0)); subPanel.add(stButton1, cell(3, 0)); subPanel.add(stButton2, cell(4, 0)); subPanel.add(stButton3, cell(5, 0)); subPanel.add(ptLabel, cell(2, 1)); subPanel.add(ptButton1, cell(3, 1)); subPanel.add(ptButton2, cell(4, 1)); subPanel.add(ptButton3, cell(5, 1)); subPanel.add(normalizeCheckBox, cell(6, 0)); subPanel.add(infoLabel, cell(6, 1)); JPanel toolPanel = new JPanel(new BorderLayout(4, 4)); toolPanel.add(toolPanelN, BorderLayout.NORTH); toolPanel.add(new JLabel(), BorderLayout.CENTER); toolPanel.add(toolPanelS, BorderLayout.SOUTH); JPanel panel = new JPanel(new BorderLayout(4, 4)); panel.setBorder(new EmptyBorder(4, 4, 4, 4)); panel.add(subPanel, BorderLayout.CENTER); panel.add(toolPanel, BorderLayout.EAST); adjustSlider(); updateState(); return panel; } private void newSettings() { if (proceedWithUnsavedChanges()) { settingsFile = null; interactor.getModel().clearSpectra(); } } private void clearSpectra() { interactor.clearSpectra(); } private void openSettings(Component parent) { if (proceedWithUnsavedChanges()) { File settingsFile = getFile(parent, this.settingsFile, true); if (settingsFile == null) { return; } try { MagicWandModel model = (MagicWandModel) createXStream().fromXML(FileUtils.readText(settingsFile)); this.settingsFile = settingsFile; interactor.assignModel(model); undoContext.getUndoManager().discardAllEdits(); interactor.setModelModified(false); updateState(); } catch (IOException e) { String msg = MessageFormat.format("Failed to open settings:\n{0}", e.getMessage()); AbstractDialog.showErrorDialog(parent, msg, "I/O Error"); } } } private void saveSettings(Component parent, File settingsFile) { if (settingsFile == null) { settingsFile = getFile(parent, this.settingsFile, false); if (settingsFile == null) { return; } } try { try (FileWriter writer = new FileWriter(settingsFile)) { writer.write(createXStream().toXML(interactor.getModel())); } this.settingsFile = settingsFile; undoContext.getUndoManager().discardAllEdits(); interactor.setModelModified(false); interactor.updateForm(); } catch (IOException e) { String msg = MessageFormat.format("Failed to safe settings:\n{0}", e.getMessage()); AbstractDialog.showErrorDialog(parent, msg, "I/O Error"); } } private XStream createXStream() { XStream xStream = new XStream(); xStream.setClassLoader(MagicWandModel.class.getClassLoader()); xStream.alias("magicWandSettings", MagicWandModel.class); return xStream; } private static File getFile(Component parent, File file, boolean open) { JFileChooser fileChooser = new JFileChooser(Preferences.userRoot().get(PREFERENCES_KEY_LAST_DIR, System.getProperty("user.home"))); if (file != null) { fileChooser.setSelectedFile(file); } else { fileChooser.setSelectedFile(new File(fileChooser.getCurrentDirectory(), "magic-wand-settings.xml")); } while (true) { int resp = open ? fileChooser.showOpenDialog(parent) : fileChooser.showSaveDialog(parent); File settingsFile = fileChooser.getSelectedFile(); Preferences.userRoot().put(PREFERENCES_KEY_LAST_DIR, fileChooser.getCurrentDirectory().getPath()); if (resp != JFileChooser.APPROVE_OPTION) { return null; } if (open || !settingsFile.exists()) { return settingsFile; } String msg = MessageFormat.format("Settings file ''{0}'' already exists." + "\nOverwrite?", settingsFile.getName()); int resp2 = JOptionPane.showConfirmDialog(parent, msg, "File exists", JOptionPane.YES_NO_CANCEL_OPTION); if (resp2 == JOptionPane.YES_OPTION) { return settingsFile; } if (resp2 == JOptionPane.CANCEL_OPTION) { return null; } } } void updateState() { bindingContext.setComponentsEnabled("spectrumTransform", interactor.getModel().getBandCount() != 1); bindingContext.setComponentsEnabled("normalize", interactor.getModel().getBandCount() != 1); MagicWandModel model = interactor.getModel(); infoLabel.setText(String.format("%d(+), %d(-), %d bands", model.getPlusSpectrumCount(), model.getMinusSpectrumCount(), model.getBandCount())); plusButton.setSelected(model.getPickMode() == MagicWandModel.PickMode.PLUS); minusButton.setSelected(model.getPickMode() == MagicWandModel.PickMode.MINUS); saveButton.setEnabled(settingsFile != null && interactor.isModelModified()); clearButton.setEnabled(model.getSpectrumCount() > 0); undoButton.setEnabled(undoContext.canUndo()); redoButton.setEnabled(undoContext.canRedo()); } private void adjustSlider() { adjustingSlider = true; double tolerance = interactor.getModel().getTolerance(); toleranceSlider.setValue(toleranceToSliderValue(tolerance)); adjustingSlider = false; } private int toleranceToSliderValue(double tolerance) { MagicWandModel model = interactor.getModel(); double minTolerance = model.getMinTolerance(); double maxTolerance = model.getMaxTolerance(); return (int) Math.round(Math.abs(TOLERANCE_SLIDER_RESOLUTION * ((tolerance - minTolerance) / (maxTolerance - minTolerance)))); } private double sliderValueToTolerance(int sliderValue) { MagicWandModel model = interactor.getModel(); double minTolerance = model.getMinTolerance(); double maxTolerance = model.getMaxTolerance(); return minTolerance + sliderValue * (maxTolerance - minTolerance) / TOLERANCE_SLIDER_RESOLUTION; } private static AbstractButton createButton(ImageIcon imageIcon) { return ToolButtonFactory.createButton(imageIcon, false); } private static AbstractButton createToggleButton(ImageIcon imageIcon) { return ToolButtonFactory.createButton(imageIcon, true); } void showBandChooser() { final ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); if (view == null) { Dialogs.showInformation("Please select an image view first.", null); return; } Product product = view.getProduct(); Band[] bands = product.getBands(); if (bands.length == 0) { Dialogs.showInformation("No bands in product.", null); return; } Set<String> oldBandNames = new HashSet<>(interactor.getModel().getBandNames()); Set<Band> oldBandSet = new HashSet<>(); for (Band band : bands) { if (oldBandNames.contains(band.getName())) { oldBandSet.add(band); } } BandChooser bandChooser = new BandChooser(interactor.getOptionsWindow(), "Available Bands and Tie Point Grids", "", bands, oldBandSet.toArray(new Band[oldBandSet.size()]), product.getAutoGrouping(), true); if (bandChooser.show() == ModalDialog.ID_OK) { Band[] newBands = bandChooser.getSelectedBands(); Arrays.sort(newBands, new SpectralBandComparator()); List<String> newBandNames = new ArrayList<>(); for (Band newBand : newBands) { newBandNames.add(newBand.getName()); } if (!oldBandNames.containsAll(newBandNames) || !newBandNames.containsAll(oldBandNames)) { interactor.getModel().setBandNames(newBandNames); } } } private boolean proceedWithUnsavedChanges() { if (settingsFile != null && interactor.isModelModified()) { String msg = MessageFormat.format("You have unsaved changes." + "\nProceed anyway?", settingsFile.getName()); int resp = JOptionPane.showConfirmDialog(interactor.getOptionsWindow(), msg, "New Settings", JOptionPane.YES_NO_OPTION); return resp == JOptionPane.YES_OPTION; } return true; } }
21,979
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MagicWandInteractor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/magicwand/MagicWandInteractor.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.magicwand; import com.bc.ceres.glayer.Layer; import com.bc.ceres.glayer.LayerType; import com.bc.ceres.glayer.support.AbstractLayerListener; import com.bc.ceres.swing.figure.ViewportInteractor; import com.bc.ceres.swing.undo.UndoContext; import org.esa.snap.core.datamodel.Band; 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.datamodel.ProductNodeGroup; import org.esa.snap.core.layer.MaskLayerType; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.rcp.util.MultiSizeIssue; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.product.ProductSceneView; import javax.swing.JDialog; import javax.swing.undo.AbstractUndoableEdit; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; import java.awt.Point; import java.awt.Window; import java.awt.event.MouseEvent; import java.awt.geom.AffineTransform; import java.awt.geom.NoninvertibleTransformException; import java.awt.geom.Point2D; import java.io.IOException; import java.util.List; /** * An interactor that lets users create masks using a "magic wand". * The mask comprises all pixels in the image that are "spectrally" close to the pixel that * has been selected using the magic wand. * * @author Norman Fomferra * @since BEAM 4.10 */ public class MagicWandInteractor extends ViewportInteractor implements MagicWandModel.Listener { private static final String DIALOG_TITLE = "Magic Wand Tool"; private JDialog optionsWindow; private final MyLayerListener layerListener; private MagicWandModel model; private UndoContext undoContext; private MagicWandForm form; private boolean modelModified; public MagicWandInteractor() { layerListener = new MyLayerListener(); model = new MagicWandModel(); model.addListener(this); } public boolean isModelModified() { return modelModified; } public void setModelModified(boolean modelModified) { this.modelModified = modelModified; } @Override public void modelChanged(MagicWandModel model, boolean recomputeMask) { setModelModified(true); if (recomputeMask) { updateMask(); } if (form != null) { updateForm(); } } void updateForm() { if (form.getSettingsFile() != null) { optionsWindow.setTitle(DIALOG_TITLE + " - " + FileUtils.getFilenameWithoutExtension(form.getSettingsFile())); } else { optionsWindow.setTitle(DIALOG_TITLE); } form.getBindingContext().adjustComponents(); form.updateState(); } public Window getOptionsWindow() { return optionsWindow; } static double[] getSpectrum(List<Band> bands, int pixelX, int pixelY) throws IOException { final double[] pixel = new double[1]; final double[] spectrum = new double[bands.size()]; for (int i = 0; i < bands.size(); i++) { final Band band = bands.get(i); band.readPixels(pixelX, pixelY, 1, 1, pixel, com.bc.ceres.core.ProgressMonitor.NULL); final double value; if (band.isPixelValid(pixelX, pixelY)) { value = pixel[0]; } else { value = Double.NaN; } spectrum[i] = value; } return spectrum; } @Override public boolean activate() { if (optionsWindow == null) { optionsWindow = createOptionsWindow(); } optionsWindow.setVisible(true); ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); if (view != null) { view.getRootLayer().addListener(layerListener); } return super.activate(); } @Override public void deactivate() { super.deactivate(); if (optionsWindow != null) { optionsWindow.setVisible(false); } ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); if (view != null) { view.getRootLayer().removeListener(layerListener); } } @Override public void mouseClicked(MouseEvent event) { final ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); if (view == null) { return; } final Product product = view.getProduct(); // if (MultiSizeIssue.isMultiSize(product)) { // System.out.println("####### LA ###########"); // // MultiSizeIssue.maybeResample(product); // //as the following code requires an exact pixel location, nothing is done after resampling // return; // } if (!ensureBandNamesSet(view, product)) { return; } List<Band> bands = model.getBands(product); if (bands == null) { if (!handleInvalidBandFilter(view)) { return; } bands = model.getBands(product); if (bands == null) { // Should not come here. return; } } // Check if all the bands have the same size (if only one band the check is skipped) int band0Width = bands.get(0).getRasterWidth(); int band0Height = bands.get(0).getRasterHeight(); for (int i = 1; i < bands.size(); i++) { // don't need to check the band "0" final Band band = bands.get(i); // Check if the band has the same size as the band "0" if (!ProductUtils.areRastersEqualInSize(band0Width, band0Height, band)){ // the current band has a different width or height as the band "0": cannot continue MultiSizeIssue.chooseBandsWithSameSize(); return; }; } // Compute the pixel position according to the (common) geocoding of the bands GeoCoding band0Geocoding = bands.get(0).getGeoCoding(); Point pixelPos = getPixelPos(band0Geocoding, band0Width, band0Height, event); // TODO GP before: getPixelPos(product, event); ==> deprecate the method ? if (pixelPos == null) { return; } final double[] spectrum; try { spectrum = getSpectrum(bands, pixelPos.x, pixelPos.y); } catch (IOException e1) { return; } MagicWandModel oldModel = getModel().clone(); getModel().addSpectrum(spectrum); MagicWandModel newModel = getModel().clone(); ensureMaskVisible(view); undoContext.postEdit(new MyUndoableEdit(oldModel, newModel)); } void clearSpectra() { MagicWandModel oldModel = getModel().clone(); getModel().clearSpectra(); MagicWandModel newModel = getModel().clone(); undoContext.postEdit(new MyUndoableEdit(oldModel, newModel)); } private void ensureMaskVisible(ProductSceneView view) { Product product = view.getProduct(); ProductNodeGroup<Mask> overlayMaskGroup = view.getRaster().getOverlayMaskGroup(); Mask mask = overlayMaskGroup.getByDisplayName(MagicWandModel.MAGIC_WAND_MASK_NAME); if (mask == null) { mask = product.getMaskGroup().get(MagicWandModel.MAGIC_WAND_MASK_NAME); if (mask != null) { overlayMaskGroup.add(mask); } } } private boolean handleInvalidBandFilter(ProductSceneView view) { Product product = view.getProduct(); Dialogs.Answer answer = Dialogs.requestDecision(DIALOG_TITLE, "The currently selected band filter does not match\n" + "the bands of the selected data product.\n\n" + "Reset filter and use the ones of the selected product?", false, "reset_magic_wand_filter"); if (answer == Dialogs.Answer.YES) { model.setBandNames(); return ensureBandNamesSet(view, product); } else { return false; } } Point getPixelPos(Product product, MouseEvent event) { final Point2D mp = toModelPoint(event); final Point2D ip; if (product.getSceneGeoCoding() != null) { AffineTransform transform = Product.findImageToModelTransform(product.getSceneGeoCoding()); try { ip = transform.inverseTransform(mp, null); } catch (NoninvertibleTransformException e) { Dialogs.showError(DIALOG_TITLE, "A geographic transformation problem occurred:\n" + e.getMessage()); return null; } } else { ip = mp; } final int pixelX = (int) ip.getX(); final int pixelY = (int) ip.getY(); if (pixelX < 0 || pixelY < 0 || pixelX >= product.getSceneRasterWidth() || pixelY >= product.getSceneRasterHeight()) { return null; } return new Point(pixelX, pixelY); } Point getPixelPos(GeoCoding geocoding, int width, int height, MouseEvent event) { final Point2D mp = toModelPoint(event); final Point2D ip; if (geocoding != null) { AffineTransform transform = Product.findImageToModelTransform(geocoding); try { ip = transform.inverseTransform(mp, null); } catch (NoninvertibleTransformException e) { Dialogs.showError(DIALOG_TITLE, "A geographic transformation problem occurred:\n" + e.getMessage()); return null; } } else { ip = mp; } final int pixelX = (int) ip.getX(); final int pixelY = (int) ip.getY(); if (pixelX < 0 || pixelY < 0 || pixelX >= width || pixelY >= height) { return null; } return new Point(pixelX, pixelY); } private boolean ensureBandNamesSet(ProductSceneView view, Product product) { if (model.getBandCount() == 0) { model.setSpectralBandNames(product); } if (model.getBandCount() == 0) { model.setBandNames(view.getRaster().getName()); } if (model.getBandCount() == 0) { // It's actually hard to get here, because we have a selected image view... Dialogs.showError(DIALOG_TITLE, "No bands selected."); return false; } return true; } void updateMask() { final ProductSceneView view = SnapApp.getDefault().getSelectedProductSceneView(); if (view != null) { final Product product = view.getProduct(); updateMagicWandMask(product); } } private void updateMagicWandMask(Product product) { MagicWandModel.setMagicWandMask(product, getModel().createMaskExpression()); } private JDialog createOptionsWindow() { form = new MagicWandForm(this); JDialog optionsWindow = new JDialog(SnapApp.getDefault().getMainFrame(), DIALOG_TITLE, false); UIUtils.centerComponent(optionsWindow, SnapApp.getDefault().getMainFrame()); optionsWindow.getContentPane().add(form.createPanel()); optionsWindow.pack(); return optionsWindow; } public MagicWandModel getModel() { return model; } public void setUndoContext(UndoContext undoContext) { this.undoContext = undoContext; } void assignModel(MagicWandModel other) { getModel().assign(other); } /** * A layer listener that sets the layer for "magic_wand" mask * visible, once it is added to the view's layer tree. */ private static class MyLayerListener extends AbstractLayerListener { @Override public void handleLayersAdded(Layer parentLayer, Layer[] childLayers) { for (Layer childLayer : childLayers) { LayerType layerType = childLayer.getLayerType(); if (layerType instanceof MaskLayerType) { if (childLayer.getName().equals(MagicWandModel.MAGIC_WAND_MASK_NAME)) { childLayer.setVisible(true); } } } } } private class MyUndoableEdit extends AbstractUndoableEdit { private final MagicWandModel oldModel; private final MagicWandModel newModel; public MyUndoableEdit(MagicWandModel oldModel, MagicWandModel newModel) { this.oldModel = oldModel; this.newModel = newModel; } @Override public void undo() throws CannotUndoException { super.undo(); assignModel(oldModel); } @Override public void redo() throws CannotRedoException { super.redo(); assignModel(newModel); } @Override public String getPresentationName() { return "Modify magic wand mask"; } } }
14,150
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SpectrumGraph.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/spectrum/SpectrumGraph.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.spectrum; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.glevel.MultiLevelModel; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.util.Debug; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.core.util.math.IndexValidator; import org.esa.snap.core.util.math.Range; import org.esa.snap.ui.diagram.AbstractDiagramGraph; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.util.Arrays; import java.util.Comparator; class SpectrumGraph extends AbstractDiagramGraph { private Placemark placemark; private Band[] bands; private double[] energies; private double[] wavelengths; private final Range energyRange; private final Range wavelengthRange; SpectrumGraph(Placemark placemark, Band[] bands) { Debug.assertNotNull(bands); this.placemark = placemark; this.bands = bands; energyRange = new Range(); wavelengthRange = new Range(); setBands(bands); } SpectrumGraph() { // this one is just for testing tb 2024-02-22 energyRange = new Range(); wavelengthRange = new Range(); } @Override public String getXName() { return "Wavelength"; } @Override public String getYName() { return placemark != null ? placemark.getLabel() : "Cursor"; } @Override public int getNumValues() { return bands.length; } @Override public double getXValueAt(int index) { return wavelengths[index]; } @Override public double getYValueAt(int index) { if (energies[index] == bands[index].getGeophysicalNoDataValue()) { return Double.NaN; } return energies[index]; } @Override public double getXMin() { return wavelengthRange.getMin(); } @Override public double getXMax() { return wavelengthRange.getMax(); } @Override public double getYMin() { return energyRange.getMin(); } @Override public double getYMax() { return energyRange.getMax(); } void setBands(Band[] bands) { Debug.assertNotNull(bands); this.bands = bands.clone(); Arrays.sort(this.bands, new Comparator<Band>() { @Override public int compare(Band band1, Band band2) { final float v = band1.getSpectralWavelength() - band2.getSpectralWavelength(); return v < 0.0F ? -1 : v > 0.0F ? 1 : 0; } }); if (wavelengths == null || wavelengths.length != this.bands.length) { wavelengths = new double[this.bands.length]; } if (energies == null || energies.length != this.bands.length) { energies = new double[this.bands.length]; } for (int i = 0; i < wavelengths.length; i++) { wavelengths[i] = this.bands[i].getSpectralWavelength(); energies[i] = 0.0f; } Range.computeRangeDouble(wavelengths, IndexValidator.TRUE, wavelengthRange, ProgressMonitor.NULL); Range.computeRangeDouble(energies, IndexValidator.TRUE, energyRange, ProgressMonitor.NULL); } void setEnergies(double[] energies) { this.energies = energies; Range.computeRangeDouble(energies, IndexValidator.TRUE, energyRange, ProgressMonitor.NULL); } @Override public void dispose() { placemark = null; bands = null; energies = null; wavelengths = null; super.dispose(); } }
4,349
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SpectraExportAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/spectrum/SpectraExportAction.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.spectrum; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.util.PreferencesPropertyMap; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.io.SnapFileFilter; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.diagram.DiagramGraph; import org.esa.snap.ui.diagram.DiagramGraphIO; import org.esa.snap.ui.product.spectrum.DisplayableSpectrum; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.prefs.Preferences; class SpectraExportAction extends AbstractAction { private final SpectrumTopComponent spectrumTopComponent; SpectraExportAction(SpectrumTopComponent spectrumTopComponent) { super("exportSpectra"); this.spectrumTopComponent = spectrumTopComponent; } @Override public void actionPerformed(ActionEvent e) { exportSpectra(); } private void exportSpectra() { final List<DisplayableSpectrum> selectedSpectra = spectrumTopComponent.getSelectedSpectra(); final Placemark[] pins = spectrumTopComponent.getDisplayedPins(); final List<SpectrumGraph> spectrumGraphList = new ArrayList<SpectrumGraph>(); final Map<Placemark, Map<Band, Double>> energiesMap = spectrumTopComponent.getPinToEnergies(); for (Placemark pin : pins) { Map<Band, Double> bandEnergyMap = energiesMap.get(pin); for (DisplayableSpectrum spectrumInDisplay : selectedSpectra) { final Band[] selectedBands = spectrumInDisplay.getSelectedBands(); final double[] energies = getEnergies(selectedBands, bandEnergyMap); final SpectrumGraph spectrumGraph = new SpectrumGraph(pin, selectedBands); spectrumGraph.setEnergies(energies); spectrumGraphList.add(spectrumGraph); } } DiagramGraph[] pinGraphs = spectrumGraphList.toArray(new DiagramGraph[0]); final Preferences preferences = SnapApp.getDefault().getPreferences(); final PropertyMap preferencesPropertyMap = new PreferencesPropertyMap(preferences); DiagramGraphIO.writeGraphs(SwingUtilities.getWindowAncestor(spectrumTopComponent), "Export Pin Spectra", new SnapFileFilter[]{DiagramGraphIO.SPECTRA_CSV_FILE_FILTER}, preferencesPropertyMap, pinGraphs); } // package access for testing only tb 2024-02-22 static double[] getEnergies(Band[] selectedBands, Map<Band, Double> bandDoubleMap) { final double[] energies = new double[selectedBands.length]; for (int i = 0; i < selectedBands.length; i++) { energies[i] = bandDoubleMap.get(selectedBands[i]); } return energies; } }
3,604
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CursorSpectrumPixelPositionListener.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/spectrum/CursorSpectrumPixelPositionListener.java
package org.esa.snap.rcp.spectrum; import com.bc.ceres.glayer.support.ImageLayer; import org.esa.snap.ui.PixelPositionListener; import javax.swing.SwingWorker; import java.awt.event.MouseEvent; public class CursorSpectrumPixelPositionListener implements PixelPositionListener { private final SpectrumTopComponent topComponent; private final WorkerChain workerChain; private final WorkerChainSupport support; public CursorSpectrumPixelPositionListener(SpectrumTopComponent topComponent) { this.topComponent = topComponent; workerChain = new WorkerChain(); support = new WorkerChainSupport() { @Override public void removeWorkerAndStartNext(SwingWorker worker) { workerChain.removeCurrentWorkerAndExecuteNext(worker); } }; } @Override public void pixelPosChanged(ImageLayer imageLayer, int pixelX, int pixelY, int currentLevel, boolean pixelPosValid, MouseEvent e) { CursorSpectraUpdater worker = new CursorSpectraUpdater(pixelPosValid, pixelX, pixelY, currentLevel, e.isShiftDown(), support); workerChain.setOrExecuteNextWorker(worker, false); } @Override public void pixelPosNotAvailable() { CursorSpectraRemover worker = new CursorSpectraRemover(support); workerChain.setOrExecuteNextWorker(worker, false); } private boolean shouldUpdateCursorPosition() { return topComponent.isVisible() && topComponent.isShowingCursorSpectrum(); } private class CursorSpectraRemover extends SwingWorker<Void, Void> { private final WorkerChainSupport support; CursorSpectraRemover(WorkerChainSupport support) { this.support = support; } @Override protected Void doInBackground() throws Exception { if (shouldUpdateCursorPosition()) { topComponent.removeCursorSpectraFromDataset(); } return null; } @Override protected void done() { topComponent.updateChart(); support.removeWorkerAndStartNext(this); } } private class CursorSpectraUpdater extends SwingWorker<Void, Void> { private final boolean pixelPosValid; private final int pixelX; private final int pixelY; private final int currentLevel; private final boolean adjustAxes; private final WorkerChainSupport support; CursorSpectraUpdater(boolean pixelPosValid, int pixelX, int pixelY, int currentLevel, boolean adjustAxes, WorkerChainSupport support) { this.pixelPosValid = pixelPosValid; this.pixelX = pixelX; this.pixelY = pixelY; this.currentLevel = currentLevel; this.adjustAxes = adjustAxes; this.support = support; } @Override protected Void doInBackground() throws Exception { if (shouldUpdateCursorPosition()) { Waiter waiter = new Waiter(); waiter.execute(); topComponent.updateData(pixelX, pixelY, currentLevel, pixelPosValid); waiter.cancel(true); } return null; } @Override protected void done() { try { topComponent.updateChart(adjustAxes); } finally { support.removeWorkerAndStartNext(this); } } } private class Waiter extends SwingWorker<Void, Void> { @Override protected Void doInBackground() throws Exception { Thread.sleep(1000); return null; } @Override protected void done() { topComponent.setPrepareForUpdateMessage(); } } //todo copied (and changed very slightly) from time-series-tool: Move to BEAM or Ceres static interface WorkerChainSupport { void removeWorkerAndStartNext(SwingWorker worker); } }
4,191
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WorkerChain.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/spectrum/WorkerChain.java
package org.esa.snap.rcp.spectrum; //todo copied from time-series-tool: move to BEAM or Ceres import javax.swing.SwingWorker; import java.util.ArrayList; import java.util.Collections; import java.util.List; class WorkerChain { private final List<SwingWorker> synchronizedWorkerChain; private SwingWorker unchainedWorker; private boolean workerIsRunning = false; WorkerChain() { synchronizedWorkerChain = Collections.synchronizedList(new ArrayList<SwingWorker>()); } synchronized void setOrExecuteNextWorker(SwingWorker w, boolean chained) { if (w == null) { return; } if (workerIsRunning) { if (chained) { synchronizedWorkerChain.add(w); } else { unchainedWorker = w; } } else { if (chained) { synchronizedWorkerChain.add(w); executeFirstWorkerInChain(); } else { unchainedWorker = w; w.execute(); } workerIsRunning = true; } } synchronized void removeCurrentWorkerAndExecuteNext(SwingWorker currentWorker) { synchronizedWorkerChain.remove(currentWorker); if (unchainedWorker == currentWorker) { unchainedWorker = null; } if (synchronizedWorkerChain.size() > 0) { executeFirstWorkerInChain(); return; } if (unchainedWorker != null) { unchainedWorker.execute(); return; } workerIsRunning = false; } private void executeFirstWorkerInChain() { synchronizedWorkerChain.get(0).execute(); } }
1,711
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SpectrumTopComponent.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/spectrum/SpectrumTopComponent.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.spectrum; import com.bc.ceres.glayer.support.ImageLayer; import com.bc.ceres.glevel.MultiLevelModel; import org.esa.snap.core.datamodel.*; import org.esa.snap.core.image.ImageManager; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.core.util.StringUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.help.HelpAction; import org.esa.snap.rcp.placemark.PlacemarkUtils; import org.esa.snap.rcp.statistics.XYPlotMarker; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.rcp.windows.ToolTopComponent; import org.esa.snap.ui.*; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.ui.product.spectrum.*; import org.esa.snap.ui.tool.ToolButtonFactory; import org.jfree.chart.*; import org.jfree.chart.annotations.XYTitleAnnotation; import org.jfree.chart.axis.ValueAxis; import org.jfree.chart.block.BlockBorder; import org.jfree.chart.block.LineBorder; import org.jfree.chart.plot.PlotOrientation; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer; import org.jfree.chart.title.LegendTitle; 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.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.locationtech.jts.geom.Point; 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.media.jai.PlanarImage; import javax.swing.*; import javax.swing.border.BevelBorder; import java.awt.*; import java.awt.geom.AffineTransform; import java.awt.geom.Line2D; import java.awt.geom.Point2D; import java.awt.image.Raster; import java.awt.image.RenderedImage; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.List; import java.util.*; @TopComponent.Description(preferredID = "SpectrumTopComponent", iconBase = "org/esa/snap/rcp/icons/Spectrum.gif") @TopComponent.Registration(mode = "Spectrum", openAtStartup = false, position = 80) @ActionID(category = "Window", id = "org.esa.snap.rcp.statistics.SpectrumTopComponent") @ActionReferences({ @ActionReference(path = "Menu/Optical", position = 0), @ActionReference(path = "Menu/View/Tool Windows/Optical"), @ActionReference(path = "Toolbars/Tool Windows") }) @TopComponent.OpenActionRegistration(displayName = "#CTL_SpectrumTopComponent_Name", preferredID = "SpectrumTopComponent") @NbBundle.Messages({"CTL_SpectrumTopComponent_Name=Spectrum View", "CTL_SpectrumTopComponent_HelpId=showSpectrumWnd"}) /* * A window which displays spectra at selected pixel positions. */ public class SpectrumTopComponent extends ToolTopComponent { public static final String ID = SpectrumTopComponent.class.getName(); private static final String SUPPRESS_MESSAGE_KEY = "plugin.spectrum.tip"; private final Map<RasterDataNode, DisplayableSpectrum[]> rasterToSpectraMap; private final Map<RasterDataNode, List<SpectrumBand>> rasterToSpectralBandsMap; private final ProductNodeListenerAdapter productNodeHandler; private final PinSelectionChangeListener pinSelectionChangeListener; private final PixelPositionListener pixelPositionListener; private AbstractButton filterButton; private AbstractButton showSpectrumForCursorButton; private AbstractButton showSpectraForSelectedPinsButton; private AbstractButton showSpectraForAllPinsButton; private AbstractButton showGridButton; private boolean tipShown; private ProductSceneView currentView; private Product currentProduct; private ChartPanel chartPanel; private ChartHandler chartHandler; private boolean domainAxisAdjustmentIsFrozen; private boolean rangeAxisAdjustmentIsFrozen; private boolean isCodeInducedAxisChange; private boolean isUserInducedAutomaticAdjustmentChosen; public SpectrumTopComponent() { productNodeHandler = new ProductNodeHandler(); pinSelectionChangeListener = new PinSelectionChangeListener(); rasterToSpectraMap = new HashMap<>(); rasterToSpectralBandsMap = new HashMap<>(); pixelPositionListener = new CursorSpectrumPixelPositionListener(this); initUI(); } //package local for testing static DisplayableSpectrum[] createSpectraFromUngroupedBands(SpectrumBand[] ungroupedBands, int symbolIndex, int strokeIndex) { List<String> knownUnits = new ArrayList<>(); List<DisplayableSpectrum> displayableSpectrumList = new ArrayList<>(); DisplayableSpectrum defaultSpectrum = new DisplayableSpectrum("tbd", -1); for (SpectrumBand ungroupedBand : ungroupedBands) { final String unit = ungroupedBand.getOriginalBand().getUnit(); if (StringUtils.isNullOrEmpty(unit)) { defaultSpectrum.addBand(ungroupedBand); } else if (knownUnits.contains(unit)) { displayableSpectrumList.get(knownUnits.indexOf(unit)).addBand(ungroupedBand); } else { knownUnits.add(unit); final DisplayableSpectrum spectrum = new DisplayableSpectrum("Bands measured in " + unit, symbolIndex); symbolIndex++; spectrum.setLineStyle(SpectrumStrokeProvider.getStroke(strokeIndex)); strokeIndex++; spectrum.addBand(ungroupedBand); displayableSpectrumList.add(spectrum); } } if (strokeIndex == 0) { defaultSpectrum.setName(DisplayableSpectrum.DEFAULT_SPECTRUM_NAME); } else { defaultSpectrum.setName(DisplayableSpectrum.REMAINING_BANDS_NAME); } defaultSpectrum.setSymbolIndex(symbolIndex); defaultSpectrum.setLineStyle(SpectrumStrokeProvider.getStroke(strokeIndex)); displayableSpectrumList.add(defaultSpectrum); return displayableSpectrumList.toArray(new DisplayableSpectrum[0]); } @Override public HelpCtx getHelpCtx() { return new HelpCtx(Bundle.CTL_SpectrumTopComponent_HelpId()); } private void setCurrentView(ProductSceneView view) { ProductSceneView oldView = currentView; currentView = view; if (oldView != currentView) { if (oldView != null) { oldView.removePropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN, pinSelectionChangeListener); } if (currentView != null) { currentView.addPropertyChangeListener(ProductSceneView.PROPERTY_NAME_SELECTED_PIN, pinSelectionChangeListener); setCurrentProduct(currentView.getProduct()); if (!rasterToSpectraMap.containsKey(currentView.getRaster())) { setUpSpectra(); } recreateChart(); } updateUIState(); } } private Product getCurrentProduct() { return currentProduct; } private void setCurrentProduct(Product product) { Product oldProduct = currentProduct; currentProduct = product; if (currentProduct != oldProduct) { if (oldProduct != null) { oldProduct.removeProductNodeListener(productNodeHandler); } if (currentProduct != null) { currentProduct.addProductNodeListener(productNodeHandler); } if (currentProduct == null) { chartHandler.setEmptyPlot(); } updateUIState(); } } private void updateUIState() { boolean hasView = currentView != null; boolean hasProduct = currentProduct != null; boolean hasSelectedPins = hasView && currentView.getSelectedPins().length > 0; boolean hasPins = hasProduct && currentProduct.getPinGroup().getNodeCount() > 0; filterButton.setEnabled(hasProduct); showSpectrumForCursorButton.setEnabled(hasView); showSpectraForSelectedPinsButton.setEnabled(hasSelectedPins); showSpectraForAllPinsButton.setEnabled(hasPins); showGridButton.setEnabled(hasView); chartPanel.setEnabled(hasProduct); // todo - hasSpectraGraphs showGridButton.setSelected(hasView); chartHandler.setGridVisible(showGridButton.isSelected()); } void setPrepareForUpdateMessage() { chartHandler.setCollectingSpectralInformationMessage(); } void updateData(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) { chartHandler.setPosition(pixelX, pixelY, level, pixelPosInRasterBounds); chartHandler.updateData(); } void updateChart(boolean adjustAxes) { chartHandler.setAutomaticRangeAdjustments(adjustAxes); updateChart(); } void updateChart() { maybeShowTip(); chartHandler.updateChart(); chartPanel.repaint(); } private void maybeShowTip() { if (!tipShown) { final String message = "<html>Tip: If you press the SHIFT key while moving the mouse cursor over<br/>" + "an image, " + SnapApp.getDefault().getInstanceName() + " adjusts the diagram axes " + "to the local values at the<br/>" + "current pixel position, if you release the SHIFT key again, then the<br/>" + "min/max are accumulated again.</html>"; Dialogs.showInformation("Spectrum Tip", message, SUPPRESS_MESSAGE_KEY); tipShown = true; } } private SpectrumBand[] getAvailableSpectralBands(RasterDataNode currentRaster) { if (!rasterToSpectralBandsMap.containsKey(currentRaster)) { rasterToSpectralBandsMap.put(currentRaster, new ArrayList<>()); } List<SpectrumBand> spectrumBands = rasterToSpectralBandsMap.get(currentRaster); Band[] bands = currentProduct.getBands(); for (Band band : bands) { if (isSpectralBand(band) && !band.isFlagBand()) { boolean isAlreadyIncluded = false; for (SpectrumBand spectrumBand : spectrumBands) { if (spectrumBand.getOriginalBand() == band) { isAlreadyIncluded = true; break; } } if (!isAlreadyIncluded) { spectrumBands.add(new SpectrumBand(band, true)); } } } return spectrumBands.toArray(new SpectrumBand[spectrumBands.size()]); } private boolean isSpectralBand(Band band) { return band.getSpectralWavelength() > 0.0; } private void initUI() { final JFreeChart chart = ChartFactory.createXYLineChart(Bundle.CTL_SpectrumTopComponent_Name(), "Wavelength (nm)", "", null, PlotOrientation.VERTICAL, true, true, false); chart.getXYPlot().getRangeAxis().addChangeListener(axisChangeEvent -> { if (!isCodeInducedAxisChange) { rangeAxisAdjustmentIsFrozen = !((ValueAxis) axisChangeEvent.getAxis()).isAutoRange(); } }); chart.getXYPlot().getDomainAxis().addChangeListener(axisChangeEvent -> { if (!isCodeInducedAxisChange) { domainAxisAdjustmentIsFrozen = !((ValueAxis) axisChangeEvent.getAxis()).isAutoRange(); } }); chart.getXYPlot().getRangeAxis().setAutoRange(false); rangeAxisAdjustmentIsFrozen = false; chart.getXYPlot().getDomainAxis().setAutoRange(false); domainAxisAdjustmentIsFrozen = false; chartPanel = new ChartPanel(chart); chartHandler = new ChartHandler(chart); final XYPlotMarker plotMarker = new XYPlotMarker(chartPanel, new XYPlotMarker.Listener() { @Override public void pointSelected(XYDataset xyDataset, int seriesIndex, Point2D dataPoint) { //do nothing } @Override public void pointDeselected() { //do nothing } }); filterButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Filter24.gif"), false); filterButton.setName("filterButton"); filterButton.setEnabled(false); filterButton.addActionListener(e -> { selectSpectralBands(); recreateChart(); }); showSpectrumForCursorButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/CursorSpectrum24.gif"), true); showSpectrumForCursorButton.addActionListener(e -> recreateChart()); showSpectrumForCursorButton.setName("showSpectrumForCursorButton"); showSpectrumForCursorButton.setSelected(true); showSpectrumForCursorButton.setToolTipText("Show spectrum at cursor position."); showSpectraForSelectedPinsButton = ToolButtonFactory.createButton( UIUtils.loadImageIcon("icons/SelectedPinSpectra24.gif"), true); showSpectraForSelectedPinsButton.addActionListener(e -> { if (isShowingSpectraForAllPins()) { showSpectraForAllPinsButton.setSelected(false); } else if (!isShowingSpectraForSelectedPins()) { plotMarker.setInvisible(); } recreateChart(); }); showSpectraForSelectedPinsButton.setName("showSpectraForSelectedPinsButton"); showSpectraForSelectedPinsButton.setToolTipText("Show spectra for selected pins."); showSpectraForAllPinsButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/PinSpectra24.gif"), true); showSpectraForAllPinsButton.addActionListener(e -> { if (isShowingSpectraForSelectedPins()) { showSpectraForSelectedPinsButton.setSelected(false); } else if (!isShowingSpectraForAllPins()) { plotMarker.setInvisible(); } recreateChart(); }); showSpectraForAllPinsButton.setName("showSpectraForAllPinsButton"); showSpectraForAllPinsButton.setToolTipText("Show spectra for all pins."); showGridButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SpectrumGrid24.gif"), true); showGridButton.addActionListener(e -> chartHandler.setGridVisible(showGridButton.isSelected())); showGridButton.setName("showGridButton"); showGridButton.setToolTipText("Show diagram grid."); AbstractButton exportSpectraButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Export24.gif"), false); exportSpectraButton.addActionListener(new SpectraExportAction(this)); exportSpectraButton.setToolTipText("Export spectra to text file."); exportSpectraButton.setName("exportSpectraButton"); AbstractButton helpButton = ToolButtonFactory.createButton(new HelpAction(this), false); helpButton.setName("helpButton"); helpButton.setToolTipText("Help."); final JPanel buttonPane = GridBagUtils.createPanel(); final GridBagConstraints gbc = new GridBagConstraints(); gbc.anchor = GridBagConstraints.CENTER; gbc.fill = GridBagConstraints.NONE; gbc.insets.top = 2; gbc.gridy = 0; buttonPane.add(filterButton, gbc); gbc.gridy++; buttonPane.add(showSpectrumForCursorButton, gbc); gbc.gridy++; buttonPane.add(showSpectraForSelectedPinsButton, gbc); gbc.gridy++; buttonPane.add(showSpectraForAllPinsButton, gbc); gbc.gridy++; buttonPane.add(showGridButton, gbc); gbc.gridy++; buttonPane.add(exportSpectraButton, gbc); gbc.gridy++; gbc.insets.bottom = 0; gbc.fill = GridBagConstraints.VERTICAL; gbc.weighty = 1.0; gbc.gridwidth = 2; buttonPane.add(new JLabel(" "), gbc); // filler gbc.fill = GridBagConstraints.NONE; gbc.weighty = 0.0; gbc.gridy = 10; gbc.anchor = GridBagConstraints.EAST; buttonPane.add(helpButton, gbc); chartPanel.setPreferredSize(new Dimension(300, 200)); chartPanel.setBackground(Color.white); chartPanel.setBorder(BorderFactory.createCompoundBorder( BorderFactory.createBevelBorder(BevelBorder.LOWERED), BorderFactory.createEmptyBorder(2, 2, 2, 2))); chartPanel.addChartMouseListener(plotMarker); JPanel mainPane = new JPanel(new BorderLayout(4, 4)); mainPane.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); mainPane.add(BorderLayout.CENTER, chartPanel); mainPane.add(BorderLayout.EAST, buttonPane); mainPane.setPreferredSize(new Dimension(320, 200)); SnapApp.getDefault().getProductManager().addListener(new ProductManager.Listener() { @Override public void productAdded(ProductManager.Event event) { // ignored } @Override public void productRemoved(ProductManager.Event event) { final Product product = event.getProduct(); if (getCurrentProduct() == product) { chartPanel.getChart().getXYPlot().setDataset(null); setCurrentView(null); setCurrentProduct(null); } if (currentView != null) { final RasterDataNode currentRaster = currentView.getRaster(); rasterToSpectraMap.remove(currentRaster); rasterToSpectralBandsMap.remove(currentRaster); } PlacemarkGroup pinGroup = product.getPinGroup(); for (int i = 0; i < pinGroup.getNodeCount(); i++) { chartHandler.removePinInformation(pinGroup.get(i)); } } }); final ProductSceneView view = getSelectedProductSceneView(); if (view != null) { productSceneViewSelected(view); } setDisplayName(Bundle.CTL_SpectrumTopComponent_Name()); setLayout(new BorderLayout()); add(mainPane, BorderLayout.CENTER); updateUIState(); } private void selectSpectralBands() { final RasterDataNode currentRaster = currentView.getRaster(); final DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentRaster); final SpectrumChooser spectrumChooser = new SpectrumChooser(SwingUtilities.getWindowAncestor(this), allSpectra); if (spectrumChooser.show() == AbstractDialog.ID_OK) { final DisplayableSpectrum[] spectra = spectrumChooser.getSpectra(); rasterToSpectraMap.put(currentRaster, spectra); } } boolean isShowingCursorSpectrum() { return showSpectrumForCursorButton.isSelected(); } private boolean isShowingPinSpectra() { return isShowingSpectraForSelectedPins() || isShowingSpectraForAllPins(); } private boolean isShowingSpectraForAllPins() { return showSpectraForAllPinsButton.isSelected(); } private void recreateChart() { chartHandler.updateData(); chartHandler.updateChart(); chartPanel.repaint(); updateUIState(); } Placemark[] getDisplayedPins() { if (isShowingSpectraForSelectedPins() && currentView != null) { return currentView.getSelectedPins(); } else if (isShowingSpectraForAllPins() && currentProduct != null) { ProductNodeGroup<Placemark> pinGroup = currentProduct.getPinGroup(); return pinGroup.toArray(new Placemark[pinGroup.getNodeCount()]); } else { return new Placemark[0]; } } private void setUpSpectra() { if (currentView == null) { return; } DisplayableSpectrum[] spectra; final RasterDataNode raster = currentView.getRaster(); final SpectrumBand[] availableSpectralBands = getAvailableSpectralBands(raster); if (availableSpectralBands.length == 0) { spectra = new DisplayableSpectrum[]{}; } else { final Product.AutoGrouping autoGrouping = currentProduct.getAutoGrouping(); if (autoGrouping != null) { final int selectedSpectrumIndex = autoGrouping.indexOf(raster.getName()); DisplayableSpectrum[] autoGroupingSpectra = new DisplayableSpectrum[autoGrouping.size()]; final Iterator<String[]> iterator = autoGrouping.iterator(); int i = 0; while (iterator.hasNext()) { final String[] autoGroupingNameAsArray = iterator.next(); StringBuilder spectrumNameBuilder = new StringBuilder(autoGroupingNameAsArray[0]); if (autoGroupingNameAsArray.length > 1) { for (int j = 1; j < autoGroupingNameAsArray.length; j++) { String autoGroupingNamePart = autoGroupingNameAsArray[j]; spectrumNameBuilder.append("_").append(autoGroupingNamePart); } } final String spectrumName = spectrumNameBuilder.toString(); int symbolIndex = SpectrumShapeProvider.getValidIndex(i, false); DisplayableSpectrum spectrum = new DisplayableSpectrum(spectrumName, symbolIndex); spectrum.setSelected(i == selectedSpectrumIndex); spectrum.setLineStyle(SpectrumStrokeProvider.getStroke(i)); autoGroupingSpectra[i] = spectrum; i++; } List<SpectrumBand> ungroupedBandsList = new ArrayList<>(); for (SpectrumBand availableSpectralBand : availableSpectralBands) { final String bandName = availableSpectralBand.getName(); final int spectrumIndex = autoGrouping.indexOf(bandName); if (spectrumIndex != -1) { autoGroupingSpectra[spectrumIndex].addBand(availableSpectralBand); } else { ungroupedBandsList.add(availableSpectralBand); } } if (ungroupedBandsList.size() == 0) { spectra = autoGroupingSpectra; } else { final DisplayableSpectrum[] spectraFromUngroupedBands = createSpectraFromUngroupedBands(ungroupedBandsList.toArray(new SpectrumBand[0]), SpectrumShapeProvider.getValidIndex(i, false), i); spectra = new DisplayableSpectrum[autoGroupingSpectra.length + spectraFromUngroupedBands.length]; System.arraycopy(autoGroupingSpectra, 0, spectra, 0, autoGroupingSpectra.length); System.arraycopy(spectraFromUngroupedBands, 0, spectra, autoGroupingSpectra.length, spectraFromUngroupedBands.length); } } else { spectra = createSpectraFromUngroupedBands(availableSpectralBands, 1, 0); } } rasterToSpectraMap.put(raster, spectra); } private DisplayableSpectrum[] getAllSpectra() { if (currentView == null || !rasterToSpectraMap.containsKey(currentView.getRaster())) { return new DisplayableSpectrum[0]; } return rasterToSpectraMap.get(currentView.getRaster()); } private boolean isShowingSpectraForSelectedPins() { return showSpectraForSelectedPinsButton.isSelected(); } List<DisplayableSpectrum> getSelectedSpectra() { List<DisplayableSpectrum> selectedSpectra = new ArrayList<>(); if (currentView != null) { final RasterDataNode currentRaster = currentView.getRaster(); if (currentProduct != null && rasterToSpectraMap.containsKey(currentRaster)) { DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentRaster); for (DisplayableSpectrum displayableSpectrum : allSpectra) { if (displayableSpectrum.isSelected()) { selectedSpectra.add(displayableSpectrum); } } } } return selectedSpectra; } private void updateSpectraUnits() { for (DisplayableSpectrum spectrum : getAllSpectra()) { spectrum.updateUnit(); } } void removeCursorSpectraFromDataset() { chartHandler.removeCursorSpectraFromDataset(); } @Override protected void productSceneViewSelected(ProductSceneView view) { view.addPixelPositionListener(pixelPositionListener); setCurrentView(view); } @Override protected void productSceneViewDeselected(ProductSceneView view) { view.removePixelPositionListener(pixelPositionListener); setCurrentView(null); } @Override protected void componentOpened() { final ProductSceneView selectedProductSceneView = getSelectedProductSceneView(); if (selectedProductSceneView != null) { selectedProductSceneView.addPixelPositionListener(pixelPositionListener); setCurrentView(selectedProductSceneView); } } @Override protected void componentClosed() { if (currentView != null) { currentView.removePixelPositionListener(pixelPositionListener); } } public boolean showsValidCursorSpectra() { return chartHandler.showsValidCursorSpectra(); } Map<Placemark, Map<Band, Double>> getPinToEnergies() { return chartHandler.getPinToEnergies(); } private class ChartHandler { private static final String MESSAGE_NO_SPECTRAL_BANDS = "No spectral bands available"; /*I18N*/ private static final String MESSAGE_NO_PRODUCT_SELECTED = "No product selected"; private static final String MESSAGE_NO_SPECTRA_SELECTED = "No spectra selected"; private static final String MESSAGE_COLLECTING_SPECTRAL_INFORMATION = "Collecting spectral information..."; private final JFreeChart chart; private final ChartUpdater chartUpdater; private ChartHandler(JFreeChart chart) { chartUpdater = new ChartUpdater(); this.chart = chart; setLegend(chart); setAutomaticRangeAdjustments(false); final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); renderer.setDefaultLinesVisible(true); renderer.setDefaultShapesFilled(false); setPlotMessage(MESSAGE_NO_PRODUCT_SELECTED); } private void setAutomaticRangeAdjustments(boolean userInducesAutomaticAdjustment) { final XYPlot plot = chart.getXYPlot(); boolean adjustmentHasChanged = false; if (userInducesAutomaticAdjustment) { if (!isUserInducedAutomaticAdjustmentChosen) { isUserInducedAutomaticAdjustmentChosen = true; if (!isAutomaticDomainAdjustmentSet()) { plot.getDomainAxis().setAutoRange(true); domainAxisAdjustmentIsFrozen = false; adjustmentHasChanged = true; } if (!isAutomaticRangeAdjustmentSet()) { plot.getRangeAxis().setAutoRange(true); rangeAxisAdjustmentIsFrozen = false; adjustmentHasChanged = true; } } } else { if (isUserInducedAutomaticAdjustmentChosen) { isUserInducedAutomaticAdjustmentChosen = false; if (isAutomaticDomainAdjustmentSet()) { plot.getDomainAxis().setAutoRange(false); domainAxisAdjustmentIsFrozen = false; adjustmentHasChanged = true; } if (isAutomaticRangeAdjustmentSet()) { plot.getRangeAxis().setAutoRange(false); rangeAxisAdjustmentIsFrozen = false; adjustmentHasChanged = true; } } } if (adjustmentHasChanged) { chartUpdater.invalidatePlotBounds(); } } private boolean isAutomaticDomainAdjustmentSet() { return chart.getXYPlot().getDomainAxis().isAutoRange(); } private boolean isAutomaticRangeAdjustmentSet() { return chart.getXYPlot().getRangeAxis().isAutoRange(); } private void setLegend(JFreeChart chart) { chart.removeLegend(); final LegendTitle legend = new LegendTitle(new SpectrumLegendItemSource()); legend.setPosition(RectangleEdge.BOTTOM); LineBorder border = new LineBorder(Color.BLACK, new BasicStroke(), new RectangleInsets(2, 2, 2, 2)); legend.setFrame(border); chart.addLegend(legend); } private void setPosition(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) { chartUpdater.setPosition(pixelX, pixelY, level, pixelPosInRasterBounds); } private void updateChart() { if (chartUpdater.isDatasetEmpty()) { setEmptyPlot(); return; } List<DisplayableSpectrum> spectra = getSelectedSpectra(); chartUpdater.updateChart(chart, spectra); chart.getXYPlot().clearAnnotations(); } private void updateData() { List<DisplayableSpectrum> spectra = getSelectedSpectra(); chartUpdater.updateData(chart, spectra); } private void setEmptyPlot() { chart.getXYPlot().setDataset(null); if (getCurrentProduct() == null) { setPlotMessage(MESSAGE_NO_PRODUCT_SELECTED); } else if (!chartUpdater.showsValidCursorSpectra()) { } else if (getAllSpectra().length == 0) { setPlotMessage(MESSAGE_NO_SPECTRA_SELECTED); } else { setPlotMessage(MESSAGE_NO_SPECTRAL_BANDS); } } private void setGridVisible(boolean visible) { chart.getXYPlot().setDomainGridlinesVisible(visible); chart.getXYPlot().setRangeGridlinesVisible(visible); } private void removePinInformation(Placemark pin) { chartUpdater.removePinInformation(pin); } private void removeBandInformation(Band band) { chartUpdater.removeBandinformation(band); } private void setPlotMessage(String messageText) { chart.getXYPlot().clearAnnotations(); TextTitle tt = new TextTitle(messageText); tt.setTextAlignment(HorizontalAlignment.RIGHT); tt.setFont(chart.getLegend().getItemFont()); tt.setBackgroundPaint(new Color(200, 200, 255, 50)); tt.setFrame(new BlockBorder(Color.white)); tt.setPosition(RectangleEdge.BOTTOM); XYTitleAnnotation message = new XYTitleAnnotation(0.5, 0.5, tt, RectangleAnchor.CENTER); chart.getXYPlot().addAnnotation(message); } public boolean showsValidCursorSpectra() { return chartUpdater.showsValidCursorSpectra(); } public void removeCursorSpectraFromDataset() { chartUpdater.removeCursorSpectraFromDataset(); } public void setCollectingSpectralInformationMessage() { setPlotMessage(MESSAGE_COLLECTING_SPECTRAL_INFORMATION); } public Map<Placemark, Map<Band, Double>> getPinToEnergies() { return chartUpdater.getPinToEnergies(); } } private class ChartUpdater { private final static int domain_axis_index = 0; private final static int range_axis_index = 1; private final static double relativePlotInset = 0.05; private final Map<Placemark, Map<Band, Double>> pinToEnergies; private boolean showsValidCursorSpectra; private boolean pixelPosInRasterBounds; private int rasterPixelX; private int rasterPixelY; private int rasterLevel; private final Range[] plotBounds; private XYSeriesCollection dataset; private Point2D modelP; private ChartUpdater() { pinToEnergies = new HashMap<>(); plotBounds = new Range[2]; invalidatePlotBounds(); } void invalidatePlotBounds() { plotBounds[domain_axis_index] = null; plotBounds[range_axis_index] = null; } private void setPosition(int pixelX, int pixelY, int level, boolean pixelPosInRasterBounds) { rasterPixelX = pixelX; rasterPixelY = pixelY; rasterLevel = level; this.pixelPosInRasterBounds = pixelPosInRasterBounds; final AffineTransform i2m = currentView.getBaseImageLayer().getImageToModelTransform(level); modelP = i2m.transform(new Point2D.Double(pixelX + 0.5, pixelY + 0.5), new Point2D.Double()); } private void updateData(JFreeChart chart, List<DisplayableSpectrum> spectra) { dataset = new XYSeriesCollection(); if (rasterLevel >= 0) { fillDatasetWithPinSeries(spectra, dataset, chart); fillDatasetWithCursorSeries(spectra, dataset, chart); } } private void updateChart(JFreeChart chart, List<DisplayableSpectrum> spectra) { final XYPlot plot = chart.getXYPlot(); if (!chartHandler.isAutomaticDomainAdjustmentSet() && !domainAxisAdjustmentIsFrozen) { isCodeInducedAxisChange = true; updatePlotBounds(dataset.getDomainBounds(true), plot.getDomainAxis(), domain_axis_index); isCodeInducedAxisChange = false; } if (!chartHandler.isAutomaticRangeAdjustmentSet() && !rangeAxisAdjustmentIsFrozen) { isCodeInducedAxisChange = true; updatePlotBounds(dataset.getRangeBounds(true), plot.getRangeAxis(), range_axis_index); isCodeInducedAxisChange = false; } plot.setDataset(dataset); setPlotUnit(spectra, plot); } private void setPlotUnit(List<DisplayableSpectrum> spectra, XYPlot plot) { String unitToBeDisplayed = ""; if (spectra.size() > 0) { unitToBeDisplayed = spectra.get(0).getUnit(); int i = 1; while (i < spectra.size() && !unitToBeDisplayed.equals(DisplayableSpectrum.MIXED_UNITS)) { DisplayableSpectrum displayableSpectrum = spectra.get(i); i++; if (displayableSpectrum.hasSelectedBands() && !unitToBeDisplayed.equals(displayableSpectrum.getUnit())) { unitToBeDisplayed = DisplayableSpectrum.MIXED_UNITS; } } } isCodeInducedAxisChange = true; plot.getRangeAxis().setLabel(unitToBeDisplayed); isCodeInducedAxisChange = false; } private void updatePlotBounds(Range newBounds, ValueAxis axis, int index) { if (newBounds != null) { final Range axisBounds = axis.getRange(); final Range oldBounds = plotBounds[index]; plotBounds[index] = getNewRange(newBounds, plotBounds[index], axisBounds); if (oldBounds != plotBounds[index]) { axis.setRange(getNewPlotBounds(plotBounds[index])); } } } private Range getNewRange(Range newBounds, Range currentBounds, Range plotBounds) { if (currentBounds == null) { currentBounds = newBounds; } else { if (plotBounds.getLowerBound() > 0 && newBounds.getLowerBound() < currentBounds.getLowerBound() || newBounds.getUpperBound() > currentBounds.getUpperBound()) { currentBounds = new Range(Math.min(currentBounds.getLowerBound(), newBounds.getLowerBound()), Math.max(currentBounds.getUpperBound(), newBounds.getUpperBound())); } } return currentBounds; } private Range getNewPlotBounds(Range bounds) { double range = bounds.getLength(); double delta = range * relativePlotInset; return new Range(Math.max(0, bounds.getLowerBound() - delta), bounds.getUpperBound() + delta); } private void fillDatasetWithCursorSeries(List<DisplayableSpectrum> spectra, XYSeriesCollection dataset, JFreeChart chart) { showsValidCursorSpectra = false; if (modelP == null) { return; } if (isShowingCursorSpectrum() && currentView != null) { for (DisplayableSpectrum spectrum : spectra) { XYSeries series = new XYSeries(spectrum.getName()); final Band[] spectralBands = spectrum.getSelectedBands(); if (!currentProduct.isMultiSize()) { for (Band spectralBand : spectralBands) { final float wavelength = spectralBand.getSpectralWavelength(); if (pixelPosInRasterBounds && isPixelValid(spectralBand, rasterPixelX, rasterPixelY, rasterLevel)) { addToSeries(spectralBand, rasterPixelX, rasterPixelY, rasterLevel, series, wavelength); showsValidCursorSpectra = true; } } } else { for (Band spectralBand : spectralBands) { final float wavelength = spectralBand.getSpectralWavelength(); final AffineTransform i2m = spectralBand.getImageToModelTransform(); if (i2m.equals(currentView.getRaster().getImageToModelTransform())) { if (pixelPosInRasterBounds && isPixelValid(spectralBand, rasterPixelX, rasterPixelY, rasterLevel)) { addToSeries(spectralBand, rasterPixelX, rasterPixelY, rasterLevel, series, wavelength); showsValidCursorSpectra = true; } } else { //todo [Multisize_products] use scenerastertransform here final PixelPos rasterPos = new PixelPos(); final MultiLevelModel multiLevelModel = spectralBand.getMultiLevelModel(); int level = getLevel(multiLevelModel); multiLevelModel.getModelToImageTransform(level).transform(modelP, rasterPos); final int rasterX = (int) rasterPos.getX(); final int rasterY = (int) rasterPos.getY(); if (coordinatesAreInRasterBounds(spectralBand, rasterX, rasterY, level) && isPixelValid(spectralBand, rasterX, rasterY, level)) { addToSeries(spectralBand, rasterX, rasterY, level, series, wavelength); showsValidCursorSpectra = true; } } } } updateRenderer(dataset.getSeriesCount(), Color.BLACK, spectrum, chart); dataset.addSeries(series); } } } private void addToSeries(Band spectralBand, int x, int y, int level, XYSeries series, double wavelength) { final double energy = ProductUtils.getGeophysicalSampleAsDouble(spectralBand, x, y, level); if (energy != spectralBand.getGeophysicalNoDataValue()) { series.add(wavelength, energy); } } //todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119 private boolean coordinatesAreInRasterBounds(RasterDataNode raster, int x, int y, int level) { final RenderedImage levelImage = raster.getSourceImage().getImage(level); return x >= 0 && y >= 0 && x < levelImage.getWidth() && y < levelImage.getHeight(); } private void fillDatasetWithPinSeries(List<DisplayableSpectrum> spectra, XYSeriesCollection dataset, JFreeChart chart) { Placemark[] pins = getDisplayedPins(); for (Placemark pin : pins) { List<XYSeries> pinSeries = createXYSeriesFromPin(pin, dataset.getSeriesCount(), spectra, chart); pinSeries.forEach(dataset::addSeries); } } private List<XYSeries> createXYSeriesFromPin(Placemark pin, int seriesIndex, List<DisplayableSpectrum> spectra, JFreeChart chart) { List<XYSeries> pinSeries = new ArrayList<>(); Color pinColor = PlacemarkUtils.getPlacemarkColor(pin, currentView); for (DisplayableSpectrum spectrum : spectra) { XYSeries series = new XYSeries(spectrum.getName() + "_" + pin.getLabel()); final Band[] spectralBands = spectrum.getSelectedBands(); Map<Band, Double> bandToEnergy; if (pinToEnergies.containsKey(pin)) { bandToEnergy = pinToEnergies.get(pin); } else { bandToEnergy = new HashMap<>(); pinToEnergies.put(pin, bandToEnergy); } for (Band spectralBand : spectralBands) { double energy; if (bandToEnergy.containsKey(spectralBand)) { energy = bandToEnergy.get(spectralBand); } else { energy = readEnergy(pin, spectralBand); bandToEnergy.put(spectralBand, energy); } final float wavelength = spectralBand.getSpectralWavelength(); if (energy != spectralBand.getGeophysicalNoDataValue()) { series.add(wavelength, energy); } } updateRenderer(seriesIndex, pinColor, spectrum, chart); seriesIndex++; pinSeries.add(series); } return pinSeries; } private void updateRenderer(int seriesIndex, Color seriesColor, DisplayableSpectrum spectrum, JFreeChart chart) { final XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) chart.getXYPlot().getRenderer(); final Stroke lineStyle = spectrum.getLineStyle(); renderer.setSeriesStroke(seriesIndex, lineStyle); Shape symbol = spectrum.getScaledShape(); renderer.setSeriesShape(seriesIndex, symbol); renderer.setSeriesShapesVisible(seriesIndex, true); renderer.setSeriesPaint(seriesIndex, seriesColor); } private double readEnergy(Placemark pin, Band spectralBand) { //todo [Multisize_products] use scenerastertransform here final Object pinGeometry = pin.getFeature().getDefaultGeometry(); if (pinGeometry == null || !(pinGeometry instanceof Point)) { return spectralBand.getGeophysicalNoDataValue(); } final Point2D.Double modelPoint = new Point2D.Double(((Point) pinGeometry).getCoordinate().x, ((Point) pinGeometry).getCoordinate().y); final MultiLevelModel multiLevelModel = spectralBand.getMultiLevelModel(); int level = getLevel(multiLevelModel); final AffineTransform m2iTransform = multiLevelModel.getModelToImageTransform(level); final PixelPos pinLevelRasterPos = new PixelPos(); m2iTransform.transform(modelPoint, pinLevelRasterPos); int pinLevelRasterX = (int) Math.floor(pinLevelRasterPos.getX()); int pinLevelRasterY = (int) Math.floor(pinLevelRasterPos.getY()); if (coordinatesAreInRasterBounds(spectralBand, pinLevelRasterX, pinLevelRasterY, level) && isPixelValid(spectralBand, pinLevelRasterX, pinLevelRasterY, level)) { return ProductUtils.getGeophysicalSampleAsDouble(spectralBand, pinLevelRasterX, pinLevelRasterY, level); } return spectralBand.getGeophysicalNoDataValue(); } private void removePinInformation(Placemark pin) { pinToEnergies.remove(pin); } private void removeBandinformation(Band band) { for (Placemark pin : pinToEnergies.keySet()) { Map<Band, Double> bandToEnergiesMap = pinToEnergies.get(pin); bandToEnergiesMap.remove(band); } } public boolean showsValidCursorSpectra() { return showsValidCursorSpectra; } void removeCursorSpectraFromDataset() { modelP = null; if (showsValidCursorSpectra) { int numberOfSelectedSpectra = getSelectedSpectra().size(); int numberOfPins = getDisplayedPins().length; int numberOfDisplayedGraphs = numberOfPins * numberOfSelectedSpectra; while (dataset.getSeriesCount() > numberOfDisplayedGraphs) { dataset.removeSeries(dataset.getSeriesCount() - 1); } } } public boolean isDatasetEmpty() { return dataset == null || dataset.getSeriesCount() == 0; } //todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119 private boolean isPixelValid(RasterDataNode raster, int pixelX, int pixelY, int level) { if (raster.isValidMaskUsed()) { PlanarImage image = ImageManager.getInstance().getValidMaskImage(raster, level); Raster data = getRasterTile(image, pixelX, pixelY); return data.getSample(pixelX, pixelY, 0) != 0; } else { return true; } } //todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119 private Raster getRasterTile(PlanarImage image, int pixelX, int pixelY) { final int tileX = image.XToTileX(pixelX); final int tileY = image.YToTileY(pixelY); return image.getTile(tileX, tileY); } //todo code duplication with pixelinfoviewmodelupdater - move to single class - tf 20151119 private int getLevel(MultiLevelModel multiLevelModel) { if (rasterLevel < multiLevelModel.getLevelCount()) { return rasterLevel; } return ImageLayer.getLevel(multiLevelModel, currentView.getViewport()); } Map<Placemark, Map<Band, Double>> getPinToEnergies() { return pinToEnergies; } } private class SpectrumLegendItemSource implements LegendItemSource { @Override public LegendItemCollection getLegendItems() { LegendItemCollection itemCollection = new LegendItemCollection(); final Placemark[] displayedPins = getDisplayedPins(); final List<DisplayableSpectrum> spectra = getSelectedSpectra(); for (Placemark pin : displayedPins) { Paint pinPaint = PlacemarkUtils.getPlacemarkColor(pin, currentView); spectra.stream().filter(DisplayableSpectrum::hasSelectedBands).forEach(spectrum -> { String legendLabel = pin.getLabel() + "_" + spectrum.getName(); LegendItem item = createLegendItem(spectrum, pinPaint, legendLabel); itemCollection.add(item); }); } if (isShowingCursorSpectrum() && showsValidCursorSpectra()) { spectra.stream().filter(DisplayableSpectrum::hasSelectedBands).forEach(spectrum -> { Paint defaultPaint = Color.BLACK; LegendItem item = createLegendItem(spectrum, defaultPaint, spectrum.getName()); itemCollection.add(item); }); } return itemCollection; } private LegendItem createLegendItem(DisplayableSpectrum spectrum, Paint paint, String legendLabel) { Stroke outlineStroke = new BasicStroke(); Line2D lineShape = new Line2D.Double(0, 5, 40, 5); Stroke lineStyle = spectrum.getLineStyle(); Shape symbol = spectrum.getScaledShape(); return new LegendItem(legendLabel, legendLabel, legendLabel, legendLabel, true, symbol, false, paint, true, paint, outlineStroke, true, lineShape, lineStyle, paint); } } ///////////////////////////////////////////////////////////////////////// // Product change handling private class ProductNodeHandler extends ProductNodeListenerAdapter { @Override public void nodeChanged(final ProductNodeEvent event) { boolean chartHasChanged = false; if (event.getSourceNode() instanceof Band) { final String propertyName = event.getPropertyName(); if (propertyName.equals(DataNode.PROPERTY_NAME_UNIT)) { updateSpectraUnits(); chartHasChanged = true; } else if (propertyName.equals(Band.PROPERTY_NAME_SPECTRAL_WAVELENGTH)) { setUpSpectra(); chartHasChanged = true; } } else if (event.getSourceNode() instanceof Placemark) { if ("geoPos".equals(event.getPropertyName()) || "pixelPos".equals(event.getPropertyName())) { chartHandler.removePinInformation((Placemark) event.getSourceNode()); } if (isShowingPinSpectra()) { chartHasChanged = true; } } else if (event.getSourceNode() instanceof Product) { if ("autoGrouping".equals(event.getPropertyName())) { setUpSpectra(); chartHasChanged = true; } } if (isActive() && chartHasChanged) { recreateChart(); } } @Override public void nodeAdded(final ProductNodeEvent event) { if (!isActive()) { return; } if (event.getSourceNode() instanceof Band) { Band newBand = (Band) event.getSourceNode(); if (isSpectralBand(newBand)) { addBandToSpectra((Band) event.getSourceNode()); recreateChart(); } } else if (event.getSourceNode() instanceof Placemark) { if (isShowingPinSpectra()) { recreateChart(); } else { updateUIState(); } } } @Override public void nodeRemoved(final ProductNodeEvent event) { if (!isActive()) { return; } if (event.getSourceNode() instanceof Band) { Band band = (Band) event.getSourceNode(); removeBandFromSpectra(band); chartHandler.removeBandInformation(band); recreateChart(); } else if (event.getSourceNode() instanceof Placemark) { if (isShowingPinSpectra()) { recreateChart(); } } } private void addBandToSpectra(Band band) { DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentView.getRaster()); Product.AutoGrouping autoGrouping = currentProduct.getAutoGrouping(); if (autoGrouping != null) { final int bandIndex = autoGrouping.indexOf(band.getName()); final DisplayableSpectrum spectrum; if (bandIndex != -1) { spectrum = allSpectra[bandIndex]; } else { spectrum = allSpectra[allSpectra.length - 1]; } spectrum.addBand(new SpectrumBand(band, spectrum.isSelected())); } else { allSpectra[0].addBand(new SpectrumBand(band, true)); } } private void removeBandFromSpectra(Band band) { DisplayableSpectrum[] allSpectra = rasterToSpectraMap.get(currentView.getRaster()); for (DisplayableSpectrum displayableSpectrum : allSpectra) { Band[] spectralBands = displayableSpectrum.getSpectralBands(); for (int j = 0; j < spectralBands.length; j++) { Band spectralBand = spectralBands[j]; if (spectralBand == band) { displayableSpectrum.remove(j); if (displayableSpectrum.getSelectedBands().length == 0) { displayableSpectrum.setSelected(false); } return; } } } } private boolean isActive() { return isVisible() && getCurrentProduct() != null; } } private class PinSelectionChangeListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { recreateChart(); } } }
55,225
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ContextWebSearch.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/ctxhelp/ContextWebSearch.java
package org.esa.snap.rcp.ctxhelp; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.util.SystemUtils; import java.awt.Desktop; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.net.URLEncoder; import java.nio.file.FileSystem; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.Properties; import java.util.logging.Level; /** * Adds contextual search support to Snap. * <p> * A contextual search is performed if a product node is selected and CTRL+F1 is pressed. * * @author Norman Fomferra */ public class ContextWebSearch { private static final String DEFAULT_SEARCH = "http://www.google.com/search?q="; private static final String DEFAULT_QUERY = "ESA Sentinel Toolbox"; private static final String CONFIG_FILENAME = "context-search.properties"; private static ContextWebSearch instance; private final Properties config; public static ContextWebSearch getDefault() { if (instance == null) { instance = new ContextWebSearch(); } return instance; } public void searchForNode(ProductNode node) { String searchString = getSearch(); String queryString = getQueryString(node); try { String search = searchString + URLEncoder.encode(queryString, "UTF-8"); URI uri = URI.create(search); Desktop.getDesktop().browse(uri); } catch (IOException e) { SystemUtils.LOG.log(Level.WARNING, "Failed to perform context search"); } } public ContextWebSearch() { this.config = new Properties(); try { loadConfig(); } catch (IOException e) { SystemUtils.LOG.log(Level.SEVERE, "Failed to load context search configuration", e); } } private String getSearch() { return config.getProperty("search", DEFAULT_SEARCH); } private String getQuery() { return config.getProperty("query", DEFAULT_QUERY); } private String getQuery(String productType, String def) { return config.getProperty(String.format("products.%s.query", productType.replace(" ", "_")), def); } private String getQueryString(ProductNode node) { String contextTerms = getQuery(); if (node == null) { return contextTerms; } Product product = node.getProduct(); if (product != null) { String productType = product.getProductType(); if (productType != null) { contextTerms = getQuery(productType, contextTerms); } } String nodeName = node.getName(); String[] nodeNameSplits = nodeName.split("[\\.\\_\\ \\-]"); StringBuilder nodeNameTerms = new StringBuilder(); for (String nodeNameSplit : nodeNameSplits) { if (!nodeNameSplit.isEmpty() && Character.isAlphabetic(nodeNameSplit.charAt(0))) { if (nodeNameTerms.length() > 0) { nodeNameTerms.append(" OR "); } nodeNameTerms.append(nodeNameSplit); } } return contextTerms + " " + nodeNameTerms; } private void loadConfig() throws IOException { Path file = getConfigPath(); try (FileReader reader = new FileReader(file.toFile())) { config.load(reader); } } private Path getConfigPath() throws IOException { FileSystem fs = FileSystems.getDefault(); // todo: fix SystemUtils.getApplicationDataDir() (nf, 201502059) Path dir = SystemUtils.getAuxDataPath(); if (Files.notExists(dir)) { Files.createDirectories(dir); } Path file = fs.getPath(dir.toString(), CONFIG_FILENAME); if (Files.notExists(file)) { try (InputStream resourceAsStream = getClass().getResourceAsStream(CONFIG_FILENAME)) { Files.copy(resourceAsStream, file); } } return file; } }
4,153
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ContextWebSearchAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/ctxhelp/ContextWebSearchAction.java
package org.esa.snap.rcp.ctxhelp; import org.esa.snap.rcp.SnapApp; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.HelpCtx; import org.openide.util.NbBundle; import javax.swing.AbstractAction; import java.awt.event.ActionEvent; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.*; /** * Provides context-sensitive web search. * * @author Norman Fomferra */ @ActionID( category = "Help", id = "org.esa.snap.rcp.ctxhelp.ContextSearchAction" ) @ActionRegistration( displayName = "#CTL_ContextSearchAction_Name", lazy = true ) @ActionReferences({ @ActionReference(path = "Menu/Help", position = 210), @ActionReference(path = "Shortcuts", name = "D-F1") }) @NbBundle.Messages({ "CTL_ContextSearchAction_Name=Context Web Search", "CTL_ContextSearchAction_ToolTip=Perform a contextual web search on the selected product element." }) public class ContextWebSearchAction extends AbstractAction implements HelpCtx.Provider { public ContextWebSearchAction() { super(Bundle.CTL_ContextSearchAction_Name()); } @Override public void actionPerformed(ActionEvent e) { ContextWebSearch contextWebSearch = ContextWebSearch.getDefault(); if (contextWebSearch != null) { contextWebSearch.searchForNode(SnapApp.getDefault().getSelectedProductNode(AUTO)); } } @Override public HelpCtx getHelpCtx() { return new HelpCtx("contextWebSearch"); } }
1,623
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SnapKeyStoreProvider.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/autoupdate/SnapKeyStoreProvider.java
package org.esa.snap.rcp.autoupdate; import org.esa.snap.rcp.SnapApp; import org.netbeans.spi.autoupdate.KeyStoreProvider; import java.io.InputStream; import java.security.KeyStore; import java.util.logging.Level; @org.openide.util.lookup.ServiceProvider(service = org.netbeans.spi.autoupdate.KeyStoreProvider.class) public final class SnapKeyStoreProvider implements KeyStoreProvider { private static final String KS_RESOURCE_PATH = "/keystore/snap.ks"; @Override public KeyStore getKeyStore() { try (InputStream inputStream = getClass().getResourceAsStream(KS_RESOURCE_PATH)) { KeyStore keyStore; keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(inputStream, null); return keyStore; } catch (Exception ex) { SnapApp.getDefault().getLogger().log(Level.WARNING, ex.getMessage(), ex); } return null; } }
941
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PreferencesPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/PreferencesPanel.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; import com.bc.ceres.binding.Property; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyPane; import javax.swing.*; import java.awt.*; /** * Non-public helper class. * * @author thomas */ class PreferencesPanel { private final BindingContext bindingContext; private JPanel panel; private boolean changed = false; PreferencesPanel(JPanel panel, BindingContext bindingContext) { this.panel = panel; this.bindingContext = bindingContext; for (Property property : bindingContext.getPropertySet().getProperties()) { property.addPropertyChangeListener(evt -> { changed = true; }); } } JPanel getComponent() { if (panel == null) { panel = new JPanel(new BorderLayout()); panel.add(new PropertyPane(bindingContext).createPanel(), BorderLayout.CENTER); } return panel; } boolean isChanged() { return changed; } void setChanged(boolean changed) { this.changed = changed; } }
1,862
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PreferenceUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/PreferenceUtils.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; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.util.SystemUtils; import org.openide.awt.ColorComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Contains some static helper functions. * * @author thomas * @author Daniel Knowles */ // SEP2018 - Daniel Knowles - Fixes bug where colorComboBox was not listening to properties change event when // DefaultConfigController was loading the user saved preferences public class PreferenceUtils { /** * Adds a text note to the given <code>JPanel</code>. * * @param panel A panel to add the note to. * @param text The note text. */ public static void addNote(JPanel panel, String text) { JLabel note = new JLabel(text); if (note.getFont() != null) { note.setFont(note.getFont().deriveFont(Font.ITALIC)); } note.setForeground(new Color(0, 0, 92)); panel.add(note); } /** * Creates color combobox components for a given property. * * @param colorProperty The property to create the components for. * * @return A new color combobox. */ public static JComponent[] createColorComponents(Property colorProperty) { JComponent[] components = new JComponent[2]; components[0] = new JLabel(colorProperty.getDescriptor().getDisplayName() + ":"); components[1] = createColorCombobox(colorProperty); return components; } /** * Creates a <code>JPanel</code> containing a label with the given text and a horizontal line. * * @param title The label text. * * @return A <code>JPanel</code> with the title label. */ public static JPanel createTitleLabel(String title) { TableLayout layout = new TableLayout(3); layout.setColumnWeightX(0, 0.0); layout.setColumnWeightX(1, 0.0); layout.setColumnWeightX(2, 1.0); layout.setColumnFill(0, TableLayout.Fill.NONE); layout.setColumnFill(1, TableLayout.Fill.NONE); layout.setColumnFill(2, TableLayout.Fill.HORIZONTAL); JPanel comp = new JPanel(layout); JLabel label = new JLabel(title); comp.add(label); comp.add(new JLabel(" ")); comp.add(new JSeparator()); return comp; } private static ColorComboBox createColorCombobox(final Property property) { ColorComboBox colorComboBox = new ColorComboBox(); colorComboBox.setSelectedColor(property.getValue()); colorComboBox.getModel().addListDataListener(new ListDataListener() { @Override public void intervalAdded(ListDataEvent e) { } @Override public void intervalRemoved(ListDataEvent e) { } @Override public void contentsChanged(ListDataEvent e) { try { property.setValue(colorComboBox.getSelectedColor()); } catch (ValidationException e1) { SystemUtils.LOG.warning("Color preference conversion error: " + e1.getMessage()); } } }); colorComboBox.setPreferredSize(new Dimension(colorComboBox.getWidth(), 25)); // Modification by Daniel Knowles SEP2018 // Add PropertyChangeListener to the passed in property which when triggered sets the colorComboBox selected color. // This fixes bug where colorComboBox was not listening to properties change event when DefaultConfigController was // loading the user saved preferences property.addPropertyChangeListener(new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { colorComboBox.setSelectedColor(property.getValue()); } }); return colorComboBox; } }
5,061
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DefaultConfigController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/DefaultConfigController.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; 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.Validator; import com.bc.ceres.binding.ValueRange; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.core.Assert; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.util.StringUtils; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.runtime.Config; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.Lookup; import javax.swing.JComponent; import javax.swing.JPanel; import java.beans.PropertyChangeListener; import java.util.HashSet; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; /** * Abstract superclass for preferences pages. Subclasses need to be annotated with either * {@link OptionsPanelController.TopLevelRegistration} or {@link OptionsPanelController.SubRegistration}. * * @author thomas */ public abstract class DefaultConfigController extends OptionsPanelController { private PreferencesPanel panel; private BindingContext bindingContext; /** * Create a {@link PropertySet} object instance that holds all parameters. * Clients that want to maintain properties need to overwrite this method. * * @return An instance of {@link PropertySet}, holding all configuration parameters. * * @see #createPropertySet(Object) */ protected abstract PropertySet createPropertySet(); /** * Create a panel that allows the user to set the parameters in the given {@link BindingContext}. Clients that want * to create their own panel representation on the given properties need to overwrite this method. * * @param context The {@link BindingContext} for the panel. * * @return A JPanel instance for the given {@link BindingContext}, never {@code null}. */ protected JPanel createPanel(BindingContext context) { Assert.state(isInitialised()); return new PreferencesPanel(null, bindingContext).getComponent(); } /** * Configure the passed binding context. This is intended to be used to create {@code enablements} in order to * add dependencies between property states. The default implementation does nothing. * * @param context The {@link BindingContext} to configure. * * @see com.bc.ceres.swing.binding.Enablement * @see com.bc.ceres.swing.binding.BindingContext#bindEnabledState(String, boolean, com.bc.ceres.swing.binding.Enablement.Condition) * @see com.bc.ceres.swing.binding.BindingContext#bindEnabledState(String, boolean, String, Object) */ protected void configure(BindingContext context) { } protected BindingContext getBindingContext() { return bindingContext; } /** * Creates a PropertyContainer for any bean. The bean parameters need to be annotated with {@link Preference}. * * @param bean a bean with fields annoted with {@link Preference}. * * @return an instance of {@link PropertyContainer}, fit for passing within overridden * {@link #createPropertySet()}. */ protected final PropertyContainer createPropertySet(Object bean) { return PropertyContainer.createObjectBacked(bean, field -> { Class<Preference> annotationClass = Preference.class; Preference annotation = field.getAnnotation(annotationClass); if (annotation == null) { throw new IllegalStateException("Field '" + field.getName() + "' must be annotated with '" + annotationClass.getSimpleName() + "'."); } String label = annotation.label(); String key = annotation.key(); String[] valueSet = annotation.valueSet(); String valueRange = annotation.interval(); String description = annotation.description(); Validator validator = createValidator(annotation.validatorClass()); Assert.state(StringUtils.isNotNullAndNotEmpty(label), "Label of field '" + field.getName() + "' must not be null or empty."); Assert.state(StringUtils.isNotNullAndNotEmpty(key), "Key of field '" + field.getName() + "' must not be null or empty."); boolean isDeprecated = field.getAnnotation(Deprecated.class) != null; PropertyDescriptor valueDescriptor = new PropertyDescriptor(key, field.getType()); valueDescriptor.setDeprecated(isDeprecated); valueDescriptor.setAttribute("key", key); valueDescriptor.setAttribute("displayName", label); valueDescriptor.setAttribute("configName", annotation.config()); valueDescriptor.setAttribute("propertyValidator", validator); valueDescriptor.setDescription(description); if (valueSet.length > 0) { valueDescriptor.setValueSet(new ValueSet(valueSet)); } if (StringUtils.isNotNullAndNotEmpty(valueRange)) { valueDescriptor.setValueRange(ValueRange.parseValueRange(valueRange)); } return valueDescriptor; }); } @Override public void update() { if (isInitialised()) { for (Property property : bindingContext.getPropertySet().getProperties()) { String key = property.getDescriptor().getAttribute("key").toString(); String preferencesValue = getPreferences(property.getDescriptor()).get(key, null); if (preferencesValue != null) { try { property.setValueFromText(preferencesValue); SystemUtils.LOG.fine(String.format("Bean property value change: %s = %s", property.getName(), property.getValueAsText())); } catch (ValidationException e) { SystemUtils.LOG.severe("Failed to set bean value from preferences: " + e.getMessage()); } } } } } @Override public void applyChanges() { if (isInitialised()) { HashSet<Preferences> set = new HashSet<>(); for (Property property : bindingContext.getPropertySet().getProperties()) { String key = property.getDescriptor().getAttribute("key").toString(); String value = property.getValueAsText(); Preferences preferences = getPreferences(property.getDescriptor()); preferences.put(key, value); set.add(preferences); SystemUtils.LOG.fine(String.format("Preferences value change: %s = %s", key, preferences.get(key, null))); } for (Preferences preferences : set) { try { preferences.flush(); } catch (BackingStoreException e) { SnapApp.getDefault().handleError("Failed to store user preferences.", e); } } setChanged(false); } } @Override public void cancel() { if (isInitialised()) { setChanged(false); } } @Override public boolean isValid() { if (!isInitialised()) { return false; } for (Property property : bindingContext.getPropertySet().getProperties()) { Validator validator = (Validator) property.getDescriptor().getAttribute("propertyValidator"); try { validator.validateValue(property, property.getValue()); } catch (ValidationException e) { return false; } } return true; } protected void setChanged(boolean changed) { panel.setChanged(changed); } @Override public boolean isChanged() { return isInitialised() && panel.isChanged(); } @Override public JComponent getComponent(Lookup lookup) { if (!isInitialised()) { initialize(); } return panel.getComponent(); } @Override public void addPropertyChangeListener(PropertyChangeListener propertyChangeListener) { if (bindingContext != null) { bindingContext.addPropertyChangeListener(propertyChangeListener); } } @Override public void removePropertyChangeListener(PropertyChangeListener propertyChangeListener) { if (bindingContext != null) { bindingContext.removePropertyChangeListener(propertyChangeListener); } } protected boolean isInitialised() { return bindingContext != null; } private void initialize() { bindingContext = new BindingContext(createPropertySet()); panel = new PreferencesPanel(createPanel(bindingContext), bindingContext); panel.getComponent(); // trigger component initialisation configure(bindingContext); } private Preferences getPreferences(PropertyDescriptor propertyDescriptor) { Object configNameValue = propertyDescriptor.getAttribute("configName"); String configName = configNameValue != null ? configNameValue.toString().trim() : null; if (configName == null || configName.isEmpty()) { return SnapApp.getDefault().getPreferences(); } return Config.instance(configName).load().preferences(); } private Validator createValidator(Class<? extends Validator> validatorClass) { Validator validator; try { validator = validatorClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalStateException(e); } return validator; } }
10,716
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Preference.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/Preference.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; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.Validator; import org.esa.snap.runtime.Config; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Annotation for user preferences. Use is mandatory if preferences are supplied via a bean, see * {@link DefaultConfigController#createPropertySet()} and * {@link DefaultConfigController#createPropertySet(Object)}. * * @see DefaultConfigController * * @author thomas */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD}) public @interface Preference { /** * @return The label of the property. Must not be empty. */ String label(); /** * @return The property key. Must not be empty. */ String key(); /** * @return The configuration name. If not set, the NetBeans preferences are used, otherwise preferences from a * named configuration are used ({@link Config#preferences() Config.instance(<i>config</i>).preferences()}). */ String config() default ""; /** * @return The set of allowed values. */ String[] valueSet() default {}; /** * Gets the valid interval for numeric parameters, e.g. {@code "[10,20)"}: in the range 10 (inclusive) to 20 (exclusive). * * @return The valid interval. Defaults to empty string (= not set). */ String interval() default ""; /** * Description text (used for tooltips). */ String description() default ""; /** * @return The validator class. */ Class<? extends Validator> validatorClass() default NullValidator.class; class NullValidator implements Validator { @Override public void validateValue(Property property, Object value) throws ValidationException { // ok } } }
2,760
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MaskLayerController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/MaskLayerController.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.core.datamodel.Mask; 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 mask layer preferences. Sub-panel of the "Layer"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#Options_DisplayName_LayerMask", keywords = "#Options_Keywords_LayerMask", keywordsCategory = "Layer", id = "LayerMask", position = 6) @org.openide.util.NbBundle.Messages({ "Options_DisplayName_LayerMask=New Masks", "Options_Keywords_LayerMask=layer, mask" }) public final class MaskLayerController extends DefaultConfigController { /** * Preferences key for the mask overlay color */ public static final String PREFERENCE_KEY_MASK_COLOR = "mask.color"; /** * Preferences key for the mask overlay transparency */ public static final String PREFERENCE_KEY_MASK_TRANSPARENCY = "mask.transparency"; protected PropertySet createPropertySet() { return createPropertySet(new MaskBean()); } @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 maskOverlayColor = context.getPropertySet().getProperty(PREFERENCE_KEY_MASK_COLOR); Property maskOverlayTransparency = context.getPropertySet().getProperty(PREFERENCE_KEY_MASK_TRANSPARENCY); JComponent[] maskOverlayColorComponents = PreferenceUtils.createColorComponents(maskOverlayColor); JComponent[] maskOverlayTransparencyComponents = registry.findPropertyEditor(maskOverlayTransparency.getDescriptor()).createComponents(maskOverlayTransparency.getDescriptor(), context); pageUI.add(maskOverlayColorComponents[0]); pageUI.add(maskOverlayColorComponents[1]); pageUI.add(maskOverlayTransparencyComponents[1]); pageUI.add(maskOverlayTransparencyComponents[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-masks"); } @SuppressWarnings("UnusedDeclaration") static class MaskBean { @SuppressWarnings("AccessStaticViaInstance") @Preference(label = "Default mask overlay colour", key = PREFERENCE_KEY_MASK_COLOR) Color maskOverlayColor = Mask.ImageType.DEFAULT_COLOR.RED; @Preference(label = "Default mask overlay transparency", key = PREFERENCE_KEY_MASK_TRANSPARENCY, interval = "[0.0,1.0]") double maskOverlayTransparency = Mask.ImageType.DEFAULT_TRANSPARENCY; } }
4,566
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/general/package-info.java
/** * This package contains product preferences handling. * * @author thomas */ @OptionsPanelController.ContainerRegistration( id = "GeneralPreferences", categoryName = "#OptionsCategory_Name_General", iconBase = "org/esa/snap/rcp/icons/generalOptions1.png", keywords = "#OptionsCategory_Keywords_General", keywordsCategory = "#OptionsCategory_Keywords_Category_General", position = 1) @org.openide.util.NbBundle.Messages({ "OptionsCategory_Name_General=General", "OptionsCategory_Keywords_General=general", "OptionsCategory_Keywords_Category_General=general" }) package org.esa.snap.rcp.preferences.general; import org.netbeans.spi.options.OptionsPanelController;
741
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
RgbController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/RgbController.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.PropertyContainer; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.binding.BindingContext; import org.esa.snap.core.util.DefaultPropertyMap; import org.esa.snap.rcp.preferences.DefaultConfigController; import org.esa.snap.ui.RGBImageProfilePane; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import javax.swing.JPanel; /** * The controller for RGB product profile preferences. Sub-level panel to the "Product Profile"-panel. * * @author thomas */ @org.openide.util.NbBundle.Messages({ "Options_DisplayName_RGB=RGB-Image Profiles", "Options_Keywords_RGB=RGB, profile" }) @OptionsPanelController.SubRegistration( location = "GeneralPreferences", displayName = "#Options_DisplayName_RGB", keywords = "#Options_Keywords_RGB", keywordsCategory = "RGB", id = "rgb-image-profiles", position = 4 ) public final class RgbController extends DefaultConfigController { @Override protected PropertySet createPropertySet() { return new PropertyContainer(); } @Override protected JPanel createPanel(BindingContext context) { return new RGBImageProfilePane(new DefaultPropertyMap()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-rgb"); } }
2,143
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorManipulationController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/ColorManipulationController.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.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.datamodel.ColorManipulationDefaults; 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 general layer preferences. Sub-panel of the "Layer"-panel. * * @author Daniel Knowles (NASA) */ @org.openide.util.NbBundle.Messages({ "Options_DisplayName_ColorManipulation=" + ColorManipulationDefaults.TOOLNAME_COLOR_MANIPULATION, "Options_Keywords_ColorManipulation=layer, general" }) @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#Options_DisplayName_ColorManipulation", keywords = "#Options_Keywords_ColorManipulation", keywordsCategory = "color, layer", id = "colorManipulationController", position = 3) public final class ColorManipulationController extends DefaultConfigController { Property restoreDefaults; boolean propertyValueChangeEventsEnabled = true; Enablement enablementGeneralPalette; Enablement enablementGeneralRange; Enablement enablementGeneralLog; protected PropertySet createPropertySet() { return createPropertySet(new GeneralLayerBean()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("colorManipulationPreferences"); } @Override protected JPanel createPanel(BindingContext context) { initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_KEY, ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_GENERAL_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_KEY, ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_KEY, ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_KEY, ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_GENERAL_LOG_KEY, ColorManipulationDefaults.PROPERTY_GENERAL_LOG_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_RESTORE_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_LOG_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_LOG_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_KEY, ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_1_SIGMA_BUTTON_KEY, ColorManipulationDefaults.PROPERTY_1_SIGMA_BUTTON_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_2_SIGMA_BUTTON_KEY, ColorManipulationDefaults.PROPERTY_2_SIGMA_BUTTON_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_3_SIGMA_BUTTON_KEY, ColorManipulationDefaults.PROPERTY_3_SIGMA_BUTTON_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_95_PERCENT_BUTTON_KEY, ColorManipulationDefaults.PROPERTY_95_PERCENT_BUTTON_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_100_PERCENT_BUTTON_KEY, ColorManipulationDefaults.PROPERTY_100_PERCENT_BUTTON_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_SELECTOR_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_VERBOSE_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_VERBOSE_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_SORT_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_SORT_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_CATEGORIZE_DISPLAY_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_CATEGORIZE_DISPLAY_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SCHEME_SHOW_DISABLED_KEY, ColorManipulationDefaults.PROPERTY_SCHEME_SHOW_DISABLED_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SLIDERS_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SLIDERS_ZOOM_IN_KEY, ColorManipulationDefaults.PROPERTY_SLIDERS_ZOOM_IN_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_KEY, ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_DEFAULT); // initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_BUTTONS_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_ZOOM_VERTICAL_BUTTONS_KEY, ColorManipulationDefaults.PROPERTY_ZOOM_VERTICAL_BUTTONS_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_INFORMATION_BUTTON_KEY, ColorManipulationDefaults.PROPERTY_INFORMATION_BUTTON_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_SECTION_KEY, true); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_KEY, ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_DEFAULT); initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_KEY, ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_DEFAULT); restoreDefaults = initPropertyDefaults(context, ColorManipulationDefaults.PROPERTY_RESTORE_DEFAULTS_NAME, ColorManipulationDefaults.PROPERTY_RESTORE_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) { configureGeneralCustomEnablement(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(ColorManipulationDefaults.PROPERTY_RESTORE_DEFAULTS_NAME, false); } } /** * 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(ColorManipulationDefaults.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; } /** * Configure enablement of the components tied to PROPERTY_GENERAL_CUSTOM_KEY * * @param context * @author Daniel Knowles */ private void configureGeneralCustomEnablement(BindingContext context) { enablementGeneralPalette = context.bindEnabledState(ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_KEY, true, ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_KEY, true); enablementGeneralRange = context.bindEnabledState(ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_KEY, true, ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_KEY, true); enablementGeneralLog = context.bindEnabledState(ColorManipulationDefaults.PROPERTY_GENERAL_LOG_KEY, true, ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_KEY, true); // handle it the first time so bound properties get properly enabled // handleGeneralCustom(); enablementGeneralPalette.apply(); enablementGeneralRange.apply(); enablementGeneralLog.apply(); } /** * Handles enablement of the components * * @author Daniel Knowles */ private void handleGeneralCustom() { enablementGeneralPalette.apply(); enablementGeneralRange.apply(); enablementGeneralLog.apply(); } @SuppressWarnings("UnusedDeclaration") static class GeneralLayerBean { // Default Palettes @Preference(label = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_SECTION_TOOLTIP) boolean defaultPaletteSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_LABEL, key = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_KEY, description = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_TOOLTIP) String grayScaleCpd = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_GRAY_SCALE_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_LABEL, key = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_KEY, description = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_TOOLTIP) String standardColorCpd = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_STANDARD_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_LABEL, key = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_KEY, description = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_TOOLTIP) String colorBlindCpd = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_UNIVERSAL_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_LABEL, key = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_KEY, description = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_TOOLTIP) String otherCpd = ColorManipulationDefaults.PROPERTY_PALETTE_DEFAULT_ANOMALIES_DEFAULT; // General Options @Preference(label = ColorManipulationDefaults.PROPERTY_GENERAL_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_GENERAL_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_GENERAL_SECTION_TOOLTIP) boolean generalBehaviorSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_LABEL, key = ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_KEY, description = ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_TOOLTIP) boolean generalCustomSchemes = ColorManipulationDefaults.PROPERTY_GENERAL_CUSTOM_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_LABEL, key = ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_KEY, description = ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_TOOLTIP, valueSet = {ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_OPTION1, ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_OPTION2, ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_OPTION3, ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_OPTION4}) String generalCpd = ColorManipulationDefaults.PROPERTY_GENERAL_PALETTE_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_LABEL, key = ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_KEY, description = ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_TOOLTIP, valueSet = {ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_OPTION1, ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_OPTION2}) String generalRange = ColorManipulationDefaults.PROPERTY_GENERAL_RANGE_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_GENERAL_LOG_LABEL, key = ColorManipulationDefaults.PROPERTY_GENERAL_LOG_KEY, description = ColorManipulationDefaults.PROPERTY_GENERAL_LOG_TOOLTIP, valueSet = {ColorManipulationDefaults.PROPERTY_GENERAL_LOG_OPTION1, ColorManipulationDefaults.PROPERTY_GENERAL_LOG_OPTION2, ColorManipulationDefaults.PROPERTY_GENERAL_LOG_OPTION3}) String generalLog = ColorManipulationDefaults.PROPERTY_GENERAL_LOG_DEFAULT; // Scheme Options @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_SECTION_TOOLTIP) boolean schemeOptionsSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_TOOLTIP) boolean autoApplySchemes = ColorManipulationDefaults.PROPERTY_SCHEME_AUTO_APPLY_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_TOOLTIP, valueSet = {ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_OPTION1, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_OPTION2, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_OPTION3, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_OPTION4, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_OPTION5, ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_OPTION6}) String schemeCpd = ColorManipulationDefaults.PROPERTY_SCHEME_PALETTE_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_TOOLTIP, valueSet = {ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_OPTION1, ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_OPTION2, ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_OPTION3}) String schemeRange = ColorManipulationDefaults.PROPERTY_SCHEME_RANGE_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_LOG_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_LOG_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_LOG_TOOLTIP, valueSet = {ColorManipulationDefaults.PROPERTY_SCHEME_LOG_OPTION1, ColorManipulationDefaults.PROPERTY_SCHEME_LOG_OPTION2, ColorManipulationDefaults.PROPERTY_SCHEME_LOG_OPTION3, ColorManipulationDefaults.PROPERTY_SCHEME_LOG_OPTION4}) String schemeLog = ColorManipulationDefaults.PROPERTY_SCHEME_LOG_DEFAULT; // Range Percentile Options @Preference(label = ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_SECTION_TOOLTIP) boolean rangePercentileSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_LABEL, key = ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_KEY, description = ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_TOOLTIP, interval = "[0.10,100.0]") double rangePercentile = ColorManipulationDefaults.PROPERTY_RANGE_PERCENTILE_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_1_SIGMA_BUTTON_LABEL, key = ColorManipulationDefaults.PROPERTY_1_SIGMA_BUTTON_KEY, description = ColorManipulationDefaults.PROPERTY_1_SIGMA_BUTTON_TOOLTIP) boolean range1Sigma = ColorManipulationDefaults.PROPERTY_1_SIGMA_BUTTON_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_2_SIGMA_BUTTON_LABEL, key = ColorManipulationDefaults.PROPERTY_2_SIGMA_BUTTON_KEY, description = ColorManipulationDefaults.PROPERTY_2_SIGMA_BUTTON_TOOLTIP) boolean range2Sigma = ColorManipulationDefaults.PROPERTY_2_SIGMA_BUTTON_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_3_SIGMA_BUTTON_LABEL, key = ColorManipulationDefaults.PROPERTY_3_SIGMA_BUTTON_KEY, description = ColorManipulationDefaults.PROPERTY_3_SIGMA_BUTTON_TOOLTIP) boolean range3Sigma = ColorManipulationDefaults.PROPERTY_3_SIGMA_BUTTON_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_95_PERCENT_BUTTON_LABEL, key = ColorManipulationDefaults.PROPERTY_95_PERCENT_BUTTON_KEY, description = ColorManipulationDefaults.PROPERTY_95_PERCENT_BUTTON_TOOLTIP) boolean range95 = ColorManipulationDefaults.PROPERTY_95_PERCENT_BUTTON_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_100_PERCENT_BUTTON_LABEL, key = ColorManipulationDefaults.PROPERTY_100_PERCENT_BUTTON_KEY, description = ColorManipulationDefaults.PROPERTY_100_PERCENT_BUTTON_TOOLTIP) boolean range100 = ColorManipulationDefaults.PROPERTY_100_PERCENT_BUTTON_DEFAULT; // Scheme Selector Options @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_SELECTOR_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_SELECTOR_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_SELECTOR_SECTION_TOOLTIP) boolean schemeSelectorSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_VERBOSE_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_VERBOSE_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_VERBOSE_TOOLTIP) boolean schemeSelectorVerbose = ColorManipulationDefaults.PROPERTY_SCHEME_VERBOSE_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_SORT_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_SORT_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_SORT_TOOLTIP) boolean schemeSelectorSort = ColorManipulationDefaults.PROPERTY_SCHEME_SORT_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_CATEGORIZE_DISPLAY_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_CATEGORIZE_DISPLAY_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_CATEGORIZE_DISPLAY_TOOLTIP) boolean schemeSelectorSplit = ColorManipulationDefaults.PROPERTY_SCHEME_CATEGORIZE_DISPLAY_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_SCHEME_SHOW_DISABLED_LABEL, key = ColorManipulationDefaults.PROPERTY_SCHEME_SHOW_DISABLED_KEY, description = ColorManipulationDefaults.PROPERTY_SCHEME_SHOW_DISABLED_TOOLTIP) boolean schemeSelectorShowDisabled = ColorManipulationDefaults.PROPERTY_SCHEME_SHOW_DISABLED_DEFAULT; // Slider and Range Options @Preference(label = ColorManipulationDefaults.PROPERTY_SLIDERS_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_SLIDERS_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_SLIDERS_SECTION_TOOLTIP) boolean sliderOptionsSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_SLIDERS_ZOOM_IN_LABEL, key = ColorManipulationDefaults.PROPERTY_SLIDERS_ZOOM_IN_KEY, description = ColorManipulationDefaults.PROPERTY_SLIDERS_ZOOM_IN_TOOLTIP) boolean sliderZoom = ColorManipulationDefaults.PROPERTY_SLIDERS_ZOOM_IN_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_LABEL, key = ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_KEY, description = ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_TOOLTIP) boolean slidersShowExtraInfo = ColorManipulationDefaults.PROPERTY_SLIDERS_SHOW_INFORMATION_DEFAULT; // // // // Button Options // // @Preference(label = ColorManipulationDefaults.PROPERTY_BUTTONS_SECTION_LABEL, // key = ColorManipulationDefaults.PROPERTY_BUTTONS_SECTION_KEY, // description = ColorManipulationDefaults.PROPERTY_BUTTONS_SECTION_TOOLTIP) // boolean buttonsSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_ZOOM_VERTICAL_BUTTONS_LABEL, key = ColorManipulationDefaults.PROPERTY_ZOOM_VERTICAL_BUTTONS_KEY, description = ColorManipulationDefaults.PROPERTY_ZOOM_VERTICAL_BUTTONS_TOOLTIP) boolean sliderZoomVertical = ColorManipulationDefaults.PROPERTY_ZOOM_VERTICAL_BUTTONS_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_INFORMATION_BUTTON_LABEL, key = ColorManipulationDefaults.PROPERTY_INFORMATION_BUTTON_KEY, description = ColorManipulationDefaults.PROPERTY_INFORMATION_BUTTON_TOOLTIP) boolean slidersShowExtraInfoButton = ColorManipulationDefaults.PROPERTY_INFORMATION_BUTTON_DEFAULT; // RGB Options @Preference(label = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_SECTION_TOOLTIP) boolean rgbOptionsSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_LABEL, key = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_KEY, description = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_TOOLTIP) double rgbOptionsMin = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MIN_DEFAULT; @Preference(label = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_LABEL, key = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_KEY, description = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_TOOLTIP) double rgbOptionsMax = ColorManipulationDefaults.PROPERTY_RGB_OPTIONS_MAX_DEFAULT; // Restore Defaults @Preference(label = ColorManipulationDefaults.PROPERTY_RESTORE_SECTION_LABEL, key = ColorManipulationDefaults.PROPERTY_RESTORE_SECTION_KEY, description = ColorManipulationDefaults.PROPERTY_RESTORE_SECTION_TOOLTIP) boolean restoreDefaultsSection = true; @Preference(label = ColorManipulationDefaults.PROPERTY_RESTORE_DEFAULTS_LABEL, key = ColorManipulationDefaults.PROPERTY_RESTORE_DEFAULTS_NAME, description = ColorManipulationDefaults.PROPERTY_RESTORE_DEFAULTS_TOOLTIP) boolean restoreDefaults = ColorManipulationDefaults.PROPERTY_RESTORE_DEFAULTS_DEFAULT; } }
29,980
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
QuicklookOptionsController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/QuicklookOptionsController.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.preferences.general; import com.bc.ceres.binding.PropertySet; import org.esa.snap.core.datamodel.quicklooks.QuicklookGenerator; 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; /** * Panel for quicklook options. Sub-level panel to the General-panel. * * @author Luis Veci */ @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#Options_DisplayName_QuicklookOptions", keywords = "#Options_Keywords_QuicklookOptions", keywordsCategory = "Quicklook", id = "QuicklookOptions", position = 6) @org.openide.util.NbBundle.Messages({ "Options_DisplayName_QuicklookOptions=Quicklooks", "Options_Keywords_QuicklookOptions=Quicklook" }) public final class QuicklookOptionsController extends DefaultConfigController { protected PropertySet createPropertySet() { return createPropertySet(new QuicklookOptionsBean()); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-quicklook"); } @SuppressWarnings("UnusedDeclaration") static class QuicklookOptionsBean { @Preference(label = "Save quicklooks with product where possible", config = "snap", key = QuicklookGenerator.PREFERENCE_KEY_QUICKLOOKS_SAVE_WITH_PRODUCT) boolean saveWithProduct = QuicklookGenerator.DEFAULT_VALUE_QUICKLOOKS_SAVE_WITH_PRODUCT; @Preference(label = "Max quicklook width in pixels", config = "snap", key = QuicklookGenerator.PREFERENCE_KEY_QUICKLOOKS_MAX_WIDTH) int maxWidth = QuicklookGenerator.DEFAULT_VALUE_QUICKLOOKS_MAX_WIDTH; } }
2,524
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
UiBehaviorController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-rcp/src/main/java/org/esa/snap/rcp/preferences/general/UiBehaviorController.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.binding.ValidationException; 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.SnapApp; import org.esa.snap.rcp.pixelinfo.PixelInfoView; 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.rcp.util.Dialogs; 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.Insets; import java.util.prefs.BackingStoreException; import java.util.prefs.Preferences; /** * Preferences tab for handling the UI behavior preferences. Sub-level panel to the "Miscellaneous"-panel. * * @author thomas */ @OptionsPanelController.SubRegistration(location = "GeneralPreferences", displayName = "#AdvancedOption_DisplayName_UiBehavior", keywords = "#AdvancedOption_Keywords_UiBehavior", keywordsCategory = "Advanced, UiBehavior", id = "UiBehavior", position = 1) @org.openide.util.NbBundle.Messages({ "AdvancedOption_DisplayName_UiBehavior=UI Behaviour", "AdvancedOption_Keywords_UiBehavior=UI, behavior" }) public final class UiBehaviorController extends DefaultConfigController { /** * Preferences key for automatically showing navigation */ public static final String PREFERENCE_KEY_AUTO_SHOW_NAVIGATION = "autoshownavigation.enabled"; /** * Preferences key for automatically showing new bands */ public static final String PREFERENCE_KEY_AUTO_SHOW_NEW_BANDS = "autoshowbands.enabled"; /** * Preferences key to set the maximum number of file in the list to reopen. */ public static final String PREFERENCE_KEY_LIST_FILES_TO_REOPEN = "filesToReopen"; private static final String PREFERENCE_KEY_SHOW_SUPPRESSED = "showSuppressedDialogsAgain"; private static final String PREFERENCE_KEY_SOUND_BEEP = "playSoundBeepAfterProcess"; @Override public void applyChanges() { if (isInitialised()) { final BindingContext bindingContext = getBindingContext(); final Property showSuppressedProperty = bindingContext.getPropertySet().getProperty(PREFERENCE_KEY_SHOW_SUPPRESSED); if (Boolean.parseBoolean(showSuppressedProperty.getValueAsText())) { final Preferences preferences = SnapApp.getDefault().getPreferences(); try { final String[] childrenNames = preferences.keys(); for (String childrenName : childrenNames) { if (childrenName.endsWith(Dialogs.PREF_KEY_SUFFIX_DONTSHOW)) { preferences.putBoolean(childrenName, false); } if (childrenName.endsWith(Dialogs.PREF_KEY_SUFFIX_DECISION)) { preferences.remove(childrenName); } } showSuppressedProperty.setValue(Boolean.FALSE); } catch (BackingStoreException | ValidationException e) { SnapApp.getDefault().handleError("Failure while resetting suppressed dialogs.", e); } } } super.applyChanges(); } @Override public void cancel() { if (isInitialised()) { final BindingContext bindingContext = getBindingContext(); final Property showSuppressedProperty = bindingContext.getPropertySet().getProperty(PREFERENCE_KEY_SHOW_SUPPRESSED); try { showSuppressedProperty.setValue(Boolean.FALSE); } catch (ValidationException e) { // ignore } } super.cancel(); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("options-uibehavior"); } static class UiBehaviorBean { @Preference(label = "Show navigation window when image views are opened", key = PREFERENCE_KEY_AUTO_SHOW_NAVIGATION) boolean autoShowNavigation = true; @Preference(label = "Open image view for new (virtual) bands", key = PREFERENCE_KEY_AUTO_SHOW_NEW_BANDS) boolean autoShowNewBands = true; @Preference(label = "Show only pixel values of loaded or displayed bands", key = PixelInfoView.PREFERENCE_KEY_SHOW_ONLY_DISPLAYED_BAND_PIXEL_VALUES) boolean showOnlyLoadedOrDisplayedBandPixels = PixelInfoView.PREFERENCE_DEFAULT_SHOW_DISPLAYED_BAND_PIXEL_VALUES; @Preference(label = "Maximum recent file list", key = PREFERENCE_KEY_LIST_FILES_TO_REOPEN, interval = "[1,20]") int fileReopen = 10; @Preference(label = "Show suppressed message dialogs again", key = PREFERENCE_KEY_SHOW_SUPPRESSED) boolean showSuppressedDialogsAgain = false; } protected PropertySet createPropertySet() { return createPropertySet(new UiBehaviorBean()); } @Override protected JPanel createPanel(BindingContext context) { TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTablePadding(new Insets(4, 10, 0, 0)); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setColumnWeightX(0, 1.0); JPanel pageUI = new JPanel(tableLayout); PropertyEditorRegistry registry = PropertyEditorRegistry.getInstance(); Property autoShowNavigation = context.getPropertySet().getProperty(PREFERENCE_KEY_AUTO_SHOW_NAVIGATION); Property showNewBands = context.getPropertySet().getProperty(PREFERENCE_KEY_AUTO_SHOW_NEW_BANDS); Property showOnlyDisplayed = context.getPropertySet().getProperty(PixelInfoView.PREFERENCE_KEY_SHOW_ONLY_DISPLAYED_BAND_PIXEL_VALUES); Property listOfFilesToReopen = context.getPropertySet().getProperty(PREFERENCE_KEY_LIST_FILES_TO_REOPEN); Property showSuppressedAgain = context.getPropertySet().getProperty(PREFERENCE_KEY_SHOW_SUPPRESSED); JComponent[] autoShowNavigationComponents = registry.findPropertyEditor(autoShowNavigation.getDescriptor()).createComponents(autoShowNavigation.getDescriptor(), context); JComponent[] showNewBandsComponents = registry.findPropertyEditor(showNewBands.getDescriptor()).createComponents(showNewBands.getDescriptor(), context); JComponent[] showOnlyDisplayedComponents = registry.findPropertyEditor(showOnlyDisplayed.getDescriptor()).createComponents(showOnlyDisplayed.getDescriptor(), context); JComponent[] listOfFilesToReopenComponent = registry.findPropertyEditor(listOfFilesToReopen.getDescriptor()).createComponents(listOfFilesToReopen.getDescriptor(), context); JComponent[] showSuppressedAgainComponent = registry.findPropertyEditor(showSuppressedAgain.getDescriptor()).createComponents(showSuppressedAgain.getDescriptor(), context); pageUI.add(PreferenceUtils.createTitleLabel("Display Settings")); pageUI.add(autoShowNavigationComponents[0]); pageUI.add(showNewBandsComponents[0]); pageUI.add(showOnlyDisplayedComponents[0]); pageUI.add(tableLayout.createHorizontalSpacer()); pageUI.add(PreferenceUtils.createTitleLabel("Other Settings")); pageUI.add(showSuppressedAgainComponent[0]); // Adding the number of file that can be reopen TableLayout layout = new TableLayout(2); JPanel panel = new JPanel(layout); layout.setTablePadding(new Insets(1, 10, 0, 0)); panel.add(listOfFilesToReopenComponent[1]); panel.add(listOfFilesToReopenComponent[0]); tableLayout.setTableFill(TableLayout.Fill.VERTICAL); pageUI.add(panel); pageUI.add(tableLayout.createVerticalSpacer()); JPanel parent = new JPanel(new BorderLayout()); parent.add(pageUI, BorderLayout.CENTER); parent.add(Box.createHorizontalStrut(100), BorderLayout.EAST); return parent; } }
9,091
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z