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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ColorCodes.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorCodes.java | package org.esa.snap.ui.color;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.util.io.FileUtils;
import java.awt.Color;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Color codes according to <a href="http://www.w3schools.com/html/html_colornames.asp">W3C HTML Color Names</a>.
*
* @author Norman Fomferra
* @since SNAP 2.0
*/
public class ColorCodes {
private List<String> nameList;
private Map<Color, String> nameMap;
private Map<String, Color> colorMap;
static final ColorCodes instance = new ColorCodes();
private ColorCodes() {
nameList = new ArrayList<>(512);
nameMap = new HashMap<>(512);
colorMap = new HashMap<>(512);
try {
Path path = FileUtils.getPathFromURI(ColorComboBox.class.getResource("color-codes.txt").toURI());
List<String> lines = Files.readAllLines(path);
for (String line : lines) {
int i = line.indexOf('\t');
Color color = Color.decode(line.substring(0, i).trim());
String name = line.substring(i).trim();
//System.out.println("color = " + color + ", name = " + name);
Assert.state(!nameMap.containsKey(color), String.format("color '%s' already added", color));
Assert.state(!colorMap.containsKey(name), String.format("color '%s' already added", name));
nameList.add(name);
nameMap.put(color, name);
colorMap.put(name, color);
}
} catch (URISyntaxException | IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> getNames() {
return Collections.unmodifiableList(instance.nameList);
}
public static int indexOf(String name) {
return instance.nameList.indexOf(name);
}
public static int indexOf(Color color) {
String name = getName(color);
if (name != null) {
return indexOf(name);
}
return -1;
}
public static Color getColor(String name) {
return instance.colorMap.get(name);
}
public static String getName(Color color) {
return instance.nameMap.get(color);
}
public static Color getColor(int index) {
return getColor(getName(index));
}
public static String getName(int index) {
return instance.nameList.get(index);
}
}
| 2,629 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorComboBoxAdapter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorComboBoxAdapter.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.ui.color;
import com.bc.ceres.swing.binding.ComponentAdapter;
import javax.swing.JComponent;
import java.awt.Color;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* A binding for the SNAP {@link ColorComboBox}.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
* @since BEAM 4.2
*/
public class ColorComboBoxAdapter extends ComponentAdapter implements PropertyChangeListener {
private ColorComboBox colorComboBox;
public ColorComboBoxAdapter(ColorComboBox colorComboBox) {
this.colorComboBox = colorComboBox;
}
@Override
public JComponent[] getComponents() {
return new JComponent[]{colorComboBox};
}
@Override
public void bindComponents() {
colorComboBox.addPropertyChangeListener(this);
}
@Override
public void unbindComponents() {
colorComboBox.removePropertyChangeListener(this);
}
@Override
public void adjustComponents() {
final Color color = (Color) getBinding().getPropertyValue();
colorComboBox.setSelectedColor(color);
}
private void adjustPropertyValue() {
final Color color = colorComboBox.getSelectedColor();
getBinding().setPropertyValue(color);
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
adjustPropertyValue();
}
}
| 2,109 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorComboBox.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorComboBox.java | package org.esa.snap.ui.color;
import com.jidesoft.popup.JidePopup;
import javax.swing.JComponent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* A combo box for color values.
*
* @author Norman Fomferra
* @since SNAP 2.0
*/
public class ColorComboBox extends JComponent {
public static final String SELECTED_COLOR_PROPERTY = "selectedColor";
public static final Color TRANSPARENCY = new Color(0, 0, 0, 0);
private JidePopup popupWindow;
private ColorLabel colorLabel;
private Color selectedColor;
private ColorChooserPanelFactory colorChooserPanelFactory;
public ColorComboBox() {
this(Color.WHITE);
}
public ColorComboBox(Color color) {
selectedColor = color;
colorLabel = new ColorLabel(selectedColor);
colorLabel.setPreferredSize(new Dimension(16, 16));
colorLabel.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
requestFocusInWindow();
showPopupWindow();
}
});
setPreferredSize(new Dimension(60, 20));
setLayout(new BorderLayout());
add(colorLabel, BorderLayout.CENTER);
setFocusable(true);
}
public ColorChooserPanelFactory getColorChooserPanelFactory() {
return colorChooserPanelFactory;
}
public void setColorChooserPanelFactory(ColorChooserPanelFactory colorChooserPanelFactory) {
this.colorChooserPanelFactory = colorChooserPanelFactory;
}
public Color getSelectedColor() {
return selectedColor;
}
public void setSelectedColor(Color selectedColor) {
Color oldValue = this.selectedColor;
this.selectedColor = selectedColor;
colorLabel.setColor(selectedColor);
firePropertyChange(SELECTED_COLOR_PROPERTY, oldValue, this.selectedColor);
}
private ColorChooserPanel createColorChooserPanel() {
if (colorChooserPanelFactory != null) {
return colorChooserPanelFactory.create(getSelectedColor());
}
return new ColorChooserPanel(getSelectedColor());
}
private void showPopupWindow() {
if (popupWindow != null && popupWindow.isShowing()) {
closePopupWindow();
return;
}
Point location = getLocationOnScreen();
location.y += getHeight();
ColorChooserPanel colorChooserPanel = createColorChooserPanel();
colorChooserPanel.addPropertyChangeListener(ColorChooserPanel.SELECTED_COLOR_PROPERTY, evt -> {
setSelectedColor(colorChooserPanel.getSelectedColor());
closePopupWindow();
});
popupWindow = new JidePopup();
popupWindow.setOwner(this);
popupWindow.getContentPane().add(colorChooserPanel);
popupWindow.setDefaultFocusComponent(colorChooserPanel);
popupWindow.setMovable(false);
popupWindow.setAttachable(false);
popupWindow.showPopup(location.x, location.y);
}
protected void closePopupWindow() {
if (popupWindow != null) {
popupWindow.hidePopupImmediately();
popupWindow = null;
}
}
}
| 3,322 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorChooserPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorChooserPanel.java | package org.esa.snap.ui.color;
import org.esa.snap.core.util.NamingConvention;
import javax.swing.DefaultListCellRenderer;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.WindowConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.colorchooser.AbstractColorChooserPanel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Vector;
/**
* A color chooser panel.
*
* @author Norman Fomferra
* @author Marco Peters
* @since SNAP 2.0
*/
public class ColorChooserPanel extends JPanel {
public static final String SELECTED_COLOR_PROPERTY = "selectedColor";
static final Color TRANSPARENCY = new Color(0, 0, 0, 0);
private static final int GAP = 2;
private Color selectedColor;
public ColorChooserPanel() {
this(Color.WHITE);
}
public ColorChooserPanel(Color selectedColor) {
super(new BorderLayout(GAP, GAP));
setBorder(new EmptyBorder(GAP, GAP, GAP, GAP));
setSelectedColor(selectedColor);
JButton noneButton = new JButton("None");
noneButton.addActionListener(e -> {
setSelectedColor(TRANSPARENCY);
});
JButton moreButton = new JButton("More...");
moreButton.addActionListener(e -> {
Color color = showMoreColorsDialog();
if (color != null) {
setSelectedColor(color);
}
});
add(noneButton, BorderLayout.NORTH);
add(createColorPicker(), BorderLayout.CENTER);
add(moreButton, BorderLayout.SOUTH);
// todo - use colors from popup menu LAF
setBackground(Color.WHITE);
}
public Color getSelectedColor() {
return selectedColor;
}
public void setSelectedColor(Color selectedColor) {
Color oldValue = this.selectedColor;
this.selectedColor = selectedColor;
firePropertyChange(SELECTED_COLOR_PROPERTY, oldValue, this.selectedColor);
}
protected JComponent createColorPicker() {
Color[] colors = {Color.BLACK,
Color.DARK_GRAY,
Color.GRAY,
Color.LIGHT_GRAY,
Color.WHITE,
Color.CYAN,
Color.BLUE,
Color.MAGENTA,
Color.YELLOW,
Color.ORANGE,
Color.RED,
Color.PINK,
Color.GREEN};
JPanel colorsPanel = new JPanel(new GridLayout(-1, 6, 4, 4));
colorsPanel.setOpaque(false);
for (Color color : colors) {
ColorLabel colorLabel = new ColorLabel(color);
colorLabel.setDisplayName(ColorCodes.getName(color));
colorLabel.setHoverEnabled(true);
colorLabel.setMaximumSize(colorLabel.getPreferredSize());
colorLabel.setMinimumSize(colorLabel.getPreferredSize());
colorLabel.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
setSelectedColor(colorLabel.getColor());
}
});
colorsPanel.add(colorLabel);
}
return colorsPanel;
}
protected Color showMoreColorsDialog() {
JColorChooser colorChooser = new JColorChooser(getSelectedColor());
AbstractColorChooserPanel[] oldChooserPanels = colorChooser.getChooserPanels();
AbstractColorChooserPanel[] newChooserPanels = new AbstractColorChooserPanel[oldChooserPanels.length + 1];
System.arraycopy(oldChooserPanels, 0, newChooserPanels, 1, oldChooserPanels.length);
newChooserPanels[0] = new MyAbstractColorChooserPanel();
colorChooser.setChooserPanels(newChooserPanels);
ColorTracker colorTracker = new ColorTracker(colorChooser);
JDialog dialog = JColorChooser.createDialog(this, "Select " + NamingConvention.COLOR_MIXED_CASE, true, colorChooser, colorTracker, null);
dialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
return colorTracker.getColor();
}
private static class MyAbstractColorChooserPanel extends AbstractColorChooserPanel implements ListSelectionListener {
private JList<String> colorList;
public MyAbstractColorChooserPanel() {
}
@Override
public void updateChooser() {
Color selectedColor = getColorSelectionModel().getSelectedColor();
if (selectedColor != null) {
int i = ColorCodes.indexOf(selectedColor);
if (i >= 0) {
colorList.setSelectedIndex(i);
}
}
}
@Override
protected void buildChooser() {
colorList = new JList<>(new Vector<>(ColorCodes.getNames()));
DefaultListCellRenderer cellRenderer = new DefaultListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
setOpaque(true);
Color color = ColorCodes.getColor(value.toString());
int max = Math.max(color.getRed(), Math.max(color.getGreen(), color.getBlue()));
setForeground(max < 160 ? Color.WHITE : Color.BLACK);
setBackground(color);
setBorder(new EmptyBorder(5, 5, 5, 5));
setFont(getFont().deriveFont(14f));
return this;
}
};
colorList.setCellRenderer(cellRenderer);
colorList.addListSelectionListener(this);
setLayout(new BorderLayout());
setBorder(new EmptyBorder(5, 5, 5, 5));
add(new JScrollPane(colorList), BorderLayout.CENTER);
}
@Override
public void valueChanged(ListSelectionEvent e) {
int selectedIndex = colorList.getSelectedIndex();
Color color = ColorCodes.getColor(selectedIndex);
getColorSelectionModel().setSelectedColor(color);
}
@Override
public String getDisplayName() {
return "HTML Color Codes";
}
@Override
public Icon getSmallDisplayIcon() {
return null;
}
@Override
public Icon getLargeDisplayIcon() {
return null;
}
}
private static class ColorTracker implements ActionListener {
private JColorChooser colorChooser;
private Color color;
public ColorTracker(JColorChooser colorChooser) {
this.colorChooser = colorChooser;
}
public Color getColor() {
return color;
}
@Override
public void actionPerformed(ActionEvent e) {
color = colorChooser.getColor();
}
}
}
| 7,468 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorChooserPanelFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorChooserPanelFactory.java | package org.esa.snap.ui.color;
import java.awt.Color;
/**
* A factory for color chooser panels.
*
* @author Norman Fomferra
* @author Marco Peters
* @since SNAP 2.0
*/
public interface ColorChooserPanelFactory {
ColorChooserPanel create(Color selectedColor);
}
| 273 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorLabel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorLabel.java | package org.esa.snap.ui.color;
import javax.swing.JComponent;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.event.MouseInputAdapter;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Shape;
import java.awt.event.MouseEvent;
/**
* A component for displaying color values.
*
* @author Norman Fomferra
* @since SNAP 2.0
*/
public class ColorLabel extends JComponent {
private String displayName;
private Color color;
private boolean highlighted;
private boolean hoverEnabled;
private MouseInputAdapter hoverListener;
public ColorLabel() {
this(Color.WHITE);
}
public ColorLabel(Color color) {
this(color, null);
}
public ColorLabel(Color color, String displayName) {
if (color != null) {
this.color = color;
} else {
this.color = ColorComboBox.TRANSPARENCY;
}
this.displayName = displayName;
setPreferredSize(new Dimension(14, 14));
setBorder(createEmptyBorder());
updateText();
hoverListener = new MouseHoverListener();
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
Color oldValue = this.color;
if (color != null) {
this.color = color;
} else {
this.color = ColorComboBox.TRANSPARENCY;
}
updateText();
repaint();
firePropertyChange("color", oldValue, this.color);
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
String oldValue = this.displayName;
this.displayName = displayName;
updateText();
firePropertyChange("displayName", oldValue, this.displayName);
}
public boolean isHoverEnabled() {
return hoverEnabled;
}
public void setHoverEnabled(boolean hoverEnabled) {
boolean oldValue = this.hoverEnabled;
this.hoverEnabled = hoverEnabled;
if (hoverEnabled) {
addMouseListener(hoverListener);
} else {
removeMouseListener(hoverListener);
}
firePropertyChange("hoverEnabled", oldValue, this.hoverEnabled);
}
public boolean isHighlighted() {
return highlighted;
}
public void setHighlighted(boolean highlighted) {
boolean oldValue = this.highlighted;
this.highlighted = highlighted;
firePropertyChange("highlighted", oldValue, this.highlighted);
if (highlighted) {
setBorder(createHighlightedBorder());
} else {
setBorder(createEmptyBorder());
}
}
private LineBorder createHighlightedBorder() {
return new LineBorder(Color.BLUE, 1);
}
private Border createEmptyBorder() {
return new EmptyBorder(1, 1, 1, 1);
}
private Color getColorBoxLineColor() {
int a = color.getAlpha();
Color borderColor;
if (a < 127) {
borderColor = Color.GRAY;
} else {
//int cMin = Math.min(color.getRed(), Math.min(color.getGreen(), color.getBlue()));
int cMax = Math.max(color.getRed(), Math.max(color.getGreen(), color.getBlue()));
if (cMax < 127) {
borderColor = Color.LIGHT_GRAY;
} else {
borderColor = Color.GRAY;
}
}
return borderColor;
}
private void updateText() {
String rgbText;
if (color.getAlpha() != 255) {
rgbText = String.format("%d,%d,%d,%d", color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
} else {
rgbText = String.format("%d,%d,%d", color.getRed(), color.getGreen(), color.getBlue());
}
String text;
if (getDisplayName() != null) {
text = String.format("%s (%s)", getDisplayName(), rgbText);
} else {
String name = ColorCodes.getName(color);
if (name != null) {
text = String.format("%s (%s)", name, rgbText);
} else {
text = rgbText;
}
}
setToolTipText(text);
}
@Override
protected void paintComponent(Graphics g) {
int x = getInsets().left;
int y = getInsets().top;
int w = getWidth() - (getInsets().left + getInsets().right) - 1;
int h = getHeight() - (getInsets().top + getInsets().bottom) - 1;
if (getColor().getAlpha() < 255) {
drawChessboardBackground(g, x, y, w, h);
}
drawColorBox(g, x, y, w, h);
}
private void drawColorBox(Graphics g, int x, int y, int w, int h) {
g.setColor(getColor());
g.fillRect(x, y, w, h);
g.setColor(getColorBoxLineColor());
g.drawRect(x, y, w, h);
}
private void drawChessboardBackground(Graphics g, int x, int y, int w, int h) {
int s = 8;
int ni = w / s + 1;
int nj = h / s + 1;
Shape clip = g.getClip();
g.setClip(x, y, w, h);
for (int j = 0; j < nj; j++) {
for (int i = 0; i < ni; i++) {
g.setColor(i % 2 != j % 2 ? Color.WHITE : Color.LIGHT_GRAY);
g.fillRect(x + i * s, y + j * s, s, s);
}
}
g.setClip(clip);
}
private class MouseHoverListener extends MouseInputAdapter {
@Override
public void mouseExited(MouseEvent e) {
setHighlighted(false);
}
@Override
public void mouseEntered(MouseEvent e) {
setHighlighted(true);
}
@Override
public void mousePressed(MouseEvent e) {
super.mousePressed(e);
}
@Override
public void mouseReleased(MouseEvent e) {
super.mouseReleased(e);
}
}
}
| 5,970 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorTableCellEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorTableCellEditor.java | package org.esa.snap.ui.color;
import javax.swing.AbstractCellEditor;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import java.awt.Color;
import java.awt.Component;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* A table cell editor for color values.
*
* @author Norman Fomferra
* @since SNAP 2.0
*/
public class ColorTableCellEditor extends AbstractCellEditor implements TableCellEditor, PropertyChangeListener {
private ColorComboBox colorComboBox;
private boolean adjusting;
public ColorTableCellEditor() {
this(new ColorComboBox());
}
public ColorTableCellEditor(ColorComboBox colorComboBox) {
this.colorComboBox = colorComboBox;
this.colorComboBox.addPropertyChangeListener(ColorComboBox.SELECTED_COLOR_PROPERTY, this);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
adjusting = true;
colorComboBox.setSelectedColor((Color) value);
adjusting = false;
return colorComboBox;
}
@Override
public Object getCellEditorValue() {
return colorComboBox.getSelectedColor();
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!adjusting) {
stopCellEditing();
}
}
}
| 1,386 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorEditor.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.ui.color;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyEditor;
import javax.swing.JComponent;
import java.awt.Color;
/**
* A value editor for colors.
*
* @author Marco Zuehlke
* @version $Revision$ $Date$
* @since BEAM 4.6
*/
public class ColorEditor extends PropertyEditor {
@Override
public boolean isValidFor(PropertyDescriptor propertyDescriptor) {
Class<?> type = propertyDescriptor.getType();
return type.isAssignableFrom(Color.class);
}
@Override
public JComponent createEditorComponent(PropertyDescriptor propertyDescriptor, BindingContext bindingContext) {
ColorComboBox colorComboBox = new ColorComboBox();
ColorComboBoxAdapter adapter = new ColorComboBoxAdapter(colorComboBox);
bindingContext.bind(propertyDescriptor.getName(), adapter);
return colorComboBox;
}
}
| 1,699 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
HelpDisplayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/help/HelpDisplayer.java | package org.esa.snap.ui.help;
import java.awt.Desktop;
import java.awt.Toolkit;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.runtime.Config;
import org.openide.util.HelpCtx;
import org.openide.util.Lookup;
import eu.esa.snap.netbeans.javahelp.api.Help;
/**
* Helper class to invoke the help system.
*/
public class HelpDisplayer {
/** URl for the online help. */
private static final String DEFAULT_ONLINE_HELP_URL = "https://step.esa.int/main/doc/online-help";
/** Relative URL for the version.json file */
private static final String VERSION_JSON_URL = "../../wp-content/help/versions/";
/** The version.json file name */
private static final String VERSION_JSON_FILE = "/version.json";
/**
* Invoke the help system with the provided help ID.
*
* @param helpId the help ID to be shown, if null the default help will be shown
*/
public static void show(String helpId) {
show(helpId != null ? new HelpCtx(helpId) : null);
}
/**
* Invoke the help system with the provided help context.
*
* @param helpCtx the context to be shown, if null the default help will be shown
*/
public static void show(HelpCtx helpCtx) {
final String serverURL = Config.instance().preferences().get("snap.online.help.url", DEFAULT_ONLINE_HELP_URL);
final String version = SystemUtils.getReleaseVersion();
final String fullURL = serverURL + "?helpid=" + helpCtx.getHelpID() + "&version=" + version;
final String versionURL = serverURL + VERSION_JSON_URL + version + VERSION_JSON_FILE;
if (checkServer(versionURL) && browse(fullURL)) {
// Online help opened
return;
}
Help helpImpl = Lookup.getDefault().lookup(Help.class);
if (helpImpl == null) {
Toolkit.getDefaultToolkit().beep();
return;
}
helpImpl.showHelp(helpCtx);
}
/**
* Open URL in default browser
*
* @param uriString the URL to open
* @return true if the operation succeded, false if not
*/
private static boolean browse(String uriString) {
final Desktop desktop = Desktop.getDesktop();
URI uri;
try {
uri = new URI(uriString);
} catch (URISyntaxException e) {
return false;
}
try {
desktop.browse(uri);
} catch (IOException e) {
return false;
} catch (UnsupportedOperationException e) {
return false;
}
return true;
}
private static boolean checkServer(final String serverURL) {
HttpURLConnection connection = null;
try {
URL url = new URL(serverURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("HEAD");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setConnectTimeout(1000);
// try to open the connection
final int responseCode = connection.getResponseCode();
if (responseCode >= 400) {
return false;
}
} catch (Exception e) {
return false;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return true;
}
}
| 3,544 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TableModelCsvEncoder.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/io/TableModelCsvEncoder.java | package org.esa.snap.ui.io;
import org.esa.snap.core.util.io.CsvWriter;
import javax.swing.table.TableModel;
import java.io.IOException;
import java.io.Writer;
/**
* This simple TableModelCsvEncoder writes the table model content encoded
* as CSV to a given writer. The separator char is {@code '\t'}.
*/
public class TableModelCsvEncoder implements CsvEncoder {
private final TableModel model;
public TableModelCsvEncoder(TableModel model) {
this.model = model;
}
/**
* Writes the table model content encoded as csv to the given writer.
* The separator char is {@code '\t'}.
* @param writer
* @throws IOException
*/
@Override
public void encodeCsv(Writer writer) throws IOException {
CsvWriter csv = new CsvWriter(writer, "\t");
encodeHeadline(csv);
encodeData(csv);
}
private void encodeHeadline(CsvWriter csv) throws IOException {
int count = model.getColumnCount();
final String[] colNames = new String[count];
for (int col = 0; col < count; col++) {
colNames[col] = model.getColumnName(col);
}
csv.writeRecord(colNames);
}
private void encodeData(CsvWriter csv) throws IOException {
int columnCount = model.getColumnCount();
int rowCount = model.getRowCount();
for (int row = 0; row < rowCount; row++) {
String[] record = new String[columnCount];
for (int column = 0; column < columnCount; column++) {
Object value = model.getValueAt(row, column);
record[column] = value != null ? value.toString() : "";
}
csv.writeRecord(record);
}
}
}
| 1,718 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FileArrayEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/io/FileArrayEditor.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.ui.io;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.util.Guardian;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.SnapFileChooser;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* An UI-Component which represents a product file list with the ability to add and remove files.
*/
public class FileArrayEditor {
private static final Dimension LIST_PREFERRED_SIZE = new Dimension(500, 200);
private JPanel basePanel;
private JFileChooser fileDialog;
private FileArrayEditorListener listener;
private final JList<File> listComponent;
private final List<File> fileList;
private final EditorParent parent;
private final String label;
/**
* Constructs the object with default values
*
* @param parent the parent editor
* @param label the label for this editor
*/
public FileArrayEditor(final EditorParent parent, String label) {
Guardian.assertNotNullOrEmpty("label", label);
this.parent = parent;
this.label = label;
fileList = new ArrayList<>();
listComponent = new JList<>();
setName(listComponent, this.label);
}
protected final EditorParent getParent() {
return parent;
}
/**
* Retrieves the editor UI.
*
* @return the editor UI
*/
public JComponent getUI() {
if (basePanel == null) {
createUI();
}
return basePanel;
}
/**
* Sets the list of files to be edited. The list currently held is overwritten.
*
* @param files {@code List} of {@code File}s to be set
*/
public void setFiles(final List<File> files) {
Guardian.assertNotNull("files", files);
fileList.clear();
fileList.addAll(files);
listComponent.setListData(fileList.toArray(new File[fileList.size()]));
notifyListener();
}
/**
* Retrieves the list of files currently edited
*
* @return a {@code List} of currently edited {@code File}s
*/
public List<File> getFiles() {
return fileList;
}
/**
* Sets the listener for this class
*
* @param listener the listener to associate with this editor
*/
public void setListener(final FileArrayEditorListener listener) {
this.listener = listener;
}
///////////////////////////////////////////////////////////////////////////
////// END OF PUBLIC
///////////////////////////////////////////////////////////////////////////
/**
* Creates the user interface
*/
private void createUI() {
// the label
final JLabel label = new JLabel(this.label + ":");
setName(label, this.label);
// the list
JComponent scrollPane = createFileArrayComponent();
// the add button
final JButton addButton = createAddFileButton();
// the remove button
final JButton removeButton = createRemoveFileButton();
// the button panel
final JPanel buttonPanel = new JPanel();
setName(buttonPanel, this.label);
buttonPanel.add(addButton);
buttonPanel.add(removeButton);
// the base panel
basePanel = GridBagUtils.createDefaultEmptyBorderPanel();
setName(basePanel, this.label);
final GridBagConstraints gbc = GridBagUtils.createConstraints(null);
gbc.anchor = GridBagConstraints.WEST;
gbc.weightx = 1;
gbc.gridy++;
basePanel.add(label, gbc);
gbc.anchor = GridBagConstraints.EAST;
basePanel.add(buttonPanel, gbc);
gbc.gridy++;
gbc.anchor = GridBagConstraints.WEST;
gbc.gridwidth = 2;
gbc.fill = GridBagConstraints.BOTH;
gbc.weightx = 1;
gbc.weighty = 1;
basePanel.add(scrollPane, gbc);
}
public JButton createRemoveFileButton() {
final JButton removeButton = (JButton) ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Minus16.gif"), false);
setName(removeButton, "removeButton");
removeButton.addActionListener(e -> onRemoveButton());
return removeButton;
}
public JButton createAddFileButton() {
final JButton addButton = (JButton) ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Plus16.gif"), false);
setName(addButton, "addButton");
addButton.addActionListener(e -> onAddButton());
return addButton;
}
public JComponent createFileArrayComponent() {
JScrollPane scrollPane = new JScrollPane(listComponent);
setName(scrollPane, label);
scrollPane.setPreferredSize(LIST_PREFERRED_SIZE);
return scrollPane;
}
private void setName(final Component comp, String name) {
comp.setName(name);
}
/*
* Callback invoked by the add button
*/
private void onAddButton() {
fileDialog = getFileDialogSafe();
final File userInputDir = parent.getUserInputDir();
final int retVal;
fileDialog.setCurrentDirectory(userInputDir);
retVal = fileDialog.showOpenDialog(basePanel);
if (retVal == JFileChooser.APPROVE_OPTION) {
File[] selected = fileDialog.getSelectedFiles();
fileList.addAll(Arrays.asList(selected));
listComponent.setListData(fileList.toArray(new File[fileList.size()]));
notifyListener();
parent.setUserInputDir(fileDialog.getCurrentDirectory());
}
}
/*
* Callback invoked by the remove button
*/
private void onRemoveButton() {
final List<File> selectedFiles = listComponent.getSelectedValuesList();
selectedFiles.forEach(fileList::remove);
listComponent.setListData(fileList.toArray(new File[fileList.size()]));
notifyListener();
}
/*
* Retrieves the file chooser object. If none is present, an object is constructed
*/
private JFileChooser getFileDialogSafe() {
if (fileDialog == null) {
fileDialog = createFileChooserDialog();
}
return fileDialog;
}
protected JFileChooser createFileChooserDialog() {
final JFileChooser chooser = new SnapFileChooser();
chooser.setAcceptAllFileFilterUsed(true);
chooser.setMultiSelectionEnabled(true);
final Iterator<ProductReaderPlugIn> iterator = ProductIOPlugInManager.getInstance().getAllReaderPlugIns();
List<SnapFileFilter> sortedFileFilters = SnapFileFilter.getSortedFileFilters(iterator);
sortedFileFilters.forEach(chooser::addChoosableFileFilter);
chooser.setFileFilter(chooser.getAcceptAllFileFilter());
return chooser;
}
/*
* Calls the listener about changes - if necessary
*/
private void notifyListener() {
if ((listener != null)) {
listener.updatedList(fileList.toArray(new File[fileList.size()]));
}
}
public interface EditorParent {
File getUserInputDir();
void setUserInputDir(File newDir);
}
public interface FileArrayEditorListener {
void updatedList(File[] files);
}
}
| 8,485 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CsvEncoder.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/io/CsvEncoder.java | package org.esa.snap.ui.io;
import java.io.IOException;
import java.io.Writer;
/**
* An encoder for CSV.
*
* @author Norman Fomferra
*/
public interface CsvEncoder {
void encodeCsv(Writer writer) throws IOException;
}
| 228 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractAssistantPage.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/assistant/AbstractAssistantPage.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.ui.assistant;
import java.awt.Component;
/**
* An abstract implementation of {@link AssistantPage}.
* <p>
* The user has only to implement the {@link #createPageComponent()} method.
* Other methods have meaningful default implementations, which can be overriden
* according to the concrete implementation.
* </p>
*/
public abstract class AbstractAssistantPage implements AssistantPage {
private String pageTitle;
private Component pageComponent;
private AssistantPageContext pageContext;
/**
* Creates a new instance with the given page title.
*
* @param pageTitle The title of the page.
*/
protected AbstractAssistantPage(String pageTitle) {
this.pageTitle = pageTitle;
}
@Override
public void setContext(AssistantPageContext pageContext) {
this.pageContext = pageContext;
}
@Override
public AssistantPageContext getContext() {
return pageContext;
}
@Override
public String getPageTitle() {
return pageTitle;
}
@Override
public final Component getPageComponent() {
if (pageComponent == null) {
pageComponent = createPageComponent();
}
return pageComponent;
}
/**
* Creates the component of this page.
*
* @return The component of this page
*/
protected abstract Component createPageComponent();
@Override
public boolean validatePage() {
return true;
}
@Override
public boolean hasNextPage() {
return false;
}
@Override
public AssistantPage getNextPage() {
return null;
}
@Override
public boolean canFinish() {
return true;
}
@Override
public boolean performFinish() {
return true;
}
@Override
public void performCancel() {
}
@Override
public boolean canHelp() {
return false;
}
@Override
public void performHelp() {
}
}
| 2,721 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AssistantPane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/assistant/AssistantPane.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.ui.assistant;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.UIUtils;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Shows a sequence of {@link AssistantPage assitant pages} with an dialog.
*/
public class AssistantPane implements AssistantPageContext {
private AssistantPage currentPage;
private Deque<AssistantPage> pageStack;
private JDialog dialog;
private Action prevAction;
private Action nextAction;
private Action finishAction;
private JLabel titleLabel;
private JPanel pagePanel;
private HelpAction helpAction;
private AssistantPane.CancelAction cancelAction;
/**
* Creates a new {@code AssistantPane}.
*
* @param parent The parent window.
* @param title The title of the dialog.
*/
public AssistantPane(Window parent, String title) {
pageStack = new ArrayDeque<AssistantPage>();
prevAction = new PrevAction();
nextAction = new NextAction();
finishAction = new FinishAction();
cancelAction = new CancelAction();
helpAction = new HelpAction();
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 2, 2));
buttonPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
buttonPanel.add(new JButton(prevAction));
final JButton nextButton = new JButton(nextAction);
buttonPanel.add(nextButton);
buttonPanel.add(new JButton(finishAction));
buttonPanel.add(new JButton(cancelAction));
buttonPanel.add(new JButton(helpAction));
titleLabel = new JLabel();
titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, 14.0f));
titleLabel.setHorizontalAlignment(JLabel.RIGHT);
titleLabel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
titleLabel.setForeground(Color.WHITE);
JPanel titlePanel = new JPanel(new BorderLayout());
titlePanel.setBackground(titlePanel.getBackground().darker());
titlePanel.add(titleLabel, BorderLayout.CENTER);
pagePanel = new JPanel(new BorderLayout());
pagePanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
dialog = new JDialog(parent, title, Dialog.ModalityType.APPLICATION_MODAL);
dialog.getContentPane().add(titlePanel, BorderLayout.NORTH);
dialog.getContentPane().add(pagePanel, BorderLayout.CENTER);
dialog.getContentPane().add(buttonPanel, BorderLayout.SOUTH);
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
dialog.getRootPane().setDefaultButton(nextButton);
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
cancelAction.cancel();
}
});
}
@Override
public Window getWindow() {
return dialog;
}
@Override
public AssistantPage getCurrentPage() {
return currentPage;
}
@Override
public void setCurrentPage(AssistantPage currentPage) {
this.currentPage = currentPage;
pagePanel.removeAll();
titleLabel.setText(currentPage.getPageTitle());
pagePanel.add(currentPage.getPageComponent(), BorderLayout.CENTER);
updateState();
dialog.invalidate();
dialog.validate();
dialog.repaint();
}
@Override
public void updateState() {
final AssistantPage page = getCurrentPage();
if (page != null) {
final boolean pageValid = page.validatePage();
prevAction.setEnabled(!pageStack.isEmpty());
nextAction.setEnabled(pageValid && page.hasNextPage());
finishAction.setEnabled(pageValid && page.canFinish());
helpAction.setEnabled(page.canHelp());
}
}
@Override
public void showErrorDialog(String message) {
final String dialogTitle;
final AssistantPage currentPage = getCurrentPage();
if (currentPage != null) {
dialogTitle = currentPage.getPageTitle();
} else {
dialogTitle = "Unexpected Error";
}
AbstractDialog.showErrorDialog(dialog, message, dialogTitle);
}
/**
* Displays the dialog if this {@code AssistantPane} with
* the given {@link AssistantPage page} as first page.
*
* @param firstPage The first page which is displayed in the dialog.
*/
public void show(AssistantPage firstPage) {
show(firstPage, null);
}
/**
* Displays the dialog if this {@code AssistantPane} with
* the given {@link AssistantPage page} as first page.
*
* @param firstPage The first page which is displayed in the dialog.
* @param bounds The screen bounds of the window, may be {@code null}.
*/
public void show(AssistantPage firstPage, Rectangle bounds) {
initPage(firstPage);
setCurrentPage(firstPage);
if (bounds == null) {
dialog.setSize(480, 320);
UIUtils.centerComponent(dialog, dialog.getParent());
} else {
dialog.setBounds(bounds);
}
dialog.setVisible(true);
}
private void initPage(AssistantPage currentPage) {
currentPage.setContext(this);
}
private void close() {
dialog.dispose();
pageStack.clear();
currentPage = null;
}
private class PrevAction extends AbstractAction {
private PrevAction() {
super("< Previous");
putValue(ACTION_COMMAND_KEY, "Previous");
putValue(MNEMONIC_KEY, (int) 'P');
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
}
@Override
public void actionPerformed(ActionEvent e) {
setCurrentPage(pageStack.pop());
}
}
private class NextAction extends AbstractAction {
private NextAction() {
super("Next >");
putValue(ACTION_COMMAND_KEY, "Next");
putValue(MNEMONIC_KEY, (int) 'N');
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
}
@Override
public void actionPerformed(ActionEvent e) {
AssistantPage nextPage = currentPage.getNextPage();
if (nextPage != null) {
pageStack.push(currentPage);
initPage(nextPage);
setCurrentPage(nextPage);
}
}
}
private class FinishAction extends AbstractAction {
private FinishAction() {
super("Finish");
putValue(ACTION_COMMAND_KEY, "Finish");
putValue(MNEMONIC_KEY, (int) 'F');
}
@Override
public void actionPerformed(ActionEvent e) {
if (getCurrentPage().performFinish()) {
close();
}
}
}
private class CancelAction extends AbstractAction {
private CancelAction() {
super("Cancel");
putValue(ACTION_COMMAND_KEY, "Cancel");
putValue(MNEMONIC_KEY, (int) 'C');
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0));
}
@Override
public void actionPerformed(ActionEvent e) {
cancel();
}
public void cancel() {
getCurrentPage().performCancel();
close();
}
}
private class HelpAction extends AbstractAction {
private HelpAction() {
super("Help");
putValue(ACTION_COMMAND_KEY, "Help");
putValue(MNEMONIC_KEY, (int) 'H');
putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_HELP, 0));
}
@Override
public void actionPerformed(ActionEvent e) {
getCurrentPage().performHelp();
}
}
}
| 9,150 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AssistantPageContext.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/assistant/AssistantPageContext.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.ui.assistant;
import java.awt.Window;
/**
* Instances of this interface provide the context for
* implementations of {@link AssistantPage}.
*/
public interface AssistantPageContext {
/**
* The window in which the {@link AssistantPage} is shown.
*
* @return The window.
*/
Window getWindow();
/**
* Gets the currently displayed {@link AssistantPage page}.
*
* @return The current page.
*/
AssistantPage getCurrentPage();
/**
* Sets the currently displayed {@link AssistantPage page}.
* Should only be called by the framwoerk.
*
* @param page The current page.
*/
void setCurrentPage(AssistantPage page);
/**
* Forces an updated of the state.
*/
void updateState();
/**
* Shows an error dialog with the given message.
*
* @param message The error message to display.
*/
void showErrorDialog(String message);
}
| 1,696 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AssistantPage.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/assistant/AssistantPage.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.ui.assistant;
import java.awt.Component;
/**
* An {@code AssistantPage} is part of a sequence of pages. <br>
* It is used by an {@link AssistantPane} to assists the user to
* accomplish a specific task by stepping through the pages.
*/
public interface AssistantPage {
/**
* Gets the title of the page.
*
* @return The page title.
*/
String getPageTitle();
/**
* Gets the component of the page.
*
* @return The page component.
*/
Component getPageComponent();
/**
* @return true, if a next page is available
*/
boolean hasNextPage();
/**
* Called only if {@link #validatePage()} and {@link #hasNextPage()} return {@code true}.
*
* @return the next page, or {@code null} if no next page exists or the page could not be created.
*/
AssistantPage getNextPage();
/**
* Called from {@link AssistantPageContext#updateState()} in order to validate user inputs.
*
* @return true, if the current page is valid
*/
boolean validatePage();
/**
* Determines if the page can finish the current assitant or not.
*
* @return {@code true} if the page can perform finish, otherwise {@code false}
*/
boolean canFinish();
/**
* Ccalled only if {@link #validatePage()} and {@link #canFinish()} return {@code true}.
*
* @return {@code true} if finishing was successful, otherwise {@code false}.
*/
boolean performFinish();
/**
* Cancels the current execution of the assitant.
* Implementors shall release allocated resources.
*/
void performCancel();
/**
* Determines if the page can show help information.
*
* @return {@code true} if the page can show help information, otherwise {@code false}
*/
boolean canHelp();
/**
* Only called if @link #canHelp ()} returns {@code true}.
*/
void performHelp();
/**
* Sets the current context for this page.
*
* @param pageContext The context of the page.
*/
void setContext(AssistantPageContext pageContext);
/**
* Gets the current context for this page.
*
* @return The context of the page.
*/
AssistantPageContext getContext();
}
| 3,025 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CollectionLayerAssistantPage.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/CollectionLayerAssistantPage.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.ui.layer;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
public class CollectionLayerAssistantPage extends AbstractLayerSourceAssistantPage {
private static final ArrayList<String> names = new ArrayList<String>();
private JComboBox nameBox;
static {
// todo - load names from preferences
names.add("");
}
CollectionLayerAssistantPage() {
super("Set Layer Name");
}
@Override
public Component createPageComponent() {
nameBox = new JComboBox(names.toArray());
nameBox.addItemListener(new NameBoxItemListener());
nameBox.addActionListener(new NameBoxActionListener());
nameBox.setEditable(true);
final JPanel panel = new JPanel(new GridBagLayout());
final GridBagConstraints constraints = new GridBagConstraints();
panel.setBorder(new EmptyBorder(4, 4, 4, 4));
constraints.fill = GridBagConstraints.HORIZONTAL;
constraints.weighty = 0.1;
constraints.weightx = 0.1;
panel.add(new JLabel("Layer name:"), constraints);
constraints.weightx = 0.9;
panel.add(nameBox, constraints);
return panel;
}
@Override
public boolean validatePage() {
return nameBox.getSelectedItem() != null && !nameBox.getSelectedItem().toString().trim().isEmpty();
}
@Override
public boolean performFinish() {
Layer layer = new CollectionLayer(nameBox.getSelectedItem().toString().trim());
Layer rootLayer = getContext().getLayerContext().getRootLayer();
rootLayer.getChildren().add(0, layer);
if (!names.contains(layer.getName())) {
names.add(1, layer.getName());
}
return true;
}
private class NameBoxItemListener implements ItemListener {
@Override
public void itemStateChanged(ItemEvent e) {
getContext().updateState();
}
}
private class NameBoxActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
getContext().updateState();
}
}
}
| 3,279 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerSourceDescriptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/LayerSourceDescriptor.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.ui.layer;
import com.bc.ceres.glayer.LayerType;
/**
* The {@code LayerSourceDescriptor} provides metadata and
* a factory method for a {@link LayerSource}.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*
* @author Marco Peters
* @author Marco Zühlke
* @version $ Revision $ $ Date $
* @since BEAM 4.6
*/
public interface LayerSourceDescriptor {
/**
* A unique ID.
*
* @return The unique ID.
*/
String getId();
/**
* A human readable name.
*
* @return The name.
*/
String getName();
/**
* A text describing what the {@link LayerSource}, created by
* this {@code LayerSourceDescriptor}, does.
*
* @return A description.
*/
String getDescription();
/**
* Creates the {@link LayerSource} which is used in the graphical user interface to
* add {@link com.bc.ceres.glayer.Layer} to a view.
*
* @return The {@link LayerSource}.
*/
LayerSource createLayerSource();
/**
* The {@link LayerType}.
*
* @return the type of the layer which is added to a view, or {@code null} if
* multiple layers are added.
*/
LayerType getLayerType();
}
| 2,020 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleLayerSource.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/SimpleLayerSource.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.ui.layer;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.LayerType;
/**
* This layer source uses the given layer type to construct new layer.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*
* @author Marco Peters
* @version $ Revision $ $ Date $
* @since BEAM 4.6
*/
public class SimpleLayerSource implements LayerSource {
private LayerType layerType;
public SimpleLayerSource(LayerType layerType) {
this.layerType = layerType;
}
@Override
public boolean isApplicable(LayerSourcePageContext pageContext) {
return layerType.isValidFor(pageContext.getLayerContext());
}
@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) {
LayerContext layerCtx = pageContext.getLayerContext();
Layer layer = layerType.createLayer(layerCtx, new PropertyContainer());
if (layer != null) {
layerCtx.getRootLayer().getChildren().add(layer);
return true;
}
return false;
}
@Override
public void cancel(LayerSourcePageContext pageContext) {
}
}
| 2,330 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerSourceAssistantPane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/LayerSourceAssistantPane.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.ui.layer;
import com.bc.ceres.glayer.LayerContext;
import org.esa.snap.ui.assistant.AssistantPane;
import org.esa.snap.ui.product.ProductSceneView;
import org.openide.util.Utilities;
import java.awt.Window;
import java.util.HashMap;
import java.util.Map;
/**
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*/
public class LayerSourceAssistantPane extends AssistantPane implements LayerSourcePageContext {
private final Map<String, Object> properties;
private LayerSource layerSource;
public LayerSourceAssistantPane(Window parent, String title) {
super(parent, title);
properties = new HashMap<String, Object>();
}
private ProductSceneView getSelectedProductSceneView() {
return Utilities.actionsGlobalContext().lookup(ProductSceneView.class);
}
@Override
public LayerContext getLayerContext() {
return getSelectedProductSceneView().getSceneImage();
}
@Override
public void setLayerSource(LayerSource layerSource) {
this.layerSource = layerSource;
}
@Override
public LayerSource getLayerSource() {
return layerSource;
}
@Override
public Object getPropertyValue(String key) {
return properties.get(key);
}
@Override
public void setPropertyValue(String key, Object value) {
properties.put(key, value);
}
}
| 2,172 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerSource.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/LayerSource.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.ui.layer;
/**
* A layer source can add one or more layers
* to an already existing root layer.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*
* @author Marco Peters
* @author Marco Zühlke
* @version $Revision: $ $Date: $
* @since BEAM 4.6
*/
public interface LayerSource {
/**
* Check if this layer source is applicable to the current context.
*
* @param pageContext The current context.
* @return true, if this layer source is applicable.
*/
boolean isApplicable(LayerSourcePageContext pageContext);
/**
* @return true, if this layer source has assistant pages.
*/
boolean hasFirstPage();
/**
* Returns the first page (of possible many) of the assistant
* that belongs to this layer source. The given context can be
* interrogated to decide which page to return.
*
* @param pageContext The current context.
* @return the first assistant page.
*/
AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext);
/**
* Checks whether this layer source can perform its finishing
* method without further information.
*
* @param pageContext The current context.
* @return true, if finish can be called.
*/
boolean canFinish(LayerSourcePageContext pageContext);
/**
* Adds one or more layers to the given context
*
* @param pageContext The current context.
* @return true, if the method completed successfully
*/
boolean performFinish(LayerSourcePageContext pageContext);
/**
* Aborts the operation of this layer source.
* This method is responsible for freeing all resources acquired by
* the layer source.
*
* @param pageContext The current context.
*/
void cancel(LayerSourcePageContext pageContext);
}
| 2,656 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CollectionLayerSource.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/CollectionLayerSource.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.ui.layer;
/**
* This layer source creates a new and empty collection layer.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*
* @author Marco Zuehlke
* @version $Revision$ $Date$
* @since BEAM 4.6
*/
public class CollectionLayerSource implements LayerSource {
@Override
public boolean isApplicable(LayerSourcePageContext pageContext) {
return true;
}
@Override
public boolean hasFirstPage() {
return true;
}
@Override
public AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext) {
return new CollectionLayerAssistantPage();
}
@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,789 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultLayerSourceDescriptor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/DefaultLayerSourceDescriptor.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.ui.layer;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
/**
* The {@code DefaultLayerSourceDescriptor} provides metadata and
* a factory method for a {@link LayerSource}.
* <p>
* Instances of this class are created by reading the extension configuration of
* the extension point {@code "layerSources"} in the {@code module.xml}.
* </p>
* Example 1:
* <pre>
* <extension point="beam-visat-rcp:layerSources">
* <layerSource>
* <id>shapefile-layer-source</id>
* <name>ESRI Shapefile</name>
* <description>Displays shapes from an ESRI Shapefile</description>
* <class>org.esa.snap.visat.toolviews.layermanager.layersrc.shapefile.ShapefileLayerSource</class>
* </layerSource>
* </extension>
* </pre>
* Example 2:
* <pre>
* <extension point="beam-visat-rcp:layerSources">
* <layerSource>
* <id>bluemarble-layer-source</id>
* <name>NASA Blue Marble;/name>
* <description>Adds NASA Blue Marble image layer to the background.</description>
* <layerType>org.esa.snap.worldmap.BlueMarbleLayerType</class>
* </layerSource>
* </extension>
* </pre>
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*/
@SuppressWarnings({"UnusedDeclaration"})
public class DefaultLayerSourceDescriptor implements LayerSourceDescriptor {
private final String id;
private final String name;
private final String description;
private final Class<? extends LayerSource> layerSourceClass;
private final String layerTypeClassName;
private LayerType layerType;
public DefaultLayerSourceDescriptor(String id, String name, String description,
Class<? extends LayerSource> layerSourceClass) {
this.id = id;
this.name = name;
this.description = description;
this.layerSourceClass = layerSourceClass;
this.layerTypeClassName = null;
}
public DefaultLayerSourceDescriptor(String id, String name, String description,
String layerTypeClassName) {
this.id = id;
this.name = name;
this.description = description;
this.layerTypeClassName = layerTypeClassName;
this.layerSourceClass = null;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public String toString() {
return name;
}
@Override
public LayerSource createLayerSource() {
if (layerSourceClass == null) {
return new SimpleLayerSource(getLayerType());
}
try {
return layerSourceClass.newInstance();
} catch (Exception e) {
String message = String.format("Could not create instance of class [%s]", layerSourceClass.getName());
throw new IllegalStateException(message, e);
}
}
@Override
public synchronized LayerType getLayerType() {
if (layerTypeClassName == null) {
return null;
}
if (layerType == null) {
try {
return LayerTypeRegistry.getLayerType(layerTypeClassName);
} catch (Exception e) {
String message = String.format("Could not create instance of class [%s]", layerTypeClassName);
throw new IllegalStateException(message, e);
}
}
return layerType;
}
}
| 4,561 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractLayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/AbstractLayerEditor.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.ui.layer;
import com.bc.ceres.glayer.Layer;
import javax.swing.JComponent;
/**
* Base class for layer editors.
*
* @author Norman Fomferra
* @since BEAM 4.10
*/
public abstract class AbstractLayerEditor implements LayerEditor {
private Layer currentLayer;
protected AbstractLayerEditor() {
}
@Override
public final JComponent createControl(Layer layer) {
this.currentLayer = layer;
return createControl();
}
@Override
public void handleEditorAttached() {
}
@Override
public void handleEditorDetached() {
}
@Override
public void handleLayerContentChanged() {
}
/**
* Creates the editor control for this editor.
*
* @return The editor control.
*/
protected abstract JComponent createControl();
/**
* @return The current layer.
*/
protected Layer getCurrentLayer() {
return currentLayer;
}
}
| 1,682 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerSourcePageContext.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/LayerSourcePageContext.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.ui.layer;
import com.bc.ceres.glayer.LayerContext;
import org.esa.snap.ui.assistant.AssistantPageContext;
/**
* Instances of this interface provide the context for implementations of {@link AbstractLayerSourceAssistantPage}.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*/
public interface LayerSourcePageContext extends AssistantPageContext {
/**
* Gets the {@link LayerContext layer context} of the selected view.
*
* @return The {@link LayerContext layer context} of the selected view.
*/
LayerContext getLayerContext();
/**
* Sets the {@link LayerSource} of this assistant.
*
* @param layerSource The {@link LayerSource} of this assistant.
*/
void setLayerSource(LayerSource layerSource);
/**
* Gets the {@link LayerSource} of this assistant.
*
* @return The {@link LayerSource} of this assistant.
*/
LayerSource getLayerSource();
/**
* Gets the value for the given key.
*
* @param key The key of the property.
*
* @return The value of the property.
*/
Object getPropertyValue(String key);
/**
* Sets the value for the given key.
*
* @param key The key of the property.
* @param value The value of the property.
*/
void setPropertyValue(String key, Object value);
}
| 2,153 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractLayerConfigurationEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/AbstractLayerConfigurationEditor.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.ui.layer;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.binding.accessors.DefaultPropertyAccessor;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyPane;
import javax.swing.JComponent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* Base class for editors allowing to modify a layer's configuration.
*
* @author Marco Zühlke
* @since BEAM 4.6
*/
// SEP2018 - Daniel Knowles - Modified to call a new method propertyPane.createJScrollPanel(), which returns
// a JScrollPane instead of a JPanel in order to ensure all property components can be accessed by the user
public abstract class AbstractLayerConfigurationEditor extends AbstractLayerEditor {
private BindingContext bindingContext;
/**
* @return The binding context.
*/
protected final BindingContext getBindingContext() {
return bindingContext;
}
@Override
public JComponent createControl() {
bindingContext = new BindingContext();
PropertySet propertySet = bindingContext.getPropertySet();
propertySet.addPropertyChangeListener(new PropertyChangeHandler());
addEditablePropertyDescriptors();
PropertyPane propertyPane = new PropertyPane(bindingContext);
//
// Modification note: Daniel Knowles 2018
// Modified to return JScrollPane instead of JPanel due to the large number of properties being added to the Graticule layer
// If for some reason this option is only desired for a certain layer then the following type of if clause might be used
// if ("Graticule".equals(getCurrentLayer().getName())) {}
//
return propertyPane.createJScrollPanel();
}
@Override
public void handleLayerContentChanged() {
final Property[] editorProperties = bindingContext.getPropertySet().getProperties();
for (Property editorProperty : editorProperties) {
final String propertyName = editorProperty.getDescriptor().getName();
final Property layerProperty = getCurrentLayer().getConfiguration().getProperty(propertyName);
if (layerProperty != null) {
final Binding binding = bindingContext.getBinding(propertyName);
final Object layerValue = layerProperty.getValue();
final Object editorValue = binding.getPropertyValue();
if (editorValue != layerValue && (editorValue == null || !editorValue.equals(layerValue))) {
binding.setPropertyValue(layerValue);
}
}
}
}
/**
* Does nothing.
*/
@Override
public void handleEditorAttached() {
}
/**
* Does nothing.
*/
@Override
public void handleEditorDetached() {
}
/**
* Clients override in order to subsequently call {@link #addPropertyDescriptor(com.bc.ceres.binding.PropertyDescriptor)}
* for each property that shall be editable by this editor.
*/
protected abstract void addEditablePropertyDescriptors();
/**
* Defines an editable property.
*
* @param propertyDescriptor The property's descriptor.
*/
protected final void addPropertyDescriptor(PropertyDescriptor propertyDescriptor) {
String propertyName = propertyDescriptor.getName();
Object value = getCurrentLayer().getConfiguration().getValue(propertyName);
if (value == null) {
value = propertyDescriptor.getDefaultValue();
}
Property editorProperty = new Property(propertyDescriptor, new DefaultPropertyAccessor(value));
bindingContext.getPropertySet().addProperty(editorProperty);
}
private class PropertyChangeHandler implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if (getCurrentLayer() != null) {
try {
final Property layerProperty = getCurrentLayer().getConfiguration().getProperty(propertyName);
if (layerProperty != null) {
layerProperty.setValue(evt.getNewValue());
}
} catch (ValidationException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
}
}
| 5,366 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LayerEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/LayerEditor.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.ui.layer;
import com.bc.ceres.glayer.Layer;
import javax.swing.JComponent;
import javax.swing.JLabel;
/**
* An editor for a specific layer type.
* <p>
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*
* @author Norman Fomferra
* @version $Revision$ $Date$
* @since BEAM 4.6
*/
public interface LayerEditor {
LayerEditor EMPTY = new AbstractLayerEditor() {
@Override
public JComponent createControl() {
return new JLabel("No editor available.");
}
};
/**
* Creates the control for the user interface which is displayed
* in the Layer Editor Toolview.
*
* @param layer The layer to create the control for.
* @return The control.
*/
JComponent createControl(Layer layer);
/**
* Called y the framework in order to inform this editor that it has been attached to the Layer Editor Toolview.
*/
void handleEditorAttached();
/**
* Called y the framework in order to inform this editor that it has been detached from the Layer Editor Toolview.
*/
void handleEditorDetached();
/**
* Called y the framework in order to inform this editor that the current layer has changed.
* Usually the the editor control must be updated in this case.
*/
void handleLayerContentChanged();
}
| 2,128 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractLayerSourceAssistantPage.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/layer/AbstractLayerSourceAssistantPage.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.ui.layer;
import org.esa.snap.ui.assistant.AbstractAssistantPage;
/**
* <i>Note: This API is not public yet and may significantly change in the future. Use it at your own risk.</i>
*/
public abstract class AbstractLayerSourceAssistantPage extends AbstractAssistantPage {
protected AbstractLayerSourceAssistantPage(String pageTitle) {
super(pageTitle);
}
@Override
public LayerSourcePageContext getContext() {
return (LayerSourcePageContext) super.getContext();
}
@Override
public void performCancel() {
LayerSourcePageContext context = getContext();
LayerSource layerSource = context.getLayerSource();
if (layerSource != null) {
layerSource.cancel(context);
}
}
}
| 1,510 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TrackLayerType.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/TrackLayerType.java | package org.esa.snap.ui.product;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.locationtech.jts.geom.Geometry;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.operation.TransformException;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.AffineTransform;
import java.awt.geom.Line2D;
import java.awt.geom.Point2D;
/**
* A special layer type that is used to create layers for {@link VectorDataNode}s that
* have a special feature type. In this case "org.esa.snap.TrackPoint".
* <p>
* <i>Note: this is experimental code.</i>
*
* @author Norman Fomferra
* @since BEAM 4.10
*/
public class TrackLayerType extends VectorDataLayerType {
public static boolean isTrackPointNode(VectorDataNode node) {
final Object trackPoints = node.getFeatureType().getUserData().get("trackPoints");
return trackPoints != null && trackPoints.toString().equals("true");
}
@Override
protected VectorDataLayer createLayer(VectorDataNode vectorDataNode, RasterDataNode rasterDataNode, PropertySet configuration) {
return new TrackLayer(this, vectorDataNode, rasterDataNode, configuration);
}
public static class TrackLayer extends VectorDataLayer {
public static final Color STROKE_COLOR = Color.ORANGE;
public static final double STROKE_OPACITY = 0.8;
public static final double STROKE_WIDTH = 2.0;
public static final double FILL_OPACITY = 0.5;
public static final Color FILL_COLOR = Color.WHITE;
private final Paint strokePaint;
private final SceneTransformProvider sceneTransformProvider;
public TrackLayer(VectorDataLayerType vectorDataLayerType, VectorDataNode vectorDataNode,
SceneTransformProvider provider, PropertySet configuration) {
super(vectorDataLayerType, vectorDataNode, provider, configuration);
String styleCss = vectorDataNode.getDefaultStyleCss();
DefaultFigureStyle style = new DefaultFigureStyle(styleCss);
style.fromCssString(styleCss);
style.setSymbolName("circle");
style.setStrokeColor(STROKE_COLOR);
style.setStrokeWidth(STROKE_WIDTH);
style.setStrokeOpacity(STROKE_OPACITY);
style.setFillColor(FILL_COLOR);
style.setFillOpacity(FILL_OPACITY);
strokePaint = style.getStrokePaint();
vectorDataNode.setDefaultStyleCss(style.toCssString());
sceneTransformProvider = provider;
}
@Override
protected void renderLayer(Rendering rendering) {
drawTrackPointConnections(rendering);
super.renderLayer(rendering);
}
private void drawTrackPointConnections(Rendering rendering) {
Graphics2D g = rendering.getGraphics();
AffineTransform oldTransform = g.getTransform();
try {
g.transform(rendering.getViewport().getModelToViewTransform());
drawTrackPointConnections0(rendering);
} finally {
g.setTransform(oldTransform);
}
}
private void drawTrackPointConnections0(Rendering rendering) {
// todo - get these styles from vector data node. (nf)
rendering.getGraphics().setPaint(strokePaint);
float scalingFactor = (float) rendering.getViewport().getViewToModelTransform().getScaleX();
float effectiveStrokeWidth = (float) (scalingFactor * STROKE_WIDTH);
float effectiveDash = Math.max(1.0F, scalingFactor * 5.0F);
float effectiveMeterLimit = Math.max(1.0F, scalingFactor * 10.0F);
BasicStroke basicStroke = new BasicStroke(effectiveStrokeWidth,
BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_MITER,
effectiveMeterLimit,
new float[]{
effectiveDash,
effectiveDash},
0.0f);
rendering.getGraphics().setStroke(basicStroke);
// FeatureCollection.toArray() returns the feature in original order
// todo - must actually sort using some (timestamp) attribute (nf)
SimpleFeature[] features = getVectorDataNode().getFeatureCollection().toArray(new SimpleFeature[0]);
double lastX = 0;
double lastY = 0;
for (int i = 0; i < features.length; i++) {
SimpleFeature feature = features[i];
Geometry geometry = (Geometry) feature.getDefaultGeometry();
org.locationtech.jts.geom.Point centroid = geometry.getCentroid();
try {
final Point2D.Double sceneCoords = new Point2D.Double(centroid.getX(), centroid.getY());
final Point2D.Double modelCoords = new Point2D.Double();
sceneTransformProvider.getSceneToModelTransform().transform(sceneCoords, modelCoords);
if (i > 0) {
rendering.getGraphics().draw(new Line2D.Double(lastX, lastY, centroid.getX(), centroid.getY()));
}
lastX = modelCoords.getX();
lastY = modelCoords.getY();
} catch (TransformException e) {
//continue loop
}
}
}
}
}
| 5,991 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractPlacemarkTableModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/AbstractPlacemarkTableModel.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.ui.product;
import com.bc.ceres.core.ProgressMonitor;
import org.locationtech.jts.geom.Point;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Placemark;
import org.esa.snap.core.datamodel.PlacemarkDescriptor;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeListenerAdapter;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.core.util.ArrayUtils;
import org.esa.snap.core.util.math.MathUtils;
import org.opengis.referencing.operation.TransformException;
import javax.swing.table.DefaultTableModel;
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
public abstract class AbstractPlacemarkTableModel extends DefaultTableModel {
private final PlacemarkDescriptor placemarkDescriptor;
private Product product;
private Band[] selectedBands;
private TiePointGrid[] selectedGrids;
private final PlacemarkListener placemarkListener;
private final ArrayList<Placemark> placemarkList = new ArrayList<>(10);
protected AbstractPlacemarkTableModel(PlacemarkDescriptor placemarkDescriptor, Product product, Band[] selectedBands,
TiePointGrid[] selectedGrids) {
this.placemarkDescriptor = placemarkDescriptor;
this.product = product;
initSelectedBands(selectedBands);
initSelectedGrids(selectedGrids);
placemarkListener = new PlacemarkListener();
if (product != null) {
product.addProductNodeListener(placemarkListener);
}
initPlacemarkList(product);
}
public Placemark[] getPlacemarks() {
return placemarkList.toArray(new Placemark[placemarkList.size()]);
}
public Placemark getPlacemarkAt(int modelRow) {
return placemarkList.get(modelRow);
}
public PlacemarkDescriptor getPlacemarkDescriptor() {
return placemarkDescriptor;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
if (this.product == product) {
return;
}
if (this.product != null) {
this.product.removeProductNodeListener(placemarkListener);
}
this.product = product;
if (this.product != null) {
this.product.addProductNodeListener(placemarkListener);
}
placemarkList.clear();
initPlacemarkList(this.product);
selectedBands = new Band[0];
selectedGrids = new TiePointGrid[0];
fireTableStructureChanged();
}
public Band[] getSelectedBands() {
return selectedBands;
}
public void setSelectedBands(Band[] selectedBands) {
this.selectedBands = selectedBands != null ? selectedBands : new Band[0];
fireTableStructureChanged();
}
public TiePointGrid[] getSelectedGrids() {
return selectedGrids;
}
public void setSelectedGrids(TiePointGrid[] selectedGrids) {
this.selectedGrids = selectedGrids != null ? selectedGrids : new TiePointGrid[0];
fireTableStructureChanged();
}
public boolean addPlacemark(Placemark placemark) {
if (placemarkList.add(placemark)) {
final int insertedRowIndex = placemarkList.indexOf(placemark);
fireTableRowsInserted(insertedRowIndex, insertedRowIndex);
return true;
}
return false;
}
public boolean removePlacemark(Placemark placemark) {
final int index = placemarkList.indexOf(placemark);
if (index != -1) {
placemarkList.remove(placemark);
fireTableRowsDeleted(index, index);
return true;
}
return false;
}
public void removePlacemarkAt(int index) {
if (placemarkList.size() > index) {
final Placemark placemark = placemarkList.get(index);
removePlacemark(placemark);
}
}
public abstract String[] getStandardColumnNames();
public String[] getAdditionalColumnNames() {
String[] standardColumnNames = getStandardColumnNames();
int columnCount = getColumnCount();
final int columnCountMin = standardColumnNames.length;
String[] additionalColumnNames = new String[columnCount - columnCountMin];
for (int i = 0; i < additionalColumnNames.length; i++) {
additionalColumnNames[i] = getColumnName(columnCountMin + i);
}
return additionalColumnNames;
}
@Override
public abstract boolean isCellEditable(int rowIndex, int columnIndex);
protected abstract Object getStandardColumnValueAt(int rowIndex, int columnIndex);
@Override
public int getRowCount() {
if (placemarkList == null) {
return 0;
}
return placemarkList.size();
}
@Override
public int getColumnCount() {
int count = getStandardColumnNames().length;
if (selectedBands != null) {
count += selectedBands.length;
}
if (selectedGrids != null) {
count += selectedGrids.length;
}
return count;
}
@Override
public String getColumnName(int columnIndex) {
if (columnIndex < getStandardColumnNames().length) {
return getStandardColumnNames()[columnIndex];
}
int newIndex = columnIndex - getStandardColumnNames().length;
if (newIndex < getNumSelectedBands()) {
return selectedBands[newIndex].getName();
}
newIndex -= getNumSelectedBands();
if (selectedGrids != null && newIndex < selectedGrids.length) {
return selectedGrids[newIndex].getName();
}
return "?";
}
public int getColumnIndex(String columnName) {
String[] standardColumnNames = getStandardColumnNames();
int index = Arrays.binarySearch(standardColumnNames, columnName);
if(index < 0) {
int elementIndex = ArrayUtils.getElementIndex(columnName, getAdditionalColumnNames());
if (elementIndex >= 0) {
index = standardColumnNames.length + elementIndex;
}
}
return index;
}
@Override
public Class getColumnClass(int columnIndex) {
if (columnIndex >= 0 && columnIndex < getStandardColumnNames().length - 1) {
return Double.class;
}
return Object.class;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex < getStandardColumnNames().length) {
return getStandardColumnValueAt(rowIndex, columnIndex);
}
return getAdditionalValue(rowIndex, columnIndex);
}
private Object getAdditionalValue(int rowIndex, int columnIndex) {
final Placemark placemark = placemarkList.get(rowIndex);
int index = columnIndex - getStandardColumnNames().length;
final Object defaultGeometry = placemark.getFeature().getDefaultGeometry();
if (!(defaultGeometry instanceof Point)) {
throw new IllegalStateException("A placemark must have a point feature");
}
final Point point = (Point) defaultGeometry;
Point2D.Double sceneCoords = new Point2D.Double(point.getX(), point.getY());
if (index < getNumSelectedBands()) {
final Band band = selectedBands[index];
final AffineTransform modelToImageTransform;
final Point2D modelCoords;
try {
modelCoords = band.getSceneToModelTransform().transform(sceneCoords, new Point2D.Double());
modelToImageTransform = band.getImageToModelTransform().createInverse();
} catch (NoninvertibleTransformException | TransformException e) {
return "Indeterminate";
}
PixelPos rasterPos = (PixelPos) modelToImageTransform.transform(modelCoords, new PixelPos());
final int x = MathUtils.floorInt(rasterPos.getX());
final int y = MathUtils.floorInt(rasterPos.getY());
final int width = band.getRasterWidth();
final int height = band.getRasterHeight();
if (x < 0 || x >= width || y < 0 || y >= height) {
return "No-data";
}
if (band.isPixelValid(x, y)) {
try {
float[] value = null;
value = band.readPixels(x, y, 1, 1, value, ProgressMonitor.NULL);
return value[0];
} catch (IOException ignored) {
return "I/O-error";
}
} else {
return "NaN";
}
}
index -= getNumSelectedBands();
if (index < selectedGrids.length) {
final TiePointGrid grid = selectedGrids[index];
final AffineTransform modelToImageTransform;
final Point2D modelCoords;
try {
modelCoords = grid.getSceneToModelTransform().transform(sceneCoords, new Point2D.Double());
modelToImageTransform = grid.getImageToModelTransform().createInverse();
} catch (NoninvertibleTransformException | TransformException e) {
return "Indeterminate";
}
PixelPos rasterPos = (PixelPos) modelToImageTransform.transform(modelCoords, new PixelPos());
final int x = MathUtils.floorInt(rasterPos.getX());
final int y = MathUtils.floorInt(rasterPos.getY());
final int width = grid.getRasterWidth();
final int height = grid.getRasterHeight();
if (x < 0 || x >= width || y < 0 || y >= height) {
return "No-data";
}
try {
float[] value = null;
value = grid.readPixels(x, y, 1, 1, value, ProgressMonitor.NULL);
return value[0];
} catch (IOException ignored) {
return "I/O-error";
}
}
return "";
}
@Override
public void setValueAt(Object value, int rowIndex, int columnIndex) {
if (value == null) {
return;
}
if (columnIndex < getStandardColumnNames().length) {
Placemark placemark = placemarkList.get(rowIndex);
if (columnIndex == 0) {
setPixelPosX(value, placemark);
} else if (columnIndex == 1) {
setPixelPosY(value, placemark);
} else if (columnIndex == 2) {
this.setGeoPosLon(value, placemark);
} else if (columnIndex == 3) {
setGeoPosLat(value, placemark);
} else if (columnIndex == getStandardColumnNames().length - 1) {
String strValue = value.toString();
placemark.setLabel(strValue);
} else {
throw new IllegalStateException(
"Column[" + columnIndex + "] '" + getColumnName(columnIndex) + "' is not editable");
}
}
}
public void dispose() {
if (product != null) {
product.removeProductNodeListener(placemarkListener);
}
selectedBands = null;
selectedGrids = null;
placemarkList.clear();
}
protected void setGeoPosLat(Object lat, Placemark placemark) {
double lon = placemark.getGeoPos() == null ? Double.NaN : placemark.getGeoPos().lon;
placemark.setGeoPos(new GeoPos((Double) lat, lon));
}
protected void setGeoPosLon(Object lon, Placemark placemark) {
double lat = placemark.getGeoPos() == null ? Double.NaN : placemark.getGeoPos().lat;
placemark.setGeoPos(new GeoPos(lat, (Double) lon));
}
protected void setPixelPosY(Object value, Placemark placemark) {
double pixelX = placemark.getPixelPos() == null ? -1 : placemark.getPixelPos().x;
placemark.setPixelPos(new PixelPos(pixelX, (Double) value));
}
protected void setPixelPosX(Object value, Placemark placemark) {
double pixelY = placemark.getPixelPos() == null ? -1 : placemark.getPixelPos().y;
placemark.setPixelPos(new PixelPos((Double) value, pixelY));
}
private void initSelectedBands(Band[] selectedBands) {
this.selectedBands = selectedBands != null ? selectedBands : new Band[0];
}
private void initSelectedGrids(TiePointGrid[] selectedGrids) {
this.selectedGrids = selectedGrids != null ? selectedGrids : new TiePointGrid[0];
}
private void initPlacemarkList(Product product) {
if (product != null) {
Placemark[] placemarks = placemarkDescriptor.getPlacemarkGroup(product).toArray(new Placemark[0]);
placemarkList.addAll(Arrays.asList(placemarks));
}
}
private int getNumSelectedBands() {
return selectedBands != null ? selectedBands.length : 0;
}
private class PlacemarkListener extends ProductNodeListenerAdapter {
@Override
public void nodeChanged(ProductNodeEvent event) {
fireTableDataChanged(event);
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
if (event.getSourceNode() instanceof Band) {
Band sourceBand = (Band) event.getSourceNode();
if (selectedBands != null) {
for (Band band : selectedBands) {
if (band == sourceBand) {
AbstractPlacemarkTableModel.this.fireTableDataChanged();
return;
}
}
}
}
if (event.getSourceNode() instanceof TiePointGrid) {
TiePointGrid sourceTPG = (TiePointGrid) event.getSourceNode();
if (selectedGrids != null) {
for (TiePointGrid tpg : selectedGrids) {
if (tpg == sourceTPG) {
AbstractPlacemarkTableModel.this.fireTableDataChanged();
return;
}
}
}
}
}
private void fireTableDataChanged(ProductNodeEvent event) {
if (event.getSourceNode() instanceof Placemark) {
Placemark placemark = (Placemark) event.getSourceNode();
// BEAM-1117: VISAT slows down using pins with GCP geo-coded images
final int index = placemarkList.indexOf(placemark);
if (index != -1) {
AbstractPlacemarkTableModel.this.fireTableRowsUpdated(index, index);
}
}
}
}
}
| 15,708 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataLayerType.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/VectorDataLayerType.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.ui.product;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.core.Assert;
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.ProductNode;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.layer.ProductLayerContext;
/**
* A {@link LayerType} that creates layers of type {@link VectorDataLayer} for a given {@code VectorDataNode}.
*
* @author Marco Peters
* @author Norman Fomferra
* @author Ralf Quast
* @since BEAM 4.7
*/
@LayerTypeMetadata(name = "VectorDataLayerType",
aliasNames = {"VectorDataLayerType"})
public class VectorDataLayerType extends LayerType {
public static final String PROPERTY_NAME_VECTOR_DATA = "vectorData";
public static final String VECTOR_DATA_LAYER_ID_PREFIX = "org.esa.snap.layers.vectorData";
public static VectorDataLayer createLayer(LayerContext ctx, VectorDataNode vectorDataNode) {
Assert.notNull(ctx, "ctx");
final ProductLayerContext plc = (ProductLayerContext) ctx;
final VectorDataLayerType specialLayerType = vectorDataNode.getExtension(VectorDataLayerType.class);
final VectorDataLayer layer;
if (specialLayerType != null) {
layer = specialLayerType.createLayerInternal(plc, vectorDataNode);
} else {
final VectorDataLayerType fallbackLayerType = LayerTypeRegistry.getLayerType(VectorDataLayerType.class);
if (fallbackLayerType == null) {
throw new IllegalStateException("fallbackLayerType == null (missing default VectorDataLayerType)");
}
layer = fallbackLayerType.createLayerInternal(plc, vectorDataNode);
}
return layer;
}
@Override
public boolean isValidFor(LayerContext ctx) {
return ctx instanceof ProductLayerContext;
}
@Override
public Layer createLayer(LayerContext ctx, PropertySet configuration) {
Assert.notNull(ctx, "ctx");
final ProductLayerContext plc = (ProductLayerContext) ctx;
final String vectorDataName = (String) configuration.getValue(PROPERTY_NAME_VECTOR_DATA);
final VectorDataNode vectorDataNode = plc.getProduct().getVectorDataGroup().get(vectorDataName);
Assert.notNull(vectorDataNode, String.format("VectorDataNode '%s' does not exist", vectorDataName));
final ProductNode productNode = plc.getProductNode();
assert(productNode instanceof RasterDataNode);
return createLayer(vectorDataNode, (RasterDataNode) productNode, configuration);
}
@Override
public PropertySet createLayerConfig(LayerContext ctx) {
return createLayerConfig();
}
public static PropertySet createLayerConfig() {
final PropertyContainer configuration = new PropertyContainer();
configuration.addProperty(Property.create(VectorDataLayerType.PROPERTY_NAME_VECTOR_DATA, String.class));
return configuration;
}
protected VectorDataLayer createLayer(VectorDataNode vectorDataNode, RasterDataNode rasterDataNode, PropertySet configuration) {
return new VectorDataLayer(this, vectorDataNode, rasterDataNode, configuration);
}
private VectorDataLayer createLayerInternal(ProductLayerContext ctx, VectorDataNode vectorDataNode) {
final PropertySet configuration = createLayerConfig(ctx);
// Save the name of the vectorDataNode, so that we can reconstruct the layer later (e.g. if loaded from session file).
configuration.setValue(PROPERTY_NAME_VECTOR_DATA, vectorDataNode.getName());
final ProductNode productNode = ctx.getProductNode();
assert(productNode instanceof RasterDataNode);
return createLayer(vectorDataNode, (RasterDataNode) productNode, configuration);
}
}
| 4,821 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleFeaturePointFigure.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/SimpleFeaturePointFigure.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.ui.product;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.swing.figure.AbstractPointFigure;
import com.bc.ceres.swing.figure.FigureStyle;
import com.bc.ceres.swing.figure.Handle;
import com.bc.ceres.swing.figure.Symbol;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import com.bc.ceres.swing.figure.support.NamedSymbol;
import com.bc.ceres.swing.figure.support.PointHandle;
import com.bc.ceres.swing.figure.support.ShapeSymbol;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.impl.CoordinateArraySequence;
import org.esa.snap.core.datamodel.Placemark;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.util.AwtGeomToJtsGeomConverter;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.operation.TransformException;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.font.GlyphVector;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
/**
* A figure representing point features.
*
* @author Norman Fomferra
*/
public class SimpleFeaturePointFigure extends AbstractPointFigure implements SimpleFeatureFigure {
private static final Font labelFont = new Font("Helvetica", Font.BOLD, 14);
private static final int[] labelOutlineAlphas = new int[]{64, 128, 192, 255};
private static final Stroke[] labelOutlineStrokes = new Stroke[labelOutlineAlphas.length];
private static final Color[] labelOutlineColors = new Color[labelOutlineAlphas.length];
private static final Color labelFontColor = Color.WHITE;
private static final Color labelOutlineColor = Color.BLACK;
private static final String[] labelAttributeNames = new String[] {
Placemark.PROPERTY_NAME_LABEL,
"Label",
};
private SceneTransformProvider sceneTransformProvider;
private SimpleFeature simpleFeature;
private Point geometry;
static {
for (int i = 0; i < labelOutlineAlphas.length; i++) {
labelOutlineStrokes[i] = new BasicStroke((labelOutlineAlphas.length - i));
labelOutlineColors[i] = new Color(labelOutlineColor.getRed(),
labelOutlineColor.getGreen(),
labelOutlineColor.getBlue(),
labelOutlineAlphas[i]);
}
}
public SimpleFeaturePointFigure(SimpleFeature simpleFeature, SceneTransformProvider provider, FigureStyle style) {
this(simpleFeature, provider, style, style);
}
public SimpleFeaturePointFigure(SimpleFeature simpleFeature, SceneTransformProvider provider,
FigureStyle normalStyle, FigureStyle selectedStyle) {
super(normalStyle, selectedStyle);
this.simpleFeature = simpleFeature;
sceneTransformProvider = provider;
Object o = simpleFeature.getDefaultGeometry();
if (!(o instanceof Point)) {
throw new IllegalArgumentException("simpleFeature");
}
setGeometry((Point) o);
setSelectable(true);
}
@Override
public Object createMemento() {
return getGeometry().clone();
}
@Override
public void setMemento(Object memento) {
Point point = (Point) memento;
simpleFeature.setDefaultGeometry(point);
forceRegeneration();
fireFigureChanged();
}
@Override
public SimpleFeature getSimpleFeature() {
return simpleFeature;
}
@Override
public Point getGeometry() {
return (Point) simpleFeature.getDefaultGeometry();
}
@Override
public void setGeometry(Geometry geometry) {
Point point = (Point) geometry;
final Point2D.Double sceneCoords = new Point2D.Double(point.getX(), point.getY());
Point2D.Double modelCoords = new Point2D.Double();
Coordinate coordinate;
try {
sceneTransformProvider.getSceneToModelTransform().transform(sceneCoords, modelCoords);
coordinate = new Coordinate(modelCoords.getX(), modelCoords.getY());
} catch (TransformException e) {
coordinate = new Coordinate(Double.NaN, Double.NaN);
}
this.geometry = new Point(new CoordinateArraySequence(new Coordinate[]{coordinate}), point.getFactory());
}
@Override
public void forceRegeneration() {
setGeometry((Geometry) simpleFeature.getDefaultGeometry());
}
@Override
public double getX() {
return geometry.getX();
}
@Override
public double getY() {
return geometry.getY();
}
@Override
public void setLocation(double x, double y) {
Coordinate coordinate = geometry.getCoordinate();
coordinate.x = x;
coordinate.y = y;
final Point2D.Double modelCoords = new Point2D.Double(x, y);
final Point2D.Double sceneCoords = new Point2D.Double();
try {
sceneTransformProvider.getModelToSceneTransform().transform(modelCoords, sceneCoords);
simpleFeature.setDefaultGeometry(new AwtGeomToJtsGeomConverter().createPoint(sceneCoords));
} catch (TransformException e) {
coordinate.x = Double.NaN;
coordinate.y = Double.NaN;
}
geometry.geometryChanged();
fireFigureChanged();
}
@Override
public double getRadius() {
return 1E-10; // = any small, non-zero value will be ok
}
@Override
public Object clone() {
SimpleFeaturePointFigure clone = (SimpleFeaturePointFigure) super.clone();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeature.getFeatureType());
builder.init(simpleFeature);
clone.simpleFeature = builder.buildFeature(null);
clone.simpleFeature.setDefaultGeometry(getGeometry().clone());
clone.geometry = (Point) geometry.clone();
clone.sceneTransformProvider = sceneTransformProvider;
return clone;
}
@Override
protected void drawPoint(Rendering rendering) {
super.drawPoint(rendering);
String label = getLabel();
if (label != null && !label.trim().isEmpty()) {
drawLabel(rendering, label);
}
}
private String getLabel() {
for (String labelAttributeName : labelAttributeNames) {
Object labelAttribute = simpleFeature.getAttribute(labelAttributeName);
if (labelAttribute instanceof String) {
return (String) labelAttribute;
}
}
return null;
}
private void drawLabel(Rendering rendering, String label) {
final Graphics2D graphics = rendering.getGraphics();
final Font oldFont = graphics.getFont();
final Stroke oldStroke = graphics.getStroke();
final Paint oldPaint = graphics.getPaint();
try {
graphics.setFont(labelFont);
GlyphVector glyphVector = labelFont.createGlyphVector(graphics.getFontRenderContext(), label);
Rectangle2D logicalBounds = glyphVector.getLogicalBounds();
float tx = (float) (logicalBounds.getX() - 0.5 * logicalBounds.getWidth());
float ty = (float) (getSymbol().getBounds().getMaxY() + logicalBounds.getHeight() + 1.0);
Shape labelOutline = glyphVector.getOutline(tx, ty);
for (int i = 0; i < labelOutlineAlphas.length; i++) {
graphics.setStroke(labelOutlineStrokes[i]);
graphics.setPaint(labelOutlineColors[i]);
graphics.draw(labelOutline);
}
graphics.setPaint(labelFontColor);
graphics.fill(labelOutline);
} finally {
graphics.setPaint(oldPaint);
graphics.setStroke(oldStroke);
graphics.setFont(oldFont);
}
}
@Override
public int getMaxSelectionStage() {
return 1;
}
@Override
public Handle[] createHandles(int selectionStage) {
if (selectionStage == 1) {
DefaultFigureStyle handleStyle = new DefaultFigureStyle();
handleStyle.setStrokeColor(Color.YELLOW);
handleStyle.setStrokeOpacity(0.8);
handleStyle.setStrokeWidth(1.0);
handleStyle.setFillColor(Color.YELLOW);
handleStyle.setFillOpacity(0.4);
Symbol symbol = getSymbol();
if (symbol instanceof NamedSymbol) {
NamedSymbol namedSymbol = (NamedSymbol) symbol;
symbol = namedSymbol.getSymbol();
}
if (symbol instanceof ShapeSymbol) {
ShapeSymbol shapeSymbol = (ShapeSymbol) symbol;
return new Handle[]{new PointHandle(this, handleStyle, shapeSymbol.getShape())};
}
return new Handle[]{new PointHandle(this, handleStyle)};
}
return super.createHandles(selectionStage);
}
}
| 9,944 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultBandChoosingStrategy.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/DefaultBandChoosingStrategy.java | package org.esa.snap.ui.product;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.ui.GridBagUtils;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
public class DefaultBandChoosingStrategy implements BandChoosingStrategy {
// @todo 3 nf/se - see ProductSubsetDialog for a similar declarations (code smell!)
private static final Font SMALL_PLAIN_FONT = new Font("SansSerif", Font.PLAIN, 10);
private static final Font SMALL_ITALIC_FONT = SMALL_PLAIN_FONT.deriveFont(Font.ITALIC);
private Band[] allBands;
private Band[] selectedBands;
private TiePointGrid[] allTiePointGrids;
private TiePointGrid[] selectedTiePointGrids;
private boolean multipleProducts;
private int numSelected;
private JCheckBox[] checkBoxes;
private JCheckBox selectAllCheckBox;
private JCheckBox selectNoneCheckBox;
public DefaultBandChoosingStrategy(Band[] allBands, Band[] selectedBands, TiePointGrid[] allTiePointGrids,
TiePointGrid[] selectedTiePointGrids, boolean multipleProducts) {
this.allBands = allBands;
this.selectedBands = selectedBands;
this.allTiePointGrids = allTiePointGrids;
this.selectedTiePointGrids = selectedTiePointGrids;
if (this.allBands == null) {
this.allBands = new Band[0];
}
if (this.selectedBands == null) {
this.selectedBands = new Band[0];
}
if (this.allTiePointGrids == null) {
this.allTiePointGrids = new TiePointGrid[0];
}
if (this.selectedTiePointGrids == null) {
this.selectedTiePointGrids = new TiePointGrid[0];
}
BandSorter.sort(allBands);
this.multipleProducts = multipleProducts;
}
@Override
public Band[] getSelectedBands() {
checkSelectedBandsAndGrids();
return selectedBands;
}
@Override
public TiePointGrid[] getSelectedTiePointGrids() {
checkSelectedBandsAndGrids();
return selectedTiePointGrids;
}
@Override
public JPanel createCheckersPane() {
int length = 0;
if (allBands != null) {
length += allBands.length;
}
if (allTiePointGrids != null) {
length += allTiePointGrids.length;
}
checkBoxes = new JCheckBox[length];
final JPanel checkersPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = GridBagUtils.createConstraints("insets.left=4,anchor=NORTHWEST,fill=HORIZONTAL");
final ActionListener checkListener = createActionListener();
addBandCheckers(new StringBuffer(), checkersPane, gbc, checkListener);
addTiePointCheckers(new StringBuffer(), checkersPane, gbc, checkListener);
GridBagUtils.addVerticalFiller(checkersPane, gbc);
return checkersPane;
}
private void addBandCheckers(final StringBuffer description, final JPanel checkersPane,
final GridBagConstraints gbc, final ActionListener checkListener) {
for (int i = 0; i < allBands.length; i++) {
Band band = allBands[i];
boolean checked = false;
for (Band selectedBand : selectedBands) {
if (band == selectedBand) {
checked = true;
numSelected++;
break;
}
}
description.setLength(0);
description.append(band.getDescription() == null ? "" : band.getDescription());
if (band.getSpectralWavelength() > 0.0) {
description.append(" (");
description.append(band.getSpectralWavelength());
description.append(" nm)");
}
final JCheckBox check = new JCheckBox(getRasterDisplayName(band), checked);
check.setFont(SMALL_PLAIN_FONT);
check.addActionListener(checkListener);
final JLabel label = new JLabel(description.toString());
label.setFont(SMALL_ITALIC_FONT);
gbc.gridy++;
GridBagUtils.addToPanel(checkersPane, check, gbc, "weightx=0,gridx=0");
GridBagUtils.addToPanel(checkersPane, label, gbc, "weightx=1,gridx=1");
checkBoxes[i] = check;
}
}
private void addTiePointCheckers(final StringBuffer description, final JPanel checkersPane,
final GridBagConstraints gbc, final ActionListener checkListener) {
for (int i = 0; i < allTiePointGrids.length; i++) {
TiePointGrid grid = allTiePointGrids[i];
boolean checked = false;
for (TiePointGrid selectedGrid : selectedTiePointGrids) {
if (grid == selectedGrid) {
checked = true;
numSelected++;
break;
}
}
description.setLength(0);
description.append(grid.getDescription() == null ? "" : grid.getDescription());
final JCheckBox check = new JCheckBox(getRasterDisplayName(grid), checked);
check.setFont(SMALL_PLAIN_FONT);
check.addActionListener(checkListener);
final JLabel label = new JLabel(description.toString());
label.setFont(SMALL_ITALIC_FONT);
gbc.gridy++;
GridBagUtils.addToPanel(checkersPane, check, gbc, "weightx=0,gridx=0");
GridBagUtils.addToPanel(checkersPane, label, gbc, "weightx=1,gridx=1");
checkBoxes[i + allBands.length] = check;
}
}
private String getRasterDisplayName(RasterDataNode rasterDataNode) {
return multipleProducts ? rasterDataNode.getDisplayName() : rasterDataNode.getName();
}
private ActionListener createActionListener() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
final JCheckBox check = (JCheckBox) e.getSource();
if (check.isSelected()) {
numSelected++;
} else {
numSelected--;
}
updateCheckBoxStates();
}
};
}
public void updateCheckBoxStates() {
selectAllCheckBox.setSelected(numSelected == checkBoxes.length);
selectAllCheckBox.setEnabled(numSelected < checkBoxes.length);
selectAllCheckBox.updateUI();
selectNoneCheckBox.setSelected(numSelected == 0);
selectNoneCheckBox.setEnabled(numSelected > 0);
selectNoneCheckBox.updateUI();
}
@Override
public void setCheckBoxes(JCheckBox selectAllCheckBox, JCheckBox selectNoneCheckBox) {
this.selectAllCheckBox = selectAllCheckBox;
this.selectNoneCheckBox = selectNoneCheckBox;
updateCheckBoxStates();
}
@Override
public void selectAll() {
select(true);
}
@Override
public void selectNone() {
select(false);
}
@Override
public boolean atLeastOneBandSelected() {
checkSelectedBandsAndGrids();
return selectedBands.length > 0;
}
@Override
public void selectRasterDataNodes(String[] nodeNames) {
for (int i = 0; i < allBands.length; i++) {
Band band = allBands[i];
for (String nodeName : nodeNames) {
if (nodeName.equals(band.getName())) {
checkBoxes[i].setSelected(true);
numSelected++;
break;
}
}
}
for (int i = 0; i < allTiePointGrids.length; i++) {
TiePointGrid grid = allTiePointGrids[i];
for (String nodeName : nodeNames) {
if (nodeName.equals(grid.getName())) {
checkBoxes[allBands.length + i].setSelected(true);
numSelected++;
break;
}
}
}
updateCheckBoxStates();
}
private void checkSelectedBandsAndGrids() {
final List<Band> bands = new ArrayList<>();
final List<TiePointGrid> grids = new ArrayList<>();
for (int i = 0; i < checkBoxes.length; i++) {
JCheckBox checkBox = checkBoxes[i];
if (checkBox.isSelected()) {
if (allBands.length > i) {
bands.add(allBands[i]);
} else {
grids.add(allTiePointGrids[i - allBands.length]);
}
}
}
selectedBands = bands.toArray(new Band[bands.size()]);
selectedTiePointGrids = grids.toArray(new TiePointGrid[grids.size()]);
}
private void select(boolean b) {
for (JCheckBox checkBox : checkBoxes) {
if (b && !checkBox.isSelected()) {
numSelected++;
}
if (!b && checkBox.isSelected()) {
numSelected--;
}
checkBox.setSelected(b);
}
updateCheckBoxStates();
}
}
| 9,539 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SourceProductList.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/SourceProductList.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.ui.product;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.core.Assert;
import com.bc.ceres.swing.binding.ComponentAdapter;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductFilter;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.util.Debug;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.BoxLayout;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListDataListener;
import javax.swing.event.ListSelectionListener;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.io.File;
/**
* Enables clients to create a component for choosing source products. The list of source products can arbitrarily be
* composed of
* <ul>
* <li>currently opened products</li>
* <li>single products anywhere in the file system</li>
* <li>whole directories anywhere in the file system and</li>
* <li>recursive directories anywhere in the file system</li>
* </ul>
* <p>
* The file paths the user chooses are stored as objects of type {@link java.io.File} within the property that is passed
* into the constructor. Products that are chosen from the product tree can be retrieved via
* {@link #getSourceProducts()}. So, clients of these must take care that the value in the given property is taken into
* account as well as the return value of that method.
*
* The property that serves as target container for the source product paths must be of type
* {@code String[].class}. Changes in the list are synchronised with the property. If the changes of the property
* values outside this component shall be synchronised with the list, it is necessary that the property lies within a
* property container.
*
* @author thomas
*/
public class SourceProductList extends ComponentAdapter {
private final AppContext appContext;
private final InputListModel listModel;
private final JList inputPathsList;
private String propertyNameLastOpenInputDir;
private String propertyNameLastOpenedFormat;
private String propertyNameFormatNames;
private boolean xAxis;
private JComponent[] components;
private ProductFilter productFilter;
private String defaultPattern;
/**
* Constructor.
*
* @param appContext The context of the app using this component.
*
*/
public SourceProductList(AppContext appContext) {
this.appContext = appContext;
this.listModel = new InputListModel();
this.inputPathsList = createInputPathsList(listModel);
this.propertyNameLastOpenInputDir = "org.esa.snap.core.ui.product.lastOpenInputDir";
this.propertyNameLastOpenedFormat = "org.esa.snap.core.ui.product.lastOpenedFormat";
this.propertyNameFormatNames = "org.esa.snap.core.ui.product.formatNames";
this.xAxis = true;
this.defaultPattern = null;
productFilter = product -> true;
}
/**
* Creates an array of two JPanels. The first panel contains a list displaying the chosen products. The second panel
* contains buttons for adding and removing products, laid out in vertical direction. Note that it makes only sense
* to use both components.
*
* @return an array of two JPanels.
*/
@Override
public JComponent[] getComponents() {
if (components == null) {
components = createComponents();
}
return components;
}
/**
* Creates an array of two JPanels. The first panel contains a list displaying the chosen products. The second panel
* contains buttons for adding and removing products, laid out in configurable direction. Note that it makes only sense
* to use both components.
*
* @return an array of two JPanels.
*/
private JComponent[] createComponents() {
JPanel listPanel = new JPanel(new BorderLayout());
final JScrollPane scrollPane = new JScrollPane(inputPathsList);
scrollPane.setPreferredSize(new Dimension(100, 50));
listPanel.add(scrollPane, BorderLayout.CENTER);
final JPanel addRemoveButtonPanel = new JPanel();
int axis = this.xAxis ? BoxLayout.X_AXIS : BoxLayout.Y_AXIS;
final BoxLayout buttonLayout = new BoxLayout(addRemoveButtonPanel, axis);
addRemoveButtonPanel.setLayout(buttonLayout);
addRemoveButtonPanel.add(createAddInputButton());
addRemoveButtonPanel.add(createRemoveInputButton());
JPanel[] panels = new JPanel[2];
panels[0] = listPanel;
panels[1] = addRemoveButtonPanel;
return panels;
}
/**
* Clears the list of source products.
*/
public void clear() {
listModel.clear();
}
/**
* Allows clients to add single products.
*
* @param product A product to add.
*/
public void addProduct(Product product) {
if (product != null) {
try {
listModel.addElements(product);
} catch (ValidationException ve) {
Debug.trace(ve);
}
}
}
/**
* Returns those source products that have been chosen from the product tree.
*
* @return An array of source products.
*/
public Product[] getSourceProducts() {
return listModel.getSourceProducts();
}
private JList<Object> createInputPathsList(InputListModel inputListModel) {
JList<Object> list = new JList<>(inputListModel);
list.setCellRenderer(new SourceProductListRenderer());
list.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
return list;
}
/**
* If set, users will be asked whether to use this pattern for recursively collecting products from directories.
* To unset this, pass {@code null} as pattern.
* @since SNAP 3.2
*
* @param pattern The pattern to be used when collecting products from directories
*/
public void setDefaultPattern(String pattern) {
this.defaultPattern = pattern;
}
private AbstractButton createAddInputButton() {
final AbstractButton addButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Plus24.gif"),
false);
addButton.addActionListener(e -> {
final JPopupMenu popup = new JPopupMenu("Add");
final Rectangle buttonBounds = addButton.getBounds();
final AddProductAction addProductAction = new AddProductAction(appContext, listModel);
addProductAction.setProductFilter(productFilter);
popup.add(addProductAction);
popup.add(new AddFileAction(appContext, listModel, propertyNameLastOpenInputDir, propertyNameLastOpenedFormat, propertyNameFormatNames));
popup.add(new AddDirectoryAction(appContext, listModel, false, propertyNameLastOpenInputDir, defaultPattern));
popup.add(new AddDirectoryAction(appContext, listModel, true, propertyNameLastOpenInputDir, defaultPattern));
popup.show(addButton, 1, buttonBounds.height + 1);
});
return addButton;
}
private AbstractButton createRemoveInputButton() {
final AbstractButton removeButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Minus24.gif"),
false);
removeButton.addActionListener(e -> listModel.removeElementsAt(inputPathsList.getSelectedIndices()));
return removeButton;
}
@Override
public void bindComponents() {
String propertyName = getBinding().getPropertyName();
Property property = getBinding().getContext().getPropertySet().getProperty(propertyName);
Assert.argument(property.getType().equals(String[].class), "property '" + propertyName +"' must be of type String[].class");
listModel.setProperty(property);
}
@Override
public void unbindComponents() {
listModel.setProperty(null);
}
@Override
public void adjustComponents() {
}
/**
* Add a listener that is informed every time the list's contents change.
* @param changeListener the listener to add
*/
public void addChangeListener(ListDataListener changeListener) {
listModel.addListDataListener(changeListener);
}
/**
* Remove a change listener
* @param changeListener the listener to remove
*/
public void removeChangeListener(ListDataListener changeListener) {
listModel.removeListDataListener(changeListener);
}
/**
* Add a listener that is informed every time the list's selection is changed.
* @since SNAP 3.2
* @param selectionListener the listener to add
*/
public void addSelectionListener(ListSelectionListener selectionListener) {
inputPathsList.addListSelectionListener(selectionListener);
}
/**
* Remove a selection listener
* @since SNAP 3.2
*
* @param selectionListener the listener to remove
*/
public void removeSelectionListener(ListSelectionListener selectionListener) {
inputPathsList.removeListSelectionListener(selectionListener);
}
/**
* @since SNAP 3.2
* @param object the object which may be selected or not
* @return true, if the object is selected
*/
public boolean isSelected(Object object) {
return inputPathsList.isSelectedIndex(listModel.getIndexOf(object));
}
/**
* The filter to be used to filter the list of opened products which are offered to the user for selection.
* @param productFilter the filter
*/
public void setProductFilter(ProductFilter productFilter) {
this.productFilter = productFilter;
}
/**
* Setter for property name indicating the last directory the user has opened
*
* @param propertyNameLastOpenedFormat property name indicating the last directory the user has opened
*/
public void setPropertyNameLastOpenedFormat(String propertyNameLastOpenedFormat) {
this.propertyNameLastOpenedFormat = propertyNameLastOpenedFormat;
}
/**
* Setter for property name indicating the last product format the user has opened
* @param propertyNameLastOpenInputDir property name indicating the last product format the user has opened
*/
public void setPropertyNameLastOpenInputDir(String propertyNameLastOpenInputDir) {
this.propertyNameLastOpenInputDir = propertyNameLastOpenInputDir;
}
/**
* Setter for property name which defines the formats offered to the user.
* The value of the list should be a comma separated list of formats.
* If the property is not set, all formats will be offered.
*
* @param formatNamesKey property name
*/
public void setPropertyNameFormatNames(String formatNamesKey) {
this.propertyNameFormatNames = formatNamesKey;
}
/**
* Setter for xAxis property.
*
* @param xAxis {@code true} if the buttons on the second panel shall be laid out in horizontal direction
*/
public void setXAxis(boolean xAxis) {
this.xAxis = xAxis;
}
private static class SourceProductListRenderer 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;
if (value instanceof File) {
text = ((File) value).getAbsolutePath();
} else {
text = ((ProductNode) value).getDisplayName();
}
label.setText(text);
label.setToolTipText(text);
return label;
}
}
}
| 13,128 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductSceneImage.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ProductSceneImage.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.ui.product;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerFilter;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.glayer.support.LayerUtils;
import org.esa.snap.core.datamodel.GcpDescriptor;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.datamodel.Mask;
import org.esa.snap.core.datamodel.PinDescriptor;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.image.ColoredBandImageMultiLevelSource;
import org.esa.snap.core.layer.GraticuleLayer;
import org.esa.snap.core.layer.GraticuleLayerType;
import org.esa.snap.core.layer.MaskCollectionLayerType;
import org.esa.snap.core.layer.MaskLayerType;
import org.esa.snap.core.layer.NoDataLayerType;
import org.esa.snap.core.layer.ProductLayerContext;
import org.esa.snap.core.layer.RasterImageLayerType;
import org.esa.snap.core.layer.RgbImageLayerType;
import org.esa.snap.core.util.PropertyMap;
import java.awt.Color;
import java.awt.geom.AffineTransform;
// SEP2018 - Daniel Knowles - added multiple new properties to the Graticule layer configuration
public class ProductSceneImage implements ProductLayerContext {
private static final ImageLayerFilter IMAGE_LAYER_FILTER = new ImageLayerFilter();
private final String name;
private final PropertyMap configuration;
private RasterDataNode[] rasters;
private Layer rootLayer;
private ColoredBandImageMultiLevelSource coloredBandImageMultiLevelSource;
/**
* Creates a color indexed product scene for the given product raster.
*
* @param raster the product raster, must not be null
* @param configuration a configuration
* @param pm a monitor to inform the user about progress @return a color indexed product scene image
*/
public ProductSceneImage(RasterDataNode raster, PropertyMap configuration, ProgressMonitor pm) {
this(raster.getDisplayName(),
new RasterDataNode[]{raster},
configuration);
coloredBandImageMultiLevelSource = ColoredBandImageMultiLevelSource.create(raster, pm);
initRootLayer();
}
/**
* Creates a new scene image for an existing view.
*
* @param raster The product raster.
* @param view An existing view.
*/
public ProductSceneImage(RasterDataNode raster, ProductSceneView view) {
this(raster.getDisplayName(),
new RasterDataNode[]{raster},
view.getSceneImage().getConfiguration());
coloredBandImageMultiLevelSource = view.getSceneImage().getColoredBandImageMultiLevelSource();
initRootLayer();
}
/**
* Creates an RGB product scene for the given raster datasets.
*
* @param name the name of the scene view
* @param redRaster the product raster used for the red color component, must not be null
* @param greenRaster the product raster used for the green color component, must not be null
* @param blueRaster the product raster used for the blue color component, must not be null
* @param configuration a configuration
* @param pm a monitor to inform the user about progress @return an RGB product scene image @throws java.io.IOException if the image creation failed due to an I/O problem
*/
public ProductSceneImage(String name, RasterDataNode redRaster,
RasterDataNode greenRaster,
RasterDataNode blueRaster,
PropertyMap configuration,
ProgressMonitor pm) {
this(name, new RasterDataNode[]{redRaster, greenRaster, blueRaster}, configuration);
coloredBandImageMultiLevelSource = ColoredBandImageMultiLevelSource.create(rasters, pm);
initRootLayer();
}
private ProductSceneImage(String name, RasterDataNode[] rasters, PropertyMap configuration) {
this.name = name;
this.rasters = rasters;
this.configuration = configuration;
}
public PropertyMap getConfiguration() {
return configuration;
}
public String getName() {
return name;
}
public ImageInfo getImageInfo() {
return coloredBandImageMultiLevelSource.getImageInfo();
}
public void setImageInfo(ImageInfo imageInfo) {
coloredBandImageMultiLevelSource.setImageInfo(imageInfo);
}
public RasterDataNode[] getRasters() {
return rasters;
}
public void setRasters(RasterDataNode[] rasters) {
this.rasters = rasters;
}
@Override
public Object getCoordinateReferenceSystem() {
return getProduct().getSceneCRS();
}
@Override
public Layer getRootLayer() {
return rootLayer;
}
Layer getLayer(String id) {
return LayerUtils.getChildLayerById(getRootLayer(), id);
}
void addLayer(int index, Layer layer) {
rootLayer.getChildren().add(index, layer);
}
int getFirstImageLayerIndex() {
return LayerUtils.getChildLayerIndex(getRootLayer(), LayerUtils.SEARCH_DEEP, 0, IMAGE_LAYER_FILTER);
}
ImageLayer getBaseImageLayer() {
return (ImageLayer) getLayer(ProductSceneView.BASE_IMAGE_LAYER_ID);
}
Layer getNoDataLayer(boolean create) {
Layer layer = getLayer(ProductSceneView.NO_DATA_LAYER_ID);
if (layer == null && create) {
layer = createNoDataLayer();
addLayer(getFirstImageLayerIndex(), layer);
}
return layer;
}
Layer getVectorDataCollectionLayer(boolean create) {
Layer layer = getLayer(ProductSceneView.VECTOR_DATA_LAYER_ID);
if (layer == null && create) {
layer = createVectorDataCollectionLayer();
addLayer(getFirstImageLayerIndex(), layer);
}
return layer;
}
Layer getMaskCollectionLayer(boolean create) {
Layer layer = getLayer(ProductSceneView.MASKS_LAYER_ID);
if (layer == null && create) {
layer = createMaskCollectionLayer();
addLayer(getFirstImageLayerIndex(), layer);
}
return layer;
}
GraticuleLayer getGraticuleLayer(boolean create) {
GraticuleLayer layer = (GraticuleLayer) getLayer(ProductSceneView.GRATICULE_LAYER_ID);
if (layer == null && create) {
layer = createGraticuleLayer(getImageToModelTransform());
addLayer(0, layer);
}
return layer;
}
Layer getGcpLayer(boolean create) {
final Product product = getProduct();
if (product != null) {
final VectorDataNode vectorDataNode = product.getGcpGroup().getVectorDataNode();
final Layer vectorDataCollectionLayer = getVectorDataCollectionLayer(create);
if (vectorDataCollectionLayer != null) {
return LayerUtils.getChildLayer(getRootLayer(),
LayerUtils.SEARCH_DEEP,
VectorDataLayerFilterFactory.createNodeFilter(vectorDataNode));
}
}
return null;
}
Layer getPinLayer(boolean create) {
final Product product = getProduct();
if (product != null) {
final VectorDataNode vectorDataNode = product.getPinGroup().getVectorDataNode();
final Layer vectorDataCollectionLayer = getVectorDataCollectionLayer(create);
if (vectorDataCollectionLayer != null) {
return LayerUtils.getChildLayer(getRootLayer(),
LayerUtils.SEARCH_DEEP,
VectorDataLayerFilterFactory.createNodeFilter(vectorDataNode));
}
}
return null;
}
private RasterDataNode getRaster() {
return rasters[0];
}
private void initRootLayer() {
rootLayer = new CollectionLayer();
addLayer(0, createBaseImageLayer());
}
public void initVectorDataCollectionLayer() {
if (mustEnableVectorDataCollectionLayer()) {
getVectorDataCollectionLayer(true);
}
}
public void initMaskCollectionLayer() {
if (mustEnableMaskCollectionLayer()) {
getMaskCollectionLayer(true);
}
}
private boolean mustEnableVectorDataCollectionLayer() {
return getRaster().getProduct().getVectorDataGroup().getNodeCount() > 0;
}
private boolean mustEnableMaskCollectionLayer() {
return getRaster().getOverlayMaskGroup().getNodeCount() > 0;
}
private AffineTransform getImageToModelTransform() {
return coloredBandImageMultiLevelSource.getModel().getImageToModelTransform(0);
}
private Layer createBaseImageLayer() {
final Layer layer;
if (getRasters().length == 1) {
final RasterImageLayerType type = LayerTypeRegistry.getLayerType(RasterImageLayerType.class);
layer = type.createLayer(getRaster(), coloredBandImageMultiLevelSource);
} else {
final RgbImageLayerType type = LayerTypeRegistry.getLayerType(RgbImageLayerType.class);
layer = type.createLayer(getRasters(), coloredBandImageMultiLevelSource);
}
layer.setName(getName());
layer.setVisible(true);
layer.setId(ProductSceneView.BASE_IMAGE_LAYER_ID);
applyBaseImageLayerStyle(configuration, layer);
return layer;
}
static void applyBaseImageLayerStyle(PropertyMap configuration, Layer layer) {
final boolean borderShown = configuration.getPropertyBool("image.border.shown",
ImageLayer.DEFAULT_BORDER_SHOWN);
final double borderWidth = configuration.getPropertyDouble("image.border.size",
ImageLayer.DEFAULT_BORDER_WIDTH);
final Color borderColor = configuration.getPropertyColor("image.border.color",
ImageLayer.DEFAULT_BORDER_COLOR);
final boolean pixelBorderShown = configuration.getPropertyBool("pixel.border.shown",
ImageLayer.DEFAULT_PIXEL_BORDER_SHOWN);
final double pixelBorderWidth = configuration.getPropertyDouble("pixel.border.size",
ImageLayer.DEFAULT_PIXEL_BORDER_WIDTH);
final Color pixelBorderColor = configuration.getPropertyColor("pixel.border.color",
ImageLayer.DEFAULT_PIXEL_BORDER_COLOR);
final PropertySet layerConfiguration = layer.getConfiguration();
layerConfiguration.setValue(ImageLayer.PROPERTY_NAME_BORDER_SHOWN, borderShown);
layerConfiguration.setValue(ImageLayer.PROPERTY_NAME_BORDER_WIDTH, borderWidth);
layerConfiguration.setValue(ImageLayer.PROPERTY_NAME_BORDER_COLOR, borderColor);
layerConfiguration.setValue(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_SHOWN, pixelBorderShown);
layerConfiguration.setValue(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_WIDTH, pixelBorderWidth);
layerConfiguration.setValue(ImageLayer.PROPERTY_NAME_PIXEL_BORDER_COLOR, pixelBorderColor);
}
private Layer createNoDataLayer() {
final LayerType noDataType = LayerTypeRegistry.getLayerType(NoDataLayerType.class);
final PropertySet configTemplate = noDataType.createLayerConfig(null);
final Color color = configuration.getPropertyColor("noDataOverlay.color", Color.ORANGE);
configTemplate.setValue(NoDataLayerType.PROPERTY_NAME_COLOR, color);
configTemplate.setValue(NoDataLayerType.PROPERTY_NAME_RASTER, getRaster());
final Layer layer = noDataType.createLayer(this, configTemplate);
final double transparency = configuration.getPropertyDouble("noDataOverlay.transparency", 0.3);
layer.setTransparency(transparency);
return layer;
}
private synchronized Layer createVectorDataCollectionLayer() {
final LayerType collectionLayerType = LayerTypeRegistry.getLayerType(VectorDataCollectionLayerType.class);
final Layer collectionLayer = collectionLayerType.createLayer(this, collectionLayerType.createLayerConfig(this));
final ProductNodeGroup<VectorDataNode> vectorDataGroup = getRaster().getProduct().getVectorDataGroup();
final VectorDataNode[] vectorDataNodes = vectorDataGroup.toArray(new VectorDataNode[vectorDataGroup.getNodeCount()]);
for (final VectorDataNode vectorDataNode : vectorDataNodes) {
final Layer layer = VectorDataLayerType.createLayer(this, vectorDataNode);
layer.setVisible(vectorDataNode.getPlacemarkDescriptor() instanceof PinDescriptor ||
vectorDataNode.getPlacemarkDescriptor() instanceof GcpDescriptor);
collectionLayer.getChildren().add(layer);
}
return collectionLayer;
}
private synchronized Layer createMaskCollectionLayer() {
final LayerType maskCollectionType = LayerTypeRegistry.getLayerType(MaskCollectionLayerType.class);
final PropertySet layerConfig = maskCollectionType.createLayerConfig(null);
layerConfig.setValue(MaskCollectionLayerType.PROPERTY_NAME_RASTER, getRaster());
final Layer maskCollectionLayer = maskCollectionType.createLayer(this, layerConfig);
ProductNodeGroup<Mask> productNodeGroup = getRaster().getProduct().getMaskGroup();
final RasterDataNode raster = getRaster();
for (int i = 0; i < productNodeGroup.getNodeCount(); i++) {
final Mask mask = productNodeGroup.get(i);
//todo add all mask layers as soon as the masks have been scaled to fit the raster
if (raster.getRasterSize().equals(mask.getRasterSize())) {
Layer layer = MaskLayerType.createLayer(raster, mask);
maskCollectionLayer.getChildren().add(layer);
}
}
return maskCollectionLayer;
}
static void applyNoDataLayerStyle(PropertyMap configuration, Layer layer) {
final PropertySet layerConfiguration = layer.getConfiguration();
final Color color = configuration.getPropertyColor("noDataOverlay.color", NoDataLayerType.DEFAULT_COLOR);
layerConfiguration.setValue(NoDataLayerType.PROPERTY_NAME_COLOR, color);
final double transparency = configuration.getPropertyDouble("noDataOverlay.transparency", 0.3);
layer.setTransparency(transparency);
}
static void applyFigureLayerStyle(PropertyMap configuration, Layer layer) {
final PropertySet layerConfiguration = layer.getConfiguration();
/*
layerConfiguration.setValue(VectorDataLayer.PROPERTY_NAME_SHAPE_OUTLINED,
configuration.getPropertyBool(VectorDataLayer.PROPERTY_NAME_SHAPE_OUTLINED,
VectorDataLayer.DEFAULT_SHAPE_OUTLINED));
layerConfiguration.setValue(VectorDataLayer.PROPERTY_NAME_SHAPE_OUTL_COLOR,
configuration.getPropertyColor(VectorDataLayer.PROPERTY_NAME_SHAPE_OUTL_COLOR,
VectorDataLayer.DEFAULT_SHAPE_OUTL_COLOR));
layerConfiguration.setValue(VectorDataLayer.PROPERTY_NAME_SHAPE_OUTL_TRANSPARENCY,
configuration.getPropertyDouble(
VectorDataLayer.PROPERTY_NAME_SHAPE_OUTL_TRANSPARENCY,
VectorDataLayer.DEFAULT_SHAPE_OUTL_TRANSPARENCY));
layerConfiguration.setValue(VectorDataLayer.PROPERTY_NAME_SHAPE_OUTL_WIDTH,
configuration.getPropertyDouble(VectorDataLayer.PROPERTY_NAME_SHAPE_OUTL_WIDTH,
VectorDataLayer.DEFAULT_SHAPE_OUTL_WIDTH));
layerConfiguration.setValue(VectorDataLayer.PROPERTY_NAME_SHAPE_FILLED,
configuration.getPropertyBool(VectorDataLayer.PROPERTY_NAME_SHAPE_FILLED,
VectorDataLayer.DEFAULT_SHAPE_FILLED));
layerConfiguration.setValue(VectorDataLayer.PROPERTY_NAME_SHAPE_FILL_COLOR,
configuration.getPropertyColor(VectorDataLayer.PROPERTY_NAME_SHAPE_FILL_COLOR,
VectorDataLayer.DEFAULT_SHAPE_FILL_COLOR));
layerConfiguration.setValue(VectorDataLayer.PROPERTY_NAME_SHAPE_FILL_TRANSPARENCY,
configuration.getPropertyDouble(
VectorDataLayer.PROPERTY_NAME_SHAPE_FILL_TRANSPARENCY,
VectorDataLayer.DEFAULT_SHAPE_FILL_TRANSPARENCY));
*/
}
private GraticuleLayer createGraticuleLayer(AffineTransform i2mTransform) {
final LayerType layerType = LayerTypeRegistry.getLayerType(GraticuleLayerType.class);
final PropertySet template = layerType.createLayerConfig(null);
template.setValue(GraticuleLayerType.PROPERTY_NAME_RASTER, getRaster());
final GraticuleLayer graticuleLayer = (GraticuleLayer) layerType.createLayer(null, template);
graticuleLayer.setId(ProductSceneView.GRATICULE_LAYER_ID);
graticuleLayer.setVisible(false);
graticuleLayer.setName("Graticule");
applyGraticuleLayerStyle(configuration, graticuleLayer);
return graticuleLayer;
}
static void applyGraticuleLayerStyle(PropertyMap configuration, Layer layer) {
final PropertySet layerConfiguration = layer.getConfiguration();
// Added multiple new properties here
// Daniel Knowles - Sept 2018
// Added section break properties
// layerConfiguration.setValue(GraticuleLayerType.PROPERTY_NUM_GRID_LINES_NAME,
// configuration.getPropertyInt(GraticuleLayerType.PROPERTY_NUM_GRID_LINES_NAME,
// GraticuleLayerType.PROPERTY_NUM_GRID_LINES_DEFAULT));
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_NUM_GRID_LINES_NAME,
GraticuleLayerType.PROPERTY_NUM_GRID_LINES_DEFAULT,
GraticuleLayerType.PROPERTY_NUM_GRID_LINES_TYPE);
// Grid Spacing Section
addSectionPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRID_SPACING_SECTION_NAME);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_NAME,
GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_DEFAULT,
GraticuleLayerType.PROPERTY_GRID_SPACING_LAT_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRID_SPACING_LON_NAME,
GraticuleLayerType.PROPERTY_GRID_SPACING_LON_DEFAULT,
GraticuleLayerType.PROPERTY_GRID_SPACING_LON_TYPE);
// Labels Section
addSectionPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_SECTION_NAME);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_NORTH_NAME,
GraticuleLayerType.PROPERTY_LABELS_NORTH_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_NORTH_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_SOUTH_NAME,
GraticuleLayerType.PROPERTY_LABELS_SOUTH_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_SOUTH_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_WEST_NAME,
GraticuleLayerType.PROPERTY_LABELS_WEST_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_WEST_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_EAST_NAME,
GraticuleLayerType.PROPERTY_LABELS_EAST_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_EAST_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_NAME,
GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_SUFFIX_NSWE_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_NAME,
GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_DECIMAL_VALUE_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_NAME,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_INSIDE_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_ITALIC_NAME,
GraticuleLayerType.PROPERTY_LABELS_ITALIC_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_ITALIC_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_BOLD_NAME,
GraticuleLayerType.PROPERTY_LABELS_BOLD_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_BOLD_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_FONT_NAME,
GraticuleLayerType.PROPERTY_LABELS_FONT_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_FONT_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_NAME,
GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_ROTATION_LON_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_NAME,
GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_ROTATION_LAT_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_SIZE_NAME,
GraticuleLayerType.PROPERTY_LABELS_SIZE_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_SIZE_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_LABELS_COLOR_NAME,
GraticuleLayerType.PROPERTY_LABELS_COLOR_DEFAULT,
GraticuleLayerType.PROPERTY_LABELS_COLOR_TYPE);
// Gridlines Section
addSectionPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRIDLINES_SECTION_NAME);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_NAME,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_DEFAULT,
GraticuleLayerType.PROPERTY_GRIDLINES_SHOW_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_NAME,
GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_DEFAULT,
GraticuleLayerType.PROPERTY_GRIDLINES_WIDTH_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_NAME,
GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_DEFAULT,
GraticuleLayerType.PROPERTY_GRIDLINES_DASHED_PHASE_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_NAME,
GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_DEFAULT,
GraticuleLayerType.PROPERTY_GRIDLINES_TRANSPARENCY_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_NAME,
GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_DEFAULT,
GraticuleLayerType.PROPERTY_GRIDLINES_COLOR_TYPE);
// Border Section
addSectionPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_BORDER_SECTION_NAME);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_BORDER_SHOW_NAME,
GraticuleLayerType.PROPERTY_BORDER_SHOW_DEFAULT,
GraticuleLayerType.PROPERTY_BORDER_SHOW_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_BORDER_WIDTH_NAME,
GraticuleLayerType.PROPERTY_BORDER_WIDTH_DEFAULT,
GraticuleLayerType.PROPERTY_BORDER_WIDTH_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_BORDER_COLOR_NAME,
GraticuleLayerType.PROPERTY_BORDER_COLOR_DEFAULT,
GraticuleLayerType.PROPERTY_BORDER_COLOR_TYPE);
// Tickmarks Section
addSectionPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_NAME,
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_DEFAULT,
GraticuleLayerType.PROPERTY_TICKMARKS_SHOW_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_NAME,
GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_DEFAULT,
GraticuleLayerType.PROPERTY_TICKMARKS_INSIDE_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_NAME,
GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_DEFAULT,
GraticuleLayerType.PROPERTY_TICKMARKS_LENGTH_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_NAME,
GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_DEFAULT,
GraticuleLayerType.PROPERTY_TICKMARKS_COLOR_TYPE);
// Corner Labels Section
addSectionPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_CORNER_LABELS_SECTION_NAME);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_NAME,
GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_DEFAULT,
GraticuleLayerType.PROPERTY_CORNER_LABELS_NORTH_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_NAME,
GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_DEFAULT,
GraticuleLayerType.PROPERTY_CORNER_LABELS_WEST_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_NAME,
GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_DEFAULT,
GraticuleLayerType.PROPERTY_CORNER_LABELS_EAST_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_NAME,
GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_DEFAULT,
GraticuleLayerType.PROPERTY_CORNER_LABELS_SOUTH_TYPE);
// Inside Labels Section
addSectionPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_SECTION_NAME);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_NAME,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_DEFAULT,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_TRANSPARENCY_TYPE);
addPropertyToLayerConfiguration(configuration, layer,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_NAME,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_DEFAULT,
GraticuleLayerType.PROPERTY_INSIDE_LABELS_BG_COLOR_TYPE);
}
private static void addPropertyToLayerConfiguration(PropertyMap configuration, Layer layer, String propertyName, Object propertyDefault, Class type) {
final PropertySet layerConfiguration = layer.getConfiguration();
if (type == Boolean.class) {
layerConfiguration.setValue(propertyName,
configuration.getPropertyBool(propertyName, (Boolean) propertyDefault));
} else if (type == Double.class) {
layerConfiguration.setValue(propertyName,
configuration.getPropertyDouble(propertyName, (Double) propertyDefault));
} else if (type == Color.class) {
layerConfiguration.setValue(propertyName,
configuration.getPropertyColor(propertyName, (Color) propertyDefault));
} else if (type == Integer.class) {
layerConfiguration.setValue(propertyName,
configuration.getPropertyInt(propertyName, (Integer) propertyDefault));
} else if (type == String.class) {
layerConfiguration.setValue(propertyName,
configuration.getPropertyString(propertyName, (String) propertyDefault));
}
}
private static void addSectionPropertyToLayerConfiguration(PropertyMap configuration, Layer layer, String propertyName) {
addPropertyToLayerConfiguration(configuration, layer, propertyName, true, Boolean.class);
}
private ColoredBandImageMultiLevelSource getColoredBandImageMultiLevelSource() {
return coloredBandImageMultiLevelSource;
}
@Override
public Product getProduct() {
return getRaster().getProduct();
}
@Override
public ProductNode getProductNode() {
return getRaster();
}
private static class ImageLayerFilter implements LayerFilter {
@Override
public boolean accept(Layer layer) {
return layer instanceof ImageLayer;
}
}
}
| 34,783 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleFeatureFigureFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/SimpleFeatureFigureFactory.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.ui.product;
import com.bc.ceres.swing.figure.FigureFactory;
import com.bc.ceres.swing.figure.FigureStyle;
import com.bc.ceres.swing.figure.PointFigure;
import com.bc.ceres.swing.figure.ShapeFigure;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.Point;
import org.esa.snap.core.datamodel.PlainFeatureFactory;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.util.AwtGeomToJtsGeomConverter;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import org.opengis.referencing.operation.TransformException;
import java.awt.Color;
import java.awt.Shape;
import java.awt.geom.Point2D;
public class SimpleFeatureFigureFactory implements FigureFactory {
private final SimpleFeatureType simpleFeatureType;
private final AwtGeomToJtsGeomConverter toJtsGeom;
private long currentFeatureId;
private SceneTransformProvider sceneTransformProvider;
public SimpleFeatureFigureFactory(SimpleFeatureType simpleFeatureType, SceneTransformProvider provider) {
this.simpleFeatureType = simpleFeatureType;
this.toJtsGeom = new AwtGeomToJtsGeomConverter();
this.currentFeatureId = System.nanoTime();
this.sceneTransformProvider = provider;
}
@Override
public PointFigure createPointFigure(Point2D point, FigureStyle style) {
final Point point1 = toJtsGeom.createPoint(point);
return createPointFigure(point1, style);
}
@Override
public ShapeFigure createLineFigure(Shape shape, FigureStyle style) {
MultiLineString multiLineString = toJtsGeom.createMultiLineString(shape);
Geometry geometry = multiLineString;
if (multiLineString.getNumGeometries() == 1) {
geometry = multiLineString.getGeometryN(0);
}
final Geometry geometryInSceneCoords;
try {
geometryInSceneCoords = sceneTransformProvider.getModelToSceneTransform().transform(geometry);
} catch (TransformException e) {
return null;
}
return createShapeFigure(geometryInSceneCoords, style);
}
@Override
public ShapeFigure createPolygonFigure(Shape shape, FigureStyle style) {
Geometry geometry = toJtsGeom.createPolygon(shape);
try {
geometry = sceneTransformProvider.getModelToSceneTransform().transform(geometry);
} catch (TransformException e) {
return null;
}
return createShapeFigure(geometry, style);
}
private PointFigure createPointFigure(Point geometry, FigureStyle style) {
return new SimpleFeaturePointFigure(createSimpleFeature(geometry), sceneTransformProvider, style);
}
public SimpleFeatureFigure createSimpleFeatureFigure(SimpleFeature simpleFeature, String defaultStyleCss) {
final String css = getStyleCss(simpleFeature, defaultStyleCss);
final FigureStyle normalStyle = DefaultFigureStyle.createFromCss(css);
final FigureStyle selectedStyle = deriveSelectedStyle(normalStyle);
final Object geometry = simpleFeature.getDefaultGeometry();
if (geometry instanceof Point) {
return new SimpleFeaturePointFigure(simpleFeature, sceneTransformProvider, normalStyle, selectedStyle);
} else {
return new SimpleFeatureShapeFigure(simpleFeature, sceneTransformProvider, normalStyle, selectedStyle);
}
}
static String getStyleCss(SimpleFeature simpleFeature, String defaultStyleCss) {
Object styleAttribute = simpleFeature.getAttribute(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS);
if (styleAttribute instanceof String) {
String css = (String) styleAttribute;
if (!css.trim().isEmpty()) {
final StringBuilder sb = new StringBuilder(css);
final String[] cssAttributes = defaultStyleCss.split(";");
for (String cssAttribute : cssAttributes) {
if (!css.contains(cssAttribute.split(":")[0].trim())) {
sb.append(";");
sb.append(cssAttribute);
}
}
return sb.toString();
}
}
return defaultStyleCss;
}
private ShapeFigure createShapeFigure(Geometry geometry, FigureStyle style) {
return new SimpleFeatureShapeFigure(createSimpleFeature(geometry), sceneTransformProvider, style, deriveSelectedStyle(style));
}
private SimpleFeature createSimpleFeature(Geometry geometry) {
return PlainFeatureFactory.createPlainFeature(simpleFeatureType,
"ID" + Long.toHexString(currentFeatureId++),
geometry,
null);
}
public FigureStyle deriveSelectedStyle(FigureStyle style) {
DefaultFigureStyle figureStyle = new DefaultFigureStyle();
figureStyle.setFillColor(style.getFillColor());
figureStyle.setFillOpacity(style.getFillOpacity());
figureStyle.setStrokeColor(Color.YELLOW);
figureStyle.setStrokeOpacity(0.75);
figureStyle.setStrokeWidth(style.getStrokeWidth() + 1.0);
figureStyle.setSymbolName(style.getSymbolName());
figureStyle.setSymbolImagePath(style.getSymbolImagePath());
figureStyle.setSymbolRefX(style.getSymbolRefX());
figureStyle.setSymbolRefY(style.getSymbolRefY());
return figureStyle;
}
}
| 6,418 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GroupedBandChoosingStrategy.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/GroupedBandChoosingStrategy.java | package org.esa.snap.ui.product;
import com.jidesoft.swing.CheckBoxTree;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.ui.GridBagUtils;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.awt.Color;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class GroupedBandChoosingStrategy implements BandChoosingStrategy {
// @todo 3 nf/se - see ProductSubsetDialog for a similar declarations (code smell!)
private static final Font SMALL_PLAIN_FONT = new Font("SansSerif", Font.PLAIN, 10);
private static final Font SMALL_ITALIC_FONT = SMALL_PLAIN_FONT.deriveFont(Font.ITALIC);
private JCheckBox selectAllCheckBox;
private JCheckBox selectNoneCheckBox;
private boolean multipleProducts;
private Product.AutoGrouping autoGrouping;
private CheckBoxTree checkBoxTree;
private final Map<Band, String> allBandsMap;
private final Map<Band, String> selectedBandsMap;
private final Map<TiePointGrid, String> allGridsMap;
private final Map<TiePointGrid, String> selectedGridsMap;
public GroupedBandChoosingStrategy(Band[] allBands, Band[] selectedBands, TiePointGrid[] allTiePointGrids,
TiePointGrid[] selectedTiePointGrids, Product.AutoGrouping autoGrouping, boolean multipleProducts) {
allBandsMap = createBandMap(allBands);
selectedBandsMap = createBandMap(selectedBands);
allGridsMap = createTiepointGridMap(allTiePointGrids);
selectedGridsMap = createTiepointGridMap(selectedTiePointGrids);
this.autoGrouping = autoGrouping;
this.multipleProducts = multipleProducts;
}
private Map<Band, String> createBandMap(Band[] bands) {
final Map<Band, String> bandMap = new TreeMap<>(BandSorter.createComparator());
if (bands != null) {
for (Band band : bands) {
bandMap.put(band, getDisplayDescription(band));
}
}
return bandMap;
}
private Map<TiePointGrid, String> createTiepointGridMap(TiePointGrid[] grids) {
final Map<TiePointGrid, String> gridMap = new TreeMap<>(new Comparator<TiePointGrid>() {
@Override
public int compare(TiePointGrid grid1, TiePointGrid grid2) {
return grid1.getName().compareTo(grid2.getName());
}
});
if (grids != null) {
for (TiePointGrid grid : grids) {
gridMap.put(grid, getDisplayDescription(grid));
}
}
return gridMap;
}
private String getDisplayDescription(RasterDataNode rasterDataNode) {
final String fullName = multipleProducts ? rasterDataNode.getDisplayName() : rasterDataNode.getName();
final StringBuilder description = new StringBuilder();
description.setLength(0);
description.append(fullName);
description.append(rasterDataNode.getDescription() == null ? "" : " (" + rasterDataNode.getDescription());
if (rasterDataNode instanceof Band) {
if (((Band) rasterDataNode).getSpectralWavelength() > 0.0) {
description.append(" (");
description.append(((Band) rasterDataNode).getSpectralWavelength());
description.append(" nm)");
}
}
description.append(")");
return description.toString();
}
@Override
public Band[] getSelectedBands() {
List<Band> selectedBandList = new ArrayList<>();
final TreePath[] selectionPaths = checkBoxTree.getCheckBoxTreeSelectionModel().getSelectionPaths();
TreePath rootPath = new TreePath(checkBoxTree.getModel().getRoot());
for (TreePath selectionPath : selectionPaths) {
if (selectionPath.equals(rootPath)) {
return allBandsMap.keySet().toArray(new Band[allBandsMap.size()]);
}
final DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
if (selectedNode.isLeaf()) {
RasterDataNode key = getKey(selectedNode.getUserObject().toString(), allBandsMap);
if (key != null) {
selectedBandList.add((Band) key);
}
} else {
for (int i = 0; i < selectedNode.getChildCount(); i++) {
final DefaultMutableTreeNode child = (DefaultMutableTreeNode) selectedNode.getChildAt(i);
RasterDataNode key = getKey(child.getUserObject().toString(), allBandsMap);
if (key != null) {
selectedBandList.add((Band) key);
}
}
}
}
return selectedBandList.toArray(new Band[selectedBandList.size()]);
}
private RasterDataNode getKey(String value, Map<? extends RasterDataNode, String> map) {
for (Map.Entry<? extends RasterDataNode, String> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
@Override
public TiePointGrid[] getSelectedTiePointGrids() {
List<TiePointGrid> selectedGridList = new ArrayList<>();
final TreePath[] selectionPaths = checkBoxTree.getCheckBoxTreeSelectionModel().getSelectionPaths();
TreePath rootPath = new TreePath(checkBoxTree.getModel().getRoot());
for (TreePath selectionPath : selectionPaths) {
if (selectionPath.equals(rootPath)) {
return allGridsMap.keySet().toArray(new TiePointGrid[allGridsMap.size()]);
}
final DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
if (selectedNode.isLeaf()) {
RasterDataNode key = getKey(selectedNode.getUserObject().toString(), allGridsMap);
if (key != null) {
selectedGridList.add((TiePointGrid) key);
}
} else {
for (int i = 0; i < selectedNode.getChildCount(); i++) {
final DefaultMutableTreeNode child = (DefaultMutableTreeNode) selectedNode.getChildAt(i);
RasterDataNode key = getKey(child.getUserObject().toString(), allGridsMap);
if (key != null) {
selectedGridList.add((TiePointGrid) key);
}
selectedGridList.add((TiePointGrid) key);
}
}
}
return selectedGridList.toArray(new TiePointGrid[selectedGridList.size()]);
}
public JPanel createCheckersPane() {
DefaultMutableTreeNode root = new DefaultMutableTreeNode();
Map<String, Integer> groupNodeMap = initGrouping(root);
List<TreePath> selectedPaths = new ArrayList<>();
addBandCheckBoxes(root, selectedPaths, groupNodeMap);
addTiePointGridCheckBoxes(root, selectedPaths, groupNodeMap);
removeEmptyGroups(root, groupNodeMap);
TreeModel treeModel = new DefaultTreeModel(root);
checkBoxTree = new CheckBoxTree(treeModel);
checkBoxTree.getCheckBoxTreeSelectionModel().setSelectionPaths(selectedPaths.toArray(new TreePath[selectedPaths.size()]));
checkBoxTree.setRootVisible(false);
checkBoxTree.setShowsRootHandles(true);
checkBoxTree.getCheckBoxTreeSelectionModel().addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
updateCheckBoxStates();
}
});
final DefaultTreeCellRenderer renderer = (DefaultTreeCellRenderer) checkBoxTree.getActualCellRenderer();
renderer.setFont(SMALL_ITALIC_FONT);
renderer.setLeafIcon(null);
renderer.setOpenIcon(null);
renderer.setClosedIcon(null);
Color color = new Color(240, 240, 240);
checkBoxTree.setBackground(color);
renderer.setBackgroundSelectionColor(color);
renderer.setBackgroundNonSelectionColor(color);
renderer.setBorderSelectionColor(color);
renderer.setTextSelectionColor(Color.BLACK);
GridBagConstraints gbc2 = GridBagUtils.createConstraints("insets.left=4,anchor=WEST,fill=BOTH");
final JPanel checkersPane = GridBagUtils.createPanel();
GridBagUtils.addToPanel(checkersPane, checkBoxTree, gbc2, "weightx=1.0,weighty=1.0");
return checkersPane;
}
private Map<String, Integer> initGrouping(DefaultMutableTreeNode root) {
Map<String, Integer> groupNodeMap = new HashMap<>();
if (autoGrouping != null) {
for (String[] groupNames : autoGrouping) {
final String groupName = groupNames[0];
if (!hasChild(root, groupName)) {
DefaultMutableTreeNode groupNode = new DefaultMutableTreeNode(groupName);
groupNodeMap.put(groupNode.getUserObject().toString(), root.getChildCount());
root.add(groupNode);
}
}
}
return groupNodeMap;
}
private void removeEmptyGroups(DefaultMutableTreeNode root, Map<String, Integer> groupNodeMap) {
DefaultMutableTreeNode rootChild = (DefaultMutableTreeNode) root.getFirstChild();
while (rootChild != null) {
DefaultMutableTreeNode nextChild = rootChild.getNextSibling();
if (rootChild.getChildCount() == 0 && groupNodeMap.containsKey(rootChild.getUserObject().toString())) {
root.remove(rootChild);
}
rootChild = nextChild;
}
}
private void addBandCheckBoxes(DefaultMutableTreeNode root, List<TreePath> selectedPaths,
Map<String, Integer> groupNodeMap) {
final Set<Map.Entry<Band, String>> allBands = allBandsMap.entrySet();
for (Map.Entry<Band, String> bandEntry : allBands) {
final Band band = bandEntry.getKey();
if (autoGrouping != null) {
final int bandIndex = autoGrouping.indexOf(band.getName());
if (bandIndex >= 0) {
final String groupName = autoGrouping.get(bandIndex)[0];
final Integer index = groupNodeMap.get(groupName);
final DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) root.getChildAt(index);
final DefaultMutableTreeNode groupChild = new DefaultMutableTreeNode(bandEntry.getValue());
if (selectedBandsMap.containsValue(bandEntry.getValue())) {
selectedPaths.add(new TreePath(new Object[]{root, groupNode, groupChild}));
}
groupNode.add(groupChild);
} else {
addToRoot(root, selectedPaths, bandEntry, band);
}
} else {
addToRoot(root, selectedPaths, bandEntry, band);
}
}
}
private void addTiePointGridCheckBoxes(DefaultMutableTreeNode root, List<TreePath> selectedPaths,
Map<String, Integer> groupNodeMap) {
final Set<Map.Entry<TiePointGrid, String>> allGrids = allGridsMap.entrySet();
for (Map.Entry<TiePointGrid, String> gridEntry : allGrids) {
final TiePointGrid grid = gridEntry.getKey();
if (autoGrouping != null) {
final int gridIndex = autoGrouping.indexOf(grid.getName());
if (gridIndex >= 0) {
final String groupName = autoGrouping.get(gridIndex)[0];
final Integer index = groupNodeMap.get(groupName);
final DefaultMutableTreeNode groupNode = (DefaultMutableTreeNode) root.getChildAt(index);
final DefaultMutableTreeNode groupChild = new DefaultMutableTreeNode(gridEntry.getValue());
if (selectedGridsMap.containsKey(grid)) {
selectedPaths.add(new TreePath(new Object[]{root, groupNode, groupChild}));
}
groupNode.add(groupChild);
} else {
addToRoot(root, selectedPaths, gridEntry, grid);
}
} else {
addToRoot(root, selectedPaths, gridEntry, grid);
}
}
}
private void addToRoot(DefaultMutableTreeNode root, List<TreePath> selectedPaths, Map.Entry<Band, String> bandEntry, Band band) {
final DefaultMutableTreeNode rootChild = new DefaultMutableTreeNode(bandEntry.getValue());
if (selectedBandsMap.containsKey(band)) {
selectedPaths.add(new TreePath(new Object[]{root, rootChild}));
}
root.add(rootChild);
}
private void addToRoot(DefaultMutableTreeNode root, List<TreePath> selectedPaths, Map.Entry<TiePointGrid, String> gridEntry, TiePointGrid grid) {
final DefaultMutableTreeNode rootChild = new DefaultMutableTreeNode(gridEntry.getValue());
if (selectedGridsMap.containsKey(grid)) {
selectedPaths.add(new TreePath(new Object[]{root, rootChild}));
}
root.add(rootChild);
}
public void updateCheckBoxStates() {
final TreePath[] selectionPaths = checkBoxTree.getCheckBoxTreeSelectionModel().getSelectionPaths();
if (selectionPaths == null || selectionPaths.length == 0) {
selectAllCheckBox.setSelected(false);
selectAllCheckBox.setEnabled(true);
selectAllCheckBox.updateUI();
selectNoneCheckBox.setSelected(true);
selectNoneCheckBox.setEnabled(false);
selectNoneCheckBox.updateUI();
} else {
final TreePath rootPath = new TreePath(checkBoxTree.getModel().getRoot());
boolean allSelected = false;
for (TreePath selectionPath : selectionPaths) {
if (selectionPath.equals(rootPath)) {
allSelected = true;
}
selectAllCheckBox.setSelected(allSelected);
selectAllCheckBox.setEnabled(!allSelected);
selectAllCheckBox.updateUI();
selectNoneCheckBox.setSelected(false);
selectNoneCheckBox.setEnabled(true);
selectNoneCheckBox.updateUI();
}
}
}
private boolean hasChild(DefaultMutableTreeNode node, String groupName) {
for (int i = 0; i < node.getChildCount(); i++) {
if (((DefaultMutableTreeNode) node.getChildAt(i)).getUserObject().equals(groupName)) {
return true;
}
}
return false;
}
@Override
public void setCheckBoxes(JCheckBox selectAllCheckBox, JCheckBox selectNoneCheckBox) {
this.selectAllCheckBox = selectAllCheckBox;
this.selectNoneCheckBox = selectNoneCheckBox;
updateCheckBoxStates();
}
@Override
public void selectAll() {
checkBoxTree.getCheckBoxTreeSelectionModel().setSelectionPath(new TreePath(checkBoxTree.getModel().getRoot()));
}
@Override
public void selectNone() {
checkBoxTree.getCheckBoxTreeSelectionModel().clearSelection();
}
@Override
public boolean atLeastOneBandSelected() {
return checkBoxTree.getCheckBoxTreeSelectionModel().getSelectionPaths() != null;
}
@Override
public void selectRasterDataNodes(String[] nodeNames) {
DefaultMutableTreeNode rootNode = (DefaultMutableTreeNode) checkBoxTree.getModel().getRoot();
selectRasterDataNodes(rootNode, nodeNames);
}
private void selectRasterDataNodes(DefaultMutableTreeNode node, String[] nodeNames) {
int childCount = node.getChildCount();
if(childCount != 0) {
for(int i = 0; i < childCount; i++) {
selectRasterDataNodes((DefaultMutableTreeNode)node.getChildAt(i), nodeNames);
}
} else {
for (String nodeName : nodeNames) {
if (nodeName.equals(((String) node.getUserObject()).split(" ")[0].trim())) {
List<TreeNode> pathList = new ArrayList<>();
TreeNode currentNode = node;
while(currentNode != null) {
pathList.add(0, currentNode);
currentNode = currentNode.getParent();
}
TreePath path = new TreePath(pathList.toArray(new TreeNode[pathList.size()]));
checkBoxTree.getCheckBoxTreeSelectionModel().addSelectionPath(path);
}
}
}
}
}
| 17,338 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddFileAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/AddFileAction.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.ui.product;
import com.bc.ceres.binding.ValidationException;
import org.esa.snap.core.dataio.ProductIOPlugInManager;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.ui.AppContext;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.util.Iterator;
import java.util.List;
/**
* @author Thomas Storm
*/
class AddFileAction extends AbstractAction {
public static final String ALL_FILES_FORMAT = "ALL_FILES";
private final AppContext appContext;
private final InputListModel listModel;
private final String propertyNameLastOpenInputDir;
private final String propertyNameLastOpenedFormat;
private final String propertyNameFormatNames;
AddFileAction(AppContext appContext, InputListModel listModel, String propertyNameLastOpenInputDir,
String propertyNameLastOpenedFormat, String propertyNameFormatNames) {
super("Add product file(s)...");
this.appContext = appContext;
this.listModel = listModel;
this.propertyNameLastOpenInputDir = propertyNameLastOpenInputDir;
this.propertyNameLastOpenedFormat = propertyNameLastOpenedFormat;
this.propertyNameFormatNames = propertyNameFormatNames;
}
@Override
public void actionPerformed(ActionEvent e) {
final PropertyMap preferences = appContext.getPreferences();
String lastDir = preferences.getPropertyString(propertyNameLastOpenInputDir, SystemUtils.getUserHomeDir().getPath());
String lastFormat = preferences.getPropertyString(propertyNameLastOpenedFormat, ALL_FILES_FORMAT);
String formatNames = preferences.getPropertyString(propertyNameFormatNames, null);
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(lastDir));
fileChooser.setDialogTitle("Select product(s)");
fileChooser.setMultiSelectionEnabled(true);
FileFilter actualFileFilter = fileChooser.getAcceptAllFileFilter();
ProductIOPlugInManager ioManager = ProductIOPlugInManager.getInstance();
if (StringUtils.isNullOrEmpty(formatNames)) {
Iterator<ProductReaderPlugIn> allReaderPlugIns = ioManager.getAllReaderPlugIns();
List<SnapFileFilter> sortedFileFilters = SnapFileFilter.getSortedFileFilters(allReaderPlugIns);
for (SnapFileFilter productFileFilter : sortedFileFilters) {
fileChooser.addChoosableFileFilter(productFileFilter);
String formatName = productFileFilter.getFormatName();
if (!ALL_FILES_FORMAT.equals(lastFormat) &&
formatName != null && formatName.equals(lastFormat)) {
actualFileFilter = productFileFilter;
}
}
} else {
String[] formats = StringUtils.csvToArray(formatNames);
for (String format : formats) {
Iterator<ProductReaderPlugIn> readerPlugIns = ioManager.getReaderPlugIns(format);
while (readerPlugIns.hasNext()) {
ProductReaderPlugIn next = readerPlugIns.next();
SnapFileFilter productFileFilter = next.getProductFileFilter();
fileChooser.addChoosableFileFilter(productFileFilter);
String formatName = productFileFilter.getFormatName();
if(formatName != null && formatName.equals(lastFormat)) {
actualFileFilter = productFileFilter;
}
}
}
}
fileChooser.setFileFilter(actualFileFilter);
int result = fileChooser.showDialog(appContext.getApplicationWindow(), "Select product(s)");
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
preferences.setPropertyString(propertyNameLastOpenInputDir, fileChooser.getCurrentDirectory().getAbsolutePath());
final Object[] selectedProducts = fileChooser.getSelectedFiles();
try {
listModel.addElements(selectedProducts);
} catch (ValidationException ve) {
// not expected to ever come here
appContext.handleError("Invalid input path", ve);
}
setLastOpenedFormat(preferences, fileChooser.getFileFilter());
}
private void setLastOpenedFormat(PropertyMap preferences, FileFilter fileFilter) {
if (fileFilter instanceof SnapFileFilter) {
String currentFormat = ((SnapFileFilter) fileFilter).getFormatName();
if (currentFormat != null) {
preferences.setPropertyString(propertyNameLastOpenedFormat, currentFormat);
}
} else {
preferences.setPropertyString(propertyNameLastOpenedFormat, ALL_FILES_FORMAT);
}
}
}
| 5,816 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductExpressionPane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ProductExpressionPane.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.ui.product;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Mask;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.jexp.Namespace;
import org.esa.snap.core.jexp.impl.ParserImpl;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.ui.ExpressionPane;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* An expression pane to be used in conjunction with {@link Product}s in order to edit and assemble band arithmetic expressions.
*/
public class ProductExpressionPane extends ExpressionPane {
private Product[] products;
private Product currentProduct;
private Product targetProduct;
private JComboBox<String> productBox;
private JList<String> nodeList;
private JCheckBox inclBandsCheck;
private JCheckBox inclMasksCheck;
private JCheckBox inclGridsCheck;
private JCheckBox inclFlagsCheck;
protected ProductExpressionPane(boolean booleanExpr,
Product[] products,
Product currentProduct,
PropertyMap preferences) {
super(booleanExpr, null, preferences);
if (products == null || products.length == 0) {
throw new IllegalArgumentException("no products given");
}
this.products = products;
this.currentProduct = currentProduct != null ? currentProduct : this.products[0];
this.targetProduct = this.currentProduct;
init();
}
public static ProductExpressionPane createBooleanExpressionPane(Product[] products,
Product currentProduct,
PropertyMap preferences) {
return new ProductExpressionPane(true, products, currentProduct, preferences);
}
public static ProductExpressionPane createGeneralExpressionPane(Product[] products,
Product currentProduct,
PropertyMap preferences) {
return new ProductExpressionPane(false, products, currentProduct, preferences);
}
public Product getCurrentProduct() {
return currentProduct;
}
protected void init() {
final int defaultIndex = Arrays.asList(products).indexOf(currentProduct);
Namespace namespace = BandArithmetic.createDefaultNamespace(products,
defaultIndex == -1 ? 0 : defaultIndex);
// We may make type checking an option (checkbox) in UI
setParser(new ParserImpl(namespace, false));
final ActionListener resetNodeListAL = e -> {
if (e.getSource() == productBox) {
setCurrentProduct();
}
resetNodeList();
};
inclBandsCheck = new JCheckBox("Show bands");
inclBandsCheck.addActionListener(resetNodeListAL);
if(!isBooleanExpressionPreferred() || currentProduct.getAllFlagNames().length == 0) {
inclBandsCheck.setSelected(true);
} else {
inclBandsCheck.setSelected(false);
}
inclMasksCheck = new JCheckBox("Show masks");
inclMasksCheck.addActionListener(resetNodeListAL);
if (!isBooleanExpressionPreferred()) {
inclMasksCheck.setSelected(true);
}
inclGridsCheck = new JCheckBox("Show tie-point grids");
inclGridsCheck.addActionListener(resetNodeListAL);
inclFlagsCheck = new JCheckBox("Show single flags");
inclFlagsCheck.addActionListener(resetNodeListAL);
if (isBooleanExpressionPreferred()) {
inclFlagsCheck.setSelected(true);
}
nodeList = createPatternList();
JScrollPane scrollableNodeList = new JScrollPane(nodeList);
Box inclNodeBox = Box.createVerticalBox();
inclNodeBox.add(inclBandsCheck);
inclNodeBox.add(inclMasksCheck);
inclNodeBox.add(inclGridsCheck);
inclNodeBox.add(inclFlagsCheck);
JPanel nodeListPane = new JPanel(new BorderLayout());
nodeListPane.add(new JLabel("Data sources: "), BorderLayout.NORTH);
nodeListPane.add(scrollableNodeList, BorderLayout.CENTER);
nodeListPane.add(inclNodeBox, BorderLayout.SOUTH);
JPanel accessoryPane = createDefaultAccessoryPane(nodeListPane);
setLeftAccessory(accessoryPane);
if (products.length > 1) {
List<String> nameList = new ArrayList<>(products.length);
for (Product product : products) {
String productName = product.getDisplayName();
nameList.add(productName);
}
String currentProductName = currentProduct.getDisplayName();
final String[] productNames = new String[nameList.size()];
nameList.toArray(productNames);
productBox = new JComboBox<>(productNames);
productBox.setEditable(false);
productBox.setEnabled(products.length > 1);
productBox.addActionListener(resetNodeListAL);
productBox.setSelectedItem(currentProductName);
JPanel productPane = new JPanel(new BorderLayout());
productPane.add(new JLabel("Product: "), BorderLayout.WEST);
productPane.add(productBox, BorderLayout.CENTER);
setTopAccessory(productPane);
}
resetNodeList();
}
@Override
public void dispose() {
products = null;
currentProduct = null;
productBox = null;
nodeList = null;
inclBandsCheck = null;
inclMasksCheck = null;
inclGridsCheck = null;
inclFlagsCheck = null;
super.dispose();
}
private void resetNodeList() {
setCurrentProduct();
List<String> listEntries = new ArrayList<>(64);
if (currentProduct != null) {
String[] flagNames = currentProduct.getAllFlagNames();
boolean hasBands = currentProduct.getNumBands() > 0;
boolean hasMasks = currentProduct.getMaskGroup().getNodeCount() > 0;
boolean hasGrids = currentProduct.getNumTiePointGrids() > 0;
boolean hasFlags = flagNames.length > 0;
boolean inclBands = inclBandsCheck.isSelected();
boolean inclMasks = inclMasksCheck.isSelected();
boolean inclGrids = inclGridsCheck.isSelected();
boolean inclFlags = inclFlagsCheck.isSelected();
inclBandsCheck.setEnabled(hasBands);
inclMasksCheck.setEnabled(hasMasks);
inclGridsCheck.setEnabled(hasGrids);
inclFlagsCheck.setEnabled(hasFlags);
if (!hasBands && inclBands) {
inclBandsCheck.setSelected(false);
inclBands = false;
}
if (!hasMasks && inclMasks) {
inclMasksCheck.setSelected(false);
inclMasks = false;
}
if (!hasGrids && inclGrids) {
inclGridsCheck.setSelected(false);
inclGrids = false;
}
if (!hasFlags && inclFlags) {
inclFlagsCheck.setSelected(false);
inclFlags = false;
}
nodeList.setEnabled(inclBands || inclMasks || inclGrids || inclFlags);
final String namePrefix = getNodeNamePrefix();
if (inclBands) {
addBandNameRefs(currentProduct, namePrefix, listEntries);
}
if (inclMasks) {
addMaskNameRefs(currentProduct, namePrefix, listEntries);
}
if (inclGrids) {
addGridNameRefs(currentProduct, namePrefix, listEntries);
}
if (inclFlags) {
addFlagNameRefs(namePrefix, flagNames, listEntries);
}
} else {
nodeList.setEnabled(false);
inclBandsCheck.setEnabled(false);
inclMasksCheck.setEnabled(false);
inclGridsCheck.setEnabled(false);
inclFlagsCheck.setEnabled(false);
}
nodeList.setListData(listEntries.toArray(new String[listEntries.size()]));
}
private void setCurrentProduct() {
if (productBox != null) {
int index = productBox.getSelectedIndex();
if (index != -1) {
currentProduct = products[index];
} else {
currentProduct = null;
}
}
}
private String getNodeNamePrefix() {
final String namePrefix;
// if multiple compatible products, the product name prefix should be the index of the product
// in order to avoid ambiguity
if (products.length > 1 || currentProduct != targetProduct) {
namePrefix = BandArithmetic.getProductNodeNamePrefix(currentProduct);
} else {
namePrefix = "";
}
return namePrefix;
}
private static void addBandNameRefs(Product product, String namePrefix, List<String> list) {
for (int j = 0; j < product.getNumBands(); j++) {
Band band = product.getBandAt(j);
list.add(namePrefix + band.getName());
}
}
private static void addMaskNameRefs(Product product, String namePrefix, List<String> list) {
for (int j = 0; j < product.getMaskGroup().getNodeCount(); j++) {
Mask mask = product.getMaskGroup().get(j);
list.add(namePrefix + mask.getName());
}
}
private static void addGridNameRefs(Product product, String namePrefix, List<String> list) {
for (int j = 0; j < product.getNumTiePointGrids(); j++) {
TiePointGrid grid = product.getTiePointGridAt(j);
list.add(namePrefix + grid.getName());
}
}
private static void addFlagNameRefs(String namePrefix, String[] flagNames, List<String> list) {
for (String flagName : flagNames) {
list.add(namePrefix + flagName);
}
}
}
| 11,084 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddProductAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/AddProductAction.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.ui.product;
import com.bc.ceres.binding.ValidationException;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductFilter;
import org.esa.snap.core.util.Debug;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import javax.swing.AbstractAction;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author Thomas Storm
*/
class AddProductAction extends AbstractAction {
private final AppContext appContext;
private final InputListModel listModel;
private ProductFilter productFilter;
AddProductAction(AppContext appContext, InputListModel listModel) {
super("Add product(s)...");
this.appContext = appContext;
this.listModel = listModel;
productFilter = product -> true;
}
@Override
public void actionPerformed(ActionEvent e) {
ProductChooser productChooser = new ProductChooser(appContext.getApplicationWindow(), "Add product",
ModalDialog.ID_OK_CANCEL, null,
filterProducts());
if (productChooser.show() != ModalDialog.ID_OK) {
return;
}
try {
if (productChooser.getSelectedProducts().size() > 0) {
listModel.addElements(productChooser.getSelectedProducts().toArray());
}
} catch (ValidationException ve) {
Debug.trace(ve);
}
}
private Product[] filterProducts() {
List<Product> currentlyOpenedProducts = Arrays.asList(listModel.getSourceProducts());
List<Product> productManagerProducts = Arrays.asList(appContext.getProductManager().getProducts());
ArrayList<Product> result = new ArrayList<>();
for (Product product : productManagerProducts) {
if (!currentlyOpenedProducts.contains(product) && productFilter.accept(product)) {
result.add(product);
}
}
return result.toArray(new Product[result.size()]);
}
/**
* Used to filter products which are offered to the user.
*
* @param productFilter the filter to be used
*/
public void setProductFilter(ProductFilter productFilter) {
this.productFilter = productFilter;
}
}
| 3,123 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AddDirectoryAction.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/AddDirectoryAction.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.ui.product;
import com.bc.ceres.binding.ValidationException;
import com.jidesoft.swing.FolderChooser;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import javax.swing.AbstractAction;
import javax.swing.JFileChooser;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.io.File;
/**
* @author Thomas Storm
*/
class AddDirectoryAction extends AbstractAction {
private final String lastDirProperty;
private boolean recursive;
private AppContext appContext;
private InputListModel listModel;
private String defaultPattern;
AddDirectoryAction(AppContext appContext, InputListModel listModel, boolean recursive, String lastDirProperty, String defaultPattern) {
this(recursive, lastDirProperty);
this.appContext = appContext;
this.listModel = listModel;
if (defaultPattern == null) {
this.defaultPattern = recursive ? "*.dim" : "*";
}
this.defaultPattern = defaultPattern;
}
private AddDirectoryAction(boolean recursive, String lastDirProperty) {
this("Add directory" + (recursive ? " recursively" : "(s)") + "...", lastDirProperty);
this.recursive = recursive;
}
private AddDirectoryAction(String title, String lastDirProperty) {
super(title);
this.lastDirProperty = lastDirProperty;
}
@Override
public void actionPerformed(ActionEvent e) {
final FolderChooser folderChooser = new FolderChooser();
final PropertyMap preferences = appContext.getPreferences();
String lastDir = preferences.getPropertyString(lastDirProperty, SystemUtils.getUserHomeDir().getPath());
if (lastDir != null) {
folderChooser.setCurrentDirectory(new File(lastDir));
}
folderChooser.setMultiSelectionEnabled(!recursive);
final Window parent = appContext.getApplicationWindow();
final int result = folderChooser.showOpenDialog(parent);
if (result != JFileChooser.APPROVE_OPTION) {
return;
}
final FileSelectionPatternDialog dialog = new FileSelectionPatternDialog(defaultPattern, parent);
if (dialog.show() != ModalDialog.ID_OK) {
return;
}
final String pattern = dialog.getPattern();
File[] selectedDirs;
if (recursive) {
File selectedDir = folderChooser.getSelectedFolder();
lastDir = selectedDir.getAbsolutePath();
selectedDir = new File(selectedDir, "**");
selectedDir = new File(selectedDir, pattern);
selectedDirs = new File[]{selectedDir};
} else {
final File[] selectedPaths = folderChooser.getSelectedFiles();
if (selectedPaths.length > 0) {
lastDir = selectedPaths[0].getAbsolutePath();
}
selectedDirs = new File[selectedPaths.length];
for (int i = 0; i < selectedPaths.length; i++) {
File selectedFile = selectedPaths[i];
selectedDirs[i] = new File(selectedFile, pattern);
}
}
preferences.setPropertyString(lastDirProperty, lastDir);
try {
listModel.addElements((Object[]) selectedDirs);
} catch (ValidationException ve) {
// not expected to ever come here
appContext.handleError("Invalid input path", ve);
}
}
}
| 4,255 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BandChoosingStrategy.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/BandChoosingStrategy.java | package org.esa.snap.ui.product;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.TiePointGrid;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
interface BandChoosingStrategy {
Band[] getSelectedBands();
TiePointGrid[] getSelectedTiePointGrids();
JPanel createCheckersPane();
void updateCheckBoxStates();
void setCheckBoxes(JCheckBox selectAllCheckBox, JCheckBox selectNoneCheckBox);
void selectAll();
void selectNone();
boolean atLeastOneBandSelected();
void selectRasterDataNodes(String[] nodeNames);
}
| 590 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataCollectionLayerType.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/VectorDataCollectionLayerType.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.ui.product;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.core.Assert;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.annotations.LayerTypeMetadata;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.layer.ProductLayerContext;
@LayerTypeMetadata(name = "VectorDataCollectionLayerType",
aliasNames = {"VectorDataCollectionLayerType"})
public class VectorDataCollectionLayerType extends CollectionLayer.Type {
@Override
public boolean isValidFor(LayerContext ctx) {
return ctx instanceof ProductLayerContext;
}
@Override
public Layer createLayer(LayerContext ctx, PropertySet configuration) {
Assert.notNull(ctx, "ctx");
final ProductLayerContext plc = (ProductLayerContext) ctx;
final ProductNodeGroup<VectorDataNode> vectorDataGroup = plc.getProduct().getVectorDataGroup();
return new VectorDataCollectionLayer(this, vectorDataGroup, configuration, plc);
}
}
| 1,882 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataLayerFilterFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/VectorDataLayerFilterFactory.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.ui.product;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerFilter;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.VectorDataNode;
/**
* Filter out layers of type {@link VectorDataLayer}.
*/
public class VectorDataLayerFilterFactory {
public static LayerFilter createGeometryFilter() {
return new TypeNameFilter(Product.GEOMETRY_FEATURE_TYPE_NAME);
}
public static LayerFilter createNodeFilter(VectorDataNode vectorDataNode) {
return new NodeFilter(vectorDataNode);
}
private static class TypeNameFilter implements LayerFilter {
private final String featureTypeName;
private TypeNameFilter(String featureTypeName) {
this.featureTypeName = featureTypeName;
}
@Override
public boolean accept(Layer layer) {
return layer instanceof VectorDataLayer
&& featureTypeName.equals(((VectorDataLayer) layer).getVectorDataNode().getFeatureType().getTypeName());
}
}
private static class NodeFilter implements LayerFilter {
private final VectorDataNode vectorDataNode;
private NodeFilter(VectorDataNode vectorDataNode) {
this.vectorDataNode = vectorDataNode;
}
@Override
public boolean accept(Layer layer) {
return layer instanceof VectorDataLayer
&& (((VectorDataLayer) layer).getVectorDataNode() == vectorDataNode);
}
}
}
| 2,249 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductSubsetDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ProductSubsetDialog.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.ui.product;
import com.bc.ceres.core.Assert;
import com.bc.ceres.core.ProgressMonitor;
import com.bc.ceres.core.SubProgressMonitor;
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.glevel.MultiLevelSource;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.grender.support.BufferedImageRendering;
import com.bc.ceres.grender.support.DefaultViewport;
import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker;
import org.esa.snap.core.dataio.ProductSubsetDef;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.Mask;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.gpf.common.SubsetOp;
import org.esa.snap.core.image.ColoredBandImageMultiLevelSource;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.jexp.Term;
import org.esa.snap.core.param.ParamChangeEvent;
import org.esa.snap.core.param.ParamChangeListener;
import org.esa.snap.core.param.ParamGroup;
import org.esa.snap.core.param.Parameter;
import org.esa.snap.core.subset.PixelSubsetRegion;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.Guardian;
import org.esa.snap.core.util.ProductUtils;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.ui.GridBagUtils;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.SliderBoxImageDisplay;
import org.esa.snap.ui.UIUtils;
import javax.swing.*;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.GridBagConstraints;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A modal dialog used to specify data product subsets.
*/
public class ProductSubsetDialog extends ModalDialog {
private static final String MEM_LABEL_TEXT = "Estimated, raw storage size: "; /*I18N*/
private static final Color MEM_LABEL_WARN_COLOR = Color.red;
private static final Color MEM_LABEL_NORM_COLOR = Color.black;
private static final int MAX_THUMBNAIL_WIDTH = 148;
private static final int MIN_SUBSET_SIZE = 1;
private static final Font SMALL_PLAIN_FONT = new Font("SansSerif", Font.PLAIN, 10);
private static final Font SMALL_ITALIC_FONT = SMALL_PLAIN_FONT.deriveFont(Font.ITALIC);
private Product product;
private ProductSubsetDef productSubsetDef;
private ProductSubsetDef givenProductSubsetDef;
private JLabel memLabel;
private SpatialSubsetPane spatialSubsetPane;
private ProductNodeSubsetPane bandSubsetPane;
private ProductNodeSubsetPane tiePointGridSubsetPane;
private ProductNodeSubsetPane metadataSubsetPane;
private double memWarnLimit;
private static final double DEFAULT_MEM_WARN_LIMIT = 1000.0;
private AtomicBoolean updatingUI;
/**
* Constructs a new subset dialog.
*
* @param window the parent window
* @param product the product for which the subset is to be specified, must not be {@code null}
*/
public ProductSubsetDialog(Window window, Product product) {
this(window, product, DEFAULT_MEM_WARN_LIMIT);
}
/**
* Constructs a new subset dialog.
*
* @param window the parent window
* @param product the product for which the subset is to be specified, must not be {@code null}
* @param memWarnLimit the warning limit in megabytes
*/
public ProductSubsetDialog(Window window, Product product, double memWarnLimit) {
this(window, product, null, memWarnLimit);
}
/**
* Constructs a new subset dialog.
*
* @param window the parent window
* @param product the product for which the subset is to be specified, must not be {@code null}
* @param productSubsetDef the initial product subset definition, can be {@code null}
*/
public ProductSubsetDialog(Window window,
Product product,
ProductSubsetDef productSubsetDef) {
this(window, product, productSubsetDef, DEFAULT_MEM_WARN_LIMIT);
}
/**
* Constructs a new subset dialog.
*
* @param window the parent window
* @param product the product for which the subset is to be specified, must not be {@code null}
* @param productSubsetDef the initial product subset definition, can be {@code null}
* @param memWarnLimit the warning limit in megabytes
*/
public ProductSubsetDialog(Window window,
Product product,
ProductSubsetDef productSubsetDef,
double memWarnLimit) {
super(window, "Specify Product Subset", ID_OK | ID_CANCEL | ID_HELP, "subsetDialog");
Guardian.assertNotNull("product", product);
this.product = product;
givenProductSubsetDef = productSubsetDef;
this.productSubsetDef = new ProductSubsetDef("undefined");
this.memWarnLimit = memWarnLimit;
updatingUI = new AtomicBoolean(false);
createUI();
}
public Product getProduct() {
return product;
}
public ProductSubsetDef getProductSubsetDef() {
return productSubsetDef;
}
@Override
protected void onOK() {
boolean ok;
ok = checkReferencedRastersIncluded();
if (!ok) {
return;
}
ok = checkFlagDatasetIncluded();
if (!ok) {
return;
}
spatialSubsetPane.cancelThumbnailLoader();
if (productSubsetDef != null && productSubsetDef.isEntireProductSelected()) {
productSubsetDef = null;
}
super.onOK();
}
private boolean checkReferencedRastersIncluded() {
final Set<String> notIncludedNames = new TreeSet<>();
String[] nodeNames = productSubsetDef.getNodeNames();
if (nodeNames != null) {
final List<String> includedNodeNames = Arrays.asList(nodeNames);
for (final String nodeName : includedNodeNames) {
final RasterDataNode rasterDataNode = product.getRasterDataNode(nodeName);
if (rasterDataNode != null) {
collectNotIncludedReferences(rasterDataNode, notIncludedNames);
}
}
}
boolean ok = true;
if (!notIncludedNames.isEmpty()) {
StringBuilder nameListText = new StringBuilder();
for (String notIncludedName : notIncludedNames) {
nameListText.append(" '").append(notIncludedName).append("'\n");
}
final String pattern = "The following dataset(s) are referenced but not included\n" +
"in your current subset definition:\n" +
"{0}\n" +
"If you do not include these dataset(s) into your selection,\n" +
"you might get unexpected results while working with the\n" +
"resulting product.\n\n" +
"Do you wish to include the referenced dataset(s) into your\n" +
"subset definition?\n"; /*I18N*/
final MessageFormat format = new MessageFormat(pattern);
int status = JOptionPane.showConfirmDialog(getJDialog(),
format.format(new Object[]{nameListText.toString()}),
"Incomplete Subset Definition", /*I18N*/
JOptionPane.YES_NO_CANCEL_OPTION);
if (status == JOptionPane.YES_OPTION) {
final String[] nodenames = notIncludedNames.toArray(new String[notIncludedNames.size()]);
productSubsetDef.addNodeNames(nodenames);
ok = true;
} else if (status == JOptionPane.NO_OPTION) {
ok = true;
} else if (status == JOptionPane.CANCEL_OPTION) {
ok = false;
}
}
return ok;
}
private void collectNotIncludedReferences(final RasterDataNode rasterDataNode, final Set<String> notIncludedNames) {
final RasterDataNode[] referencedNodes = getReferencedNodes(rasterDataNode);
for (final RasterDataNode referencedNode : referencedNodes) {
final String name = referencedNode.getName();
if (!productSubsetDef.isNodeAccepted(name) && !notIncludedNames.contains(name)) {
notIncludedNames.add(name);
collectNotIncludedReferences(referencedNode, notIncludedNames);
}
}
}
private static RasterDataNode[] getReferencedNodes(final RasterDataNode node) {
final Product product = node.getProduct();
if (product != null) {
final List<String> expressions = new ArrayList<>(10);
if (node.getValidPixelExpression() != null) {
expressions.add(node.getValidPixelExpression());
}
final ProductNodeGroup<Mask> overlayMaskGroup = node.getOverlayMaskGroup();
if (overlayMaskGroup.getNodeCount() > 0) {
final Mask[] overlayMasks = overlayMaskGroup.toArray(new Mask[overlayMaskGroup.getNodeCount()]);
for (final Mask overlayMask : overlayMasks) {
final String expression;
if (overlayMask.getImageType() == Mask.BandMathsType.INSTANCE) {
expression = Mask.BandMathsType.getExpression(overlayMask);
} else if (overlayMask.getImageType() == Mask.RangeType.INSTANCE) {
expression = Mask.RangeType.getExpression(overlayMask);
} else {
expression = null;
}
if (expression != null) {
expressions.add(expression);
}
}
}
if (node instanceof VirtualBand) {
final VirtualBand virtualBand = (VirtualBand) node;
expressions.add(virtualBand.getExpression());
}
final ArrayList<Term> termList = new ArrayList<>(10);
for (final String expression : expressions) {
try {
final Term term = product.parseExpression(expression);
if (term != null) {
termList.add(term);
}
} catch (ParseException e) {
// @todo se handle parse exception
Debug.trace(e);
}
}
return BandArithmetic.getRefRasters(termList.toArray(new Term[termList.size()]));
}
return new RasterDataNode[0];
}
private boolean checkFlagDatasetIncluded() {
final String[] nodeNames = productSubsetDef.getNodeNames();
final List<String> flagDsNameList = new ArrayList<>(10);
boolean flagDsInSubset = false;
for (int i = 0; i < product.getNumBands(); i++) {
Band band = product.getBandAt(i);
if (band.getFlagCoding() != null) {
flagDsNameList.add(band.getName());
if (StringUtils.contains(nodeNames, band.getName())) {
flagDsInSubset = true;
}
break;
}
}
final int numFlagDs = flagDsNameList.size();
boolean ok = true;
if (numFlagDs > 0 && !flagDsInSubset) {
int status = JOptionPane.showConfirmDialog(getJDialog(),
"No flag dataset selected.\n\n"
+ "If you do not include a flag dataset in the subset,\n"
+ "you will not be able to create bitmask overlays.\n\n"
+ "Do you wish to include the available flag dataset(s)\n"
+ "in the current subset?\n",
"No Flag Dataset Selected",
JOptionPane.YES_NO_CANCEL_OPTION
);
if (status == JOptionPane.YES_OPTION) {
productSubsetDef.addNodeNames(flagDsNameList.toArray(new String[numFlagDs]));
ok = true;
} else if (status == JOptionPane.NO_OPTION) {
/* OK, no flag datasets wanted */
ok = true;
} else if (status == JOptionPane.CANCEL_OPTION) {
ok = false;
}
}
return ok;
}
@Override
protected void onCancel() {
spatialSubsetPane.cancelThumbnailLoader();
super.onCancel();
}
private void createUI() {
memLabel = new JLabel("####", JLabel.RIGHT);
JTabbedPane tabbedPane = new JTabbedPane();
setComponentName(tabbedPane, "TabbedPane");
spatialSubsetPane = createSpatialSubsetPane();
setComponentName(spatialSubsetPane, "SpatialSubsetPane");
if (spatialSubsetPane != null) {
tabbedPane.addTab("Spatial Subset", spatialSubsetPane); /*I18N*/
}
bandSubsetPane = createBandSubsetPane();
setComponentName(bandSubsetPane, "BandSubsetPane");
if (bandSubsetPane != null) {
tabbedPane.addTab("Band Subset", bandSubsetPane);
}
tiePointGridSubsetPane = createTiePointGridSubsetPane();
setComponentName(tiePointGridSubsetPane, "TiePointGridSubsetPane");
if (tiePointGridSubsetPane != null) {
tabbedPane.addTab("Tie-Point Grid Subset", tiePointGridSubsetPane);
}
metadataSubsetPane = createAnnotationSubsetPane();
setComponentName(metadataSubsetPane, "MetadataSubsetPane");
if (metadataSubsetPane != null) {
tabbedPane.addTab("Metadata Subset", metadataSubsetPane);
}
tabbedPane.setPreferredSize(new Dimension(512, 380));
tabbedPane.setSelectedIndex(0);
JPanel contentPane = new JPanel(new BorderLayout(4, 4));
setComponentName(contentPane, "ContentPane");
contentPane.add(tabbedPane, BorderLayout.CENTER);
contentPane.add(memLabel, BorderLayout.SOUTH);
setContent(contentPane);
updateSubsetDefNodeNameList();
}
private SpatialSubsetPane createSpatialSubsetPane() {
return new SpatialSubsetPane();
}
private ProductNodeSubsetPane createBandSubsetPane() {
Band[] bands = product.getBands();
if (bands.length == 0) {
return null;
}
return new ProductNodeSubsetPane(product.getBands(), true);
}
private ProductNodeSubsetPane createTiePointGridSubsetPane() {
TiePointGrid[] tiePointGrids = product.getTiePointGrids();
if (tiePointGrids.length == 0) {
return null;
}
return new ProductNodeSubsetPane(product.getTiePointGrids(),
new String[]{"latitude", "longitude"},
true);
}
private ProductNodeSubsetPane createAnnotationSubsetPane() {
final MetadataElement metadataRoot = product.getMetadataRoot();
final MetadataElement[] metadataElements = metadataRoot.getElements();
final String[] metaNodes;
if (metadataElements.length == 0) {
return null;
}
// metadata elements must be added to includeAlways list
// to ensure that they are selected if isIgnoreMetadata is set to false
if (givenProductSubsetDef != null && !givenProductSubsetDef.isIgnoreMetadata()) {
metaNodes = new String[metadataElements.length];
for (int i = 0; i < metadataElements.length; i++) {
final MetadataElement metadataElement = metadataElements[i];
metaNodes[i] = metadataElement.getName();
}
} else {
metaNodes = new String[0];
}
final String[] includeNodes = StringUtils.addToArray(metaNodes, Product.HISTORY_ROOT_NAME);
return new ProductNodeSubsetPane(metadataElements, includeNodes, true);
}
private static void setComponentName(JComponent component, String name) {
if (component != null) {
Container parent = component.getParent();
if (parent != null) {
component.setName(parent.getName() + "." + name);
} else {
component.setName(name);
}
}
}
private void updateSubsetDefRegion(int x1, int y1, int x2, int y2, int sx, int sy) {
productSubsetDef.setSubsetRegion(new PixelSubsetRegion(x1, y1, x2 - x1 + 1, y2 - y1 + 1, 0));
productSubsetDef.setRegionMap(SubsetOp.computeRegionMap(productSubsetDef.getRegion(),product,productSubsetDef.getNodeNames()));
productSubsetDef.setSubSampling(sx, sy);
updateMemDisplay();
}
private void updateSubsetDefNodeNameList() {
/* We don't use this option! */
productSubsetDef.setIgnoreMetadata(false);
productSubsetDef.setNodeNames(null);
if (bandSubsetPane != null) {
productSubsetDef.addNodeNames(bandSubsetPane.getSubsetNames());
}
if (tiePointGridSubsetPane != null) {
productSubsetDef.addNodeNames(tiePointGridSubsetPane.getSubsetNames());
}
if (metadataSubsetPane != null) {
productSubsetDef.addNodeNames(metadataSubsetPane.getSubsetNames());
}
updateMemDisplay();
}
private void updateMemDisplay() {
if (product != null) {
long storageMem = product.getRawStorageSize(productSubsetDef);
double factor = 1.0 / (1024 * 1024);
double megas = MathUtils.round(factor * storageMem, 10);
if (megas > memWarnLimit) {
memLabel.setForeground(MEM_LABEL_WARN_COLOR);
} else {
memLabel.setForeground(MEM_LABEL_NORM_COLOR);
}
memLabel.setText(MEM_LABEL_TEXT + megas + "M");
} else {
memLabel.setText(" ");
}
}
private class SpatialSubsetPane extends JPanel
implements ActionListener, ParamChangeListener, SliderBoxImageDisplay.SliderBoxChangeListener {
private Parameter paramX1;
private Parameter paramY1;
private Parameter paramX2;
private Parameter paramY2;
private Parameter paramSX;
private Parameter paramSY;
private Parameter paramWestLon1;
private Parameter paramEastLon2;
private Parameter paramNorthLat1;
private Parameter paramSouthLat2;
private SliderBoxImageDisplay imageCanvas;
private JCheckBox fixSceneWidthCheck;
private JCheckBox fixSceneHeightCheck;
private JLabel subsetWidthLabel;
private JLabel subsetHeightLabel;
private JLabel sourceWidthLabel;
private JLabel sourceHeightLabel;
private int thumbNailSubSampling;
private JButton setToVisibleButton;
private JScrollPane imageScrollPane;
private ProgressMonitorSwingWorker<BufferedImage, Object> thumbnailLoader;
private JComboBox referenceCombo;
String _oldReference;
private SpatialSubsetPane() {
if(product.isMultiSize()) {
referenceCombo = new JComboBox();
for (String bandName : product.getBandNames()) {
referenceCombo.addItem(bandName);
}
referenceCombo.setSelectedItem(product.getBandAt(0));
_oldReference = (String) referenceCombo.getSelectedItem();
referenceCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int w ;
int h ;
if(product.isMultiSize()) {
w = product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth();
h = product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight();
} else {
w = product.getSceneRasterWidth();
h = product.getSceneRasterHeight();
}
final int wMin = MIN_SUBSET_SIZE;
final int hMin = MIN_SUBSET_SIZE;
paramX1.getProperties().setMaxValue((w - wMin - 1) > 0 ? w - wMin - 1 : 0);
paramY1.getProperties().setMaxValue((h - hMin - 1) > 0 ? h - hMin - 1 : 0);
paramX2.getProperties().setMaxValue(w - 1);
paramY2.getProperties().setMaxValue(h - 1);
updateUIState(new ParamChangeEvent(this,new Parameter("geo_"),null ));
_oldReference = (String) referenceCombo.getSelectedItem();
}
});
}
initParameters();
createUI();
}
private void createUI() {
setThumbnailSubsampling();
final Dimension imageSize = getScaledImageSize();
thumbnailLoader = new ProgressMonitorSwingWorker<BufferedImage, Object>(this,
"Loading thumbnail image...") {
@Override
protected BufferedImage doInBackground(ProgressMonitor pm) throws Exception {
return createThumbNailImage(imageSize, pm);
}
@Override
protected void done() {
BufferedImage thumbnail = null;
try {
thumbnail = get();
} catch (Exception ignored) {
}
if (thumbnail != null) {
imageCanvas.setImage(thumbnail);
}
}
};
thumbnailLoader.execute();
imageCanvas = new SliderBoxImageDisplay(imageSize.width, imageSize.height, this);
imageCanvas.setSize(imageSize.width, imageSize.height);
setComponentName(imageCanvas, "ImageCanvas");
imageScrollPane = new JScrollPane(imageCanvas);
imageScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
imageScrollPane.getVerticalScrollBar().setUnitIncrement(20);
imageScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
imageScrollPane.getHorizontalScrollBar().setUnitIncrement(20);
imageScrollPane.getViewport().setExtentSize(new Dimension(MAX_THUMBNAIL_WIDTH, 2 * MAX_THUMBNAIL_WIDTH));
setComponentName(imageScrollPane, "ImageScrollPane");
subsetWidthLabel = new JLabel("####", JLabel.RIGHT);
subsetHeightLabel = new JLabel("####", JLabel.RIGHT);
int sceneWidth;
int sceneHeight;
if(product.isMultiSize()) {
sceneWidth = product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth();
sceneHeight = product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight();
} else {
sceneWidth = product.getSceneRasterWidth();
sceneHeight = product.getSceneRasterHeight();
}
sourceWidthLabel = new JLabel(String.valueOf(sceneWidth), JLabel.RIGHT);
sourceHeightLabel = new JLabel(String.valueOf(sceneHeight), JLabel.RIGHT);
setToVisibleButton = new JButton("Use Preview");/*I18N*/
setToVisibleButton.setMnemonic('v');
setToVisibleButton.setToolTipText("Use coordinates of visible thumbnail area"); /*I18N*/
setToVisibleButton.addActionListener(this);
setComponentName(setToVisibleButton, "UsePreviewButton");
fixSceneWidthCheck = new JCheckBox("Fix full width");
fixSceneWidthCheck.setMnemonic('w');
fixSceneWidthCheck.setToolTipText("Checks whether or not to fix the full scene width");
fixSceneWidthCheck.addActionListener(this);
setComponentName(fixSceneWidthCheck, "FixWidthCheck");
fixSceneHeightCheck = new JCheckBox("Fix full height");
fixSceneHeightCheck.setMnemonic('h');
fixSceneHeightCheck.setToolTipText("Checks whether or not to fix the full scene height");
fixSceneHeightCheck.addActionListener(this);
setComponentName(fixSceneHeightCheck, "FixHeightCheck");
JPanel textInputPane = GridBagUtils.createPanel();
setComponentName(textInputPane, "TextInputPane");
final JTabbedPane tabbedPane = new JTabbedPane();
setComponentName(tabbedPane, "coordinatePane");
tabbedPane.addTab("Pixel Coordinates", createPixelCoordinatesPane());
tabbedPane.addTab("Geo Coordinates", createGeoCoordinatesPane());
tabbedPane.setEnabledAt(1, canUseGeoCoordinates(product));
GridBagConstraints gbc = GridBagUtils.createConstraints(
"insets.left=7,anchor=WEST,fill=HORIZONTAL, weightx=1.0");
GridBagUtils.setAttributes(gbc, "gridwidth=2");
GridBagUtils.addToPanel(textInputPane, tabbedPane, gbc, "gridx=0,gridy=0");
GridBagUtils.setAttributes(gbc, "insets.top=7,gridwidth=1");
GridBagUtils.addToPanel(textInputPane, new JLabel("Scene step X:"), gbc, "gridx=0,gridy=1");
GridBagUtils.addToPanel(textInputPane, UIUtils.createSpinner(paramSX, 1, "#0"), gbc, "gridx=1,gridy=1");
GridBagUtils.setAttributes(gbc, "insets.top=1");
GridBagUtils.addToPanel(textInputPane, new JLabel("Scene step Y:"), gbc, "gridx=0,gridy=2");
GridBagUtils.addToPanel(textInputPane, UIUtils.createSpinner(paramSY, 1, "#0"), gbc, "gridx=1,gridy=2");
GridBagUtils.setAttributes(gbc, "insets.top=4");
GridBagUtils.addToPanel(textInputPane, new JLabel("Subset scene width:"), gbc, "gridx=0,gridy=3");
GridBagUtils.addToPanel(textInputPane, subsetWidthLabel, gbc, "gridx=1,gridy=3");
GridBagUtils.setAttributes(gbc, "insets.top=1");
GridBagUtils.addToPanel(textInputPane, new JLabel("Subset scene height:"), gbc, "gridx=0,gridy=4");
GridBagUtils.addToPanel(textInputPane, subsetHeightLabel, gbc, "gridx=1,gridy=4");
GridBagUtils.setAttributes(gbc, "insets.top=4,gridwidth=1");
GridBagUtils.addToPanel(textInputPane, new JLabel("Source scene width:"), gbc, "gridx=0,gridy=5");
GridBagUtils.addToPanel(textInputPane, sourceWidthLabel, gbc, "gridx=1,gridy=5");
GridBagUtils.setAttributes(gbc, "insets.top=1");
GridBagUtils.addToPanel(textInputPane, new JLabel("Source scene height:"), gbc, "gridx=0,gridy=6");
GridBagUtils.addToPanel(textInputPane, sourceHeightLabel, gbc, "gridx=1,gridy=6");
GridBagUtils.setAttributes(gbc, "insets.top=7,gridwidth=1, gridheight=2");
GridBagUtils.addToPanel(textInputPane, setToVisibleButton, gbc, "gridx=0,gridy=7");
GridBagUtils.setAttributes(gbc, "insets.top=7,gridwidth=1, gridheight=1");
GridBagUtils.addToPanel(textInputPane, fixSceneWidthCheck, gbc, "gridx=1,gridy=7");
GridBagUtils.setAttributes(gbc, "insets.top=1,gridwidth=1");
GridBagUtils.addToPanel(textInputPane, fixSceneHeightCheck, gbc, "gridx=1,gridy=8");
JPanel referencePanel = new JPanel();
if(product.isMultiSize()) {
BoxLayout boxlayoutRef = new BoxLayout(referencePanel, BoxLayout.X_AXIS);
referencePanel.setLayout(boxlayoutRef);
referencePanel.add(new JLabel("Reference Band:"));
referencePanel.add(referenceCombo);
}
JPanel centerPanel = new JPanel();
BoxLayout boxlayout = new BoxLayout(centerPanel, BoxLayout.Y_AXIS);
centerPanel.setLayout(boxlayout);
centerPanel.add(referencePanel);
centerPanel.add(textInputPane);
setLayout(new BorderLayout(4, 4));
add(imageScrollPane, BorderLayout.WEST);
add(centerPanel, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7));
updateUIState(null);
imageCanvas.scrollRectToVisible(imageCanvas.getSliderBoxBounds());
}
private boolean canUseGeoCoordinates(Product product) {
final GeoCoding geoCoding = product.getSceneGeoCoding();
return geoCoding != null && geoCoding.canGetPixelPos() && geoCoding.canGetGeoPos();
}
private boolean canUseGeoCoordinates(RasterDataNode rasterDataNode) {
final GeoCoding geoCoding = rasterDataNode.getGeoCoding();
return geoCoding != null && geoCoding.canGetPixelPos() && geoCoding.canGetGeoPos();
}
private JPanel createGeoCoordinatesPane() {
JPanel geoCoordinatesPane = GridBagUtils.createPanel();
setComponentName(geoCoordinatesPane, "geoCoordinatesPane");
GridBagConstraints gbc = GridBagUtils.createConstraints(
"insets.left=3,anchor=WEST,fill=HORIZONTAL, weightx=1.0");
GridBagUtils.setAttributes(gbc, "insets.top=4");
GridBagUtils.addToPanel(geoCoordinatesPane, new JLabel("North latitude bound:"), gbc, "gridx=0,gridy=0");
GridBagUtils.addToPanel(geoCoordinatesPane, UIUtils.createSpinner(paramNorthLat1, 1.0, "#0.00#"),
gbc, "gridx=1,gridy=0");
GridBagUtils.setAttributes(gbc, "insets.top=1");
GridBagUtils.addToPanel(geoCoordinatesPane, new JLabel("West longitude bound:"), gbc, "gridx=0,gridy=1");
GridBagUtils.addToPanel(geoCoordinatesPane, UIUtils.createSpinner(paramWestLon1, 1.0, "#0.00#"),
gbc, "gridx=1,gridy=1");
GridBagUtils.setAttributes(gbc, "insets.top=4");
GridBagUtils.addToPanel(geoCoordinatesPane, new JLabel("South latitude bound:"), gbc, "gridx=0,gridy=2");
GridBagUtils.addToPanel(geoCoordinatesPane, UIUtils.createSpinner(paramSouthLat2, 1.0, "#0.00#"),
gbc, "gridx=1,gridy=2");
GridBagUtils.setAttributes(gbc, "insets.top=1");
GridBagUtils.addToPanel(geoCoordinatesPane, new JLabel("East longitude bound:"), gbc, "gridx=0,gridy=3");
GridBagUtils.addToPanel(geoCoordinatesPane, UIUtils.createSpinner(paramEastLon2, 1.0, "#0.00#"),
gbc, "gridx=1,gridy=3");
return geoCoordinatesPane;
}
private JPanel createPixelCoordinatesPane() {
GridBagConstraints gbc = GridBagUtils.createConstraints(
"insets.left=3,anchor=WEST,fill=HORIZONTAL, weightx=1.0");
JPanel pixelCoordinatesPane = GridBagUtils.createPanel();
setComponentName(pixelCoordinatesPane, "pixelCoordinatesPane");
GridBagUtils.setAttributes(gbc, "insets.top=4");
GridBagUtils.addToPanel(pixelCoordinatesPane, new JLabel("Scene start X:"), gbc, "gridx=0,gridy=0");
GridBagUtils.addToPanel(pixelCoordinatesPane, UIUtils.createSpinner(paramX1, 25, "#0"),
gbc, "gridx=1,gridy=0");
GridBagUtils.setAttributes(gbc, "insets.top=1");
GridBagUtils.addToPanel(pixelCoordinatesPane, new JLabel("Scene start Y:"), gbc, "gridx=0,gridy=1");
GridBagUtils.addToPanel(pixelCoordinatesPane, UIUtils.createSpinner(paramY1, 25, "#0"),
gbc, "gridx=1,gridy=1");
GridBagUtils.setAttributes(gbc, "insets.top=4");
GridBagUtils.addToPanel(pixelCoordinatesPane, new JLabel("Scene end X:"), gbc, "gridx=0,gridy=2");
GridBagUtils.addToPanel(pixelCoordinatesPane, UIUtils.createSpinner(paramX2, 25, "#0"),
gbc, "gridx=1,gridy=2");
GridBagUtils.setAttributes(gbc, "insets.top=1");
GridBagUtils.addToPanel(pixelCoordinatesPane, new JLabel("Scene end Y:"), gbc, "gridx=0,gridy=3");
GridBagUtils.addToPanel(pixelCoordinatesPane, UIUtils.createSpinner(paramY2, 25, "#0"),
gbc, "gridx=1,gridy=3");
return pixelCoordinatesPane;
}
private void setThumbnailSubsampling() {
int w ;
if(product.isMultiSize()) {
w = product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth();
} else {
w = product.getSceneRasterWidth();
}
thumbNailSubSampling = w / MAX_THUMBNAIL_WIDTH;
if (thumbNailSubSampling <= 1) {
thumbNailSubSampling = 1;
}
}
public void cancelThumbnailLoader() {
if (thumbnailLoader != null) {
thumbnailLoader.cancel(true);
}
}
public boolean isThumbnailLoaderCanceled() {
return thumbnailLoader != null && thumbnailLoader.isCancelled();
}
@Override
public void sliderBoxChanged(Rectangle sliderBoxBounds) {
int x1 = sliderBoxBounds.x * thumbNailSubSampling;
int y1 = sliderBoxBounds.y * thumbNailSubSampling;
int x2 = x1 + sliderBoxBounds.width * thumbNailSubSampling;
int y2 = y1 + sliderBoxBounds.height * thumbNailSubSampling;
int w = product.getSceneRasterWidth();
int h = product.getSceneRasterHeight();
if(product.isMultiSize()) {
w = product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth();
h = product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight();
}
if (x1 < 0) {
x1 = 0;
}
if (x1 > w - 2) {
x1 = w - 2;
}
if (y1 < 0) {
y1 = 0;
}
if (y1 > h - 2) {
y1 = h - 2;
}
if (x2 < 1) {
x2 = 1;
}
if (x2 > w - 1) {
x2 = w - 1;
}
if (y2 < 1) {
y2 = 1;
}
if (y2 > h - 1) {
y2 = h - 1;
}
// first reset the bounds, otherwise negative regions can occur
paramX1.setValue(0, null);
paramY1.setValue(0, null);
paramX2.setValue(w - 1, null);
paramY2.setValue(h - 1, null);
paramX1.setValue(x1, null);
paramY1.setValue(y1, null);
paramX2.setValue(x2, null);
paramY2.setValue(y2, null);
}
/**
* Invoked when an action occurs.
*/
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(fixSceneWidthCheck)) {
imageCanvas.setImageWidthFixed(fixSceneWidthCheck.isSelected());
final boolean enable = !fixSceneWidthCheck.isSelected();
paramX1.setUIEnabled(enable);
paramX2.setUIEnabled(enable);
}
if (e.getSource().equals(fixSceneHeightCheck)) {
imageCanvas.setImageHeightFixed(fixSceneHeightCheck.isSelected());
final boolean enable = !fixSceneHeightCheck.isSelected();
paramY1.setUIEnabled(enable);
paramY2.setUIEnabled(enable);
}
if (e.getSource().equals(setToVisibleButton)) {
imageCanvas.setSliderBoxBounds(imageScrollPane.getViewport().getViewRect(), true);
}
}
/**
* Called if the value of a parameter changed.
*
* @param event the parameter change event
*/
@Override
public void parameterValueChanged(ParamChangeEvent event) {
updateUIState(event);
}
private void initParameters() {
ParamGroup pg = new ParamGroup();
addPixelParameter(pg);
addGeoParameter(pg);
pg.addParamChangeListener(this);
}
private void addGeoParameter(ParamGroup pg) {
paramNorthLat1 = new Parameter("geo_lat1", 90.0);
paramNorthLat1.getProperties().setDescription("North bound latitude");
paramNorthLat1.getProperties().setPhysicalUnit("°");
paramNorthLat1.getProperties().setMinValue(-90.0);
paramNorthLat1.getProperties().setMaxValue(90.0);
pg.addParameter(paramNorthLat1);
paramWestLon1 = new Parameter("geo_lon1", -180.0);
paramWestLon1.getProperties().setDescription("West bound longitude");
paramWestLon1.getProperties().setPhysicalUnit("°");
paramWestLon1.getProperties().setMinValue(-180.0);
paramWestLon1.getProperties().setMaxValue(180.0);
pg.addParameter(paramWestLon1);
paramSouthLat2 = new Parameter("geo_lat2", -90.0);
paramSouthLat2.getProperties().setDescription("South bound latitude");
paramSouthLat2.getProperties().setPhysicalUnit("°");
paramSouthLat2.getProperties().setMinValue(-90.0);
paramSouthLat2.getProperties().setMaxValue(90.0);
pg.addParameter(paramSouthLat2);
paramEastLon2 = new Parameter("geo_lon2", 180.0);
paramEastLon2.getProperties().setDescription("East bound longitude");
paramEastLon2.getProperties().setPhysicalUnit("°");
paramEastLon2.getProperties().setMinValue(-180.0);
paramEastLon2.getProperties().setMaxValue(180.0);
pg.addParameter(paramEastLon2);
boolean canUseGeocoding;
if(product.isMultiSize()) {
canUseGeocoding = canUseGeoCoordinates(product.getBand((String) referenceCombo.getSelectedItem()));
} else {
canUseGeocoding = canUseGeoCoordinates(product);
}
if (canUseGeocoding) {
syncLatLonWithXYParams();
}
}
private void addPixelParameter(ParamGroup pg) {
int w ;
int h ;
if(product.isMultiSize()) {
w = product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth();
h = product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight();
} else {
w = product.getSceneRasterWidth();
h = product.getSceneRasterHeight();
}
int x1 = 0;
int y1 = 0;
int x2 = w - 1;
int y2 = h - 1;
int sx = 1;
int sy = 1;
if (givenProductSubsetDef != null) {
Rectangle region;
if(product.isMultiSize() && givenProductSubsetDef.getRegionMap() != null) {
region = givenProductSubsetDef.getRegionMap().get((String) referenceCombo.getSelectedItem());
} else {
region = givenProductSubsetDef.getRegion();
}
if (region != null) {
x1 = region.x;
y1 = region.y;
final int preX2 = x1 + region.width - 1;
if (preX2 < x2) {
x2 = preX2;
}
final int preY2 = y1 + region.height - 1;
if (preY2 < y2) {
y2 = preY2;
}
}
sx = givenProductSubsetDef.getSubSamplingX();
sy = givenProductSubsetDef.getSubSamplingY();
}
final int wMin = MIN_SUBSET_SIZE;
final int hMin = MIN_SUBSET_SIZE;
paramX1 = new Parameter("source_x1", x1);
paramX1.getProperties().setDescription("Start X co-ordinate given in pixels"); /*I18N*/
paramX1.getProperties().setMinValue(0);
paramX1.getProperties().setMaxValue((w - wMin - 1) > 0 ? w - wMin - 1 : 0);
paramY1 = new Parameter("source_y1", y1);
paramY1.getProperties().setDescription("Start Y co-ordinate given in pixels"); /*I18N*/
paramY1.getProperties().setMinValue(0);
paramY1.getProperties().setMaxValue((h - hMin - 1) > 0 ? h - hMin - 1 : 0);
paramX2 = new Parameter("source_x2", x2);
paramX2.getProperties().setDescription("End X co-ordinate given in pixels");/*I18N*/
paramX2.getProperties().setMinValue(wMin - 1);
final Integer maxValue = w - 1;
paramX2.getProperties().setMaxValue(maxValue);
paramY2 = new Parameter("source_y2", y2);
paramY2.getProperties().setDescription("End Y co-ordinate given in pixels");/*I18N*/
paramY2.getProperties().setMinValue(hMin - 1);
paramY2.getProperties().setMaxValue(h - 1);
paramSX = new Parameter("source_sx", sx);
paramSX.getProperties().setDescription("Sub-sampling in X-direction given in pixels");/*I18N*/
paramSX.getProperties().setMinValue(1);
paramSX.getProperties().setMaxValue(w / wMin + 1);
paramSY = new Parameter("source_sy", sy);
paramSY.getProperties().setDescription("Sub-sampling in Y-direction given in pixels");/*I18N*/
paramSY.getProperties().setMinValue(1);
paramSY.getProperties().setMaxValue(h / hMin + 1);
pg.addParameter(paramX1);
pg.addParameter(paramY1);
pg.addParameter(paramX2);
pg.addParameter(paramY2);
pg.addParameter(paramSX);
pg.addParameter(paramSY);
}
private void updateUIState(ParamChangeEvent event) {
if (updatingUI.compareAndSet(false, true)) {
try {
boolean canUseGeocoding;
if(product.isMultiSize()) {
canUseGeocoding = canUseGeoCoordinates(product.getBand((String) referenceCombo.getSelectedItem()));
} else {
canUseGeocoding = canUseGeoCoordinates(product);
}
if (event != null && canUseGeocoding) {
final String parmName = event.getParameter().getName();
if (parmName.startsWith("geo_")) {
final GeoPos geoPos1 = new GeoPos((Double) paramNorthLat1.getValue(),
(Double) paramWestLon1.getValue());
final GeoPos geoPos2 = new GeoPos((Double) paramSouthLat2.getValue(),
(Double) paramEastLon2.getValue());
updateXYParams(geoPos1, geoPos2);
} else if (parmName.startsWith("source_x") || parmName.startsWith("source_y")) {
syncLatLonWithXYParams();
}
}
int x1 = ((Number) paramX1.getValue()).intValue();
int y1 = ((Number) paramY1.getValue()).intValue();
int x2 = ((Number) paramX2.getValue()).intValue();
int y2 = ((Number) paramY2.getValue()).intValue();
int sx = ((Number) paramSX.getValue()).intValue();
int sy = ((Number) paramSY.getValue()).intValue();
if(product.isMultiSize()) {
productSubsetDef.setRegionMap(SubsetOp.computeRegionMap (computeROIToPositiveAxis(x1,y1,x2,y2),
(String) referenceCombo.getSelectedItem(),
product, null));
productSubsetDef.setSubSampling(sx, sy);
updateMemDisplay();
} else {
productSubsetDef.setSubsetRegion(new PixelSubsetRegion(computeROIToPositiveAxis(x1,y1,x2,y2), 0));
productSubsetDef.setSubSampling(sx, sy);
updateMemDisplay();
}
Dimension s;
if(product.isMultiSize()) {
s = productSubsetDef.getSceneRasterSize(product.getSceneRasterWidth(),
product.getSceneRasterHeight(),
(String) referenceCombo.getSelectedItem());
} else {
s = productSubsetDef.getSceneRasterSize(product.getSceneRasterWidth(),
product.getSceneRasterHeight());
}
subsetWidthLabel.setText(String.valueOf(s.getWidth()));
subsetHeightLabel.setText(String.valueOf(s.getHeight()));
int sceneWidth;
int sceneHeight;
if(product.isMultiSize()) {
sceneWidth = product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth();
sceneHeight = product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight();
} else {
sceneWidth = product.getSceneRasterWidth();
sceneHeight = product.getSceneRasterHeight();
}
sourceHeightLabel.setText(String.valueOf(sceneHeight));
sourceWidthLabel.setText(String.valueOf(sceneWidth));
setThumbnailSubsampling();
int sliderBoxX1 = x1 / thumbNailSubSampling;
int sliderBoxY1 = y1 / thumbNailSubSampling;
int sliderBoxX2 = x2 / thumbNailSubSampling;
int sliderBoxY2 = y2 / thumbNailSubSampling;
int sliderBoxW = sliderBoxX2 - sliderBoxX1 + 1;
int sliderBoxH = sliderBoxY2 - sliderBoxY1 + 1;
Rectangle box = getScaledRectangle(new Rectangle(sliderBoxX1, sliderBoxY1, sliderBoxW, sliderBoxH));
imageCanvas.setSliderBoxBounds(box);
} finally {
updatingUI.set(false);
}
}
}
private Rectangle computeROIToPositiveAxis(int x1,int y1, int x2, int y2)
{
// keep positive dimensions of the ROI
int diffX = x2 - x1;
int diffY = y2 - y1;
if(diffX<0)
x1=x1+diffX-1;
if(diffY<0)
y1=y1+diffY-1;
return new Rectangle(x1, y1, Math.abs(diffX)+1, Math.abs(diffY)+1);
}
private void syncLatLonWithXYParams() {
final PixelPos pixelPos1 = new PixelPos(((Number) paramX1.getValue()).intValue(),
((Number) paramY1.getValue()).intValue());
final PixelPos pixelPos2 = new PixelPos(((Number) paramX2.getValue()).intValue(),
((Number) paramY2.getValue()).intValue());
GeoCoding geoCoding;
if(product.isMultiSize()) {
geoCoding = product.getBand((String) referenceCombo.getSelectedItem()).getGeoCoding();
} else {
geoCoding = product.getSceneGeoCoding();
}
final GeoPos geoPos1 = geoCoding.getGeoPos(pixelPos1, null);
final GeoPos geoPos2 = geoCoding.getGeoPos(pixelPos2, null);
if(geoPos1.isValid()) {
double lat = geoPos1.getLat();
lat = MathUtils.crop(lat, -90.0, 90.0);
paramNorthLat1.setValue(lat, ex -> true);
double lon = geoPos1.getLon();
lon = MathUtils.crop(lon, -180.0, 180.0);
paramWestLon1.setValue(lon, ex -> true);
}
if (geoPos2.isValid()) {
double lat = geoPos2.getLat();
lat = MathUtils.crop(lat, -90.0, 90.0);
paramSouthLat2.setValue(lat, ex -> true);
double lon = geoPos2.getLon();
lon = MathUtils.crop(lon, -180.0, 180.0);
paramEastLon2.setValue(lon, ex -> true);
}
}
private void updateXYParams(GeoPos geoPos1, GeoPos geoPos2) {
GeoCoding geoCoding;
if(product.isMultiSize()) {
geoCoding = product.getBand((String) referenceCombo.getSelectedItem()).getGeoCoding();
} else {
geoCoding = product.getSceneGeoCoding();
}
final PixelPos pixelPos1 = geoCoding.getPixelPos(geoPos1, null);
if (!pixelPos1.isValid()) {
pixelPos1.setLocation(0, 0);
}
final PixelPos pixelPos2 = geoCoding.getPixelPos(geoPos2, null);
if (!pixelPos2.isValid()) {
if(product.isMultiSize()) {
pixelPos2.setLocation(product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth(),
product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight());
} else {
pixelPos2.setLocation(product.getSceneRasterWidth(),
product.getSceneRasterHeight());
}
}
final Rectangle.Float region = new Rectangle.Float();
region.setFrameFromDiagonal(pixelPos1.x, pixelPos1.y, pixelPos2.x, pixelPos2.y);
final Rectangle.Float productBounds;
if(product.isMultiSize()) {
productBounds = new Rectangle.Float(0, 0,
product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth(),
product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight());
} else {
productBounds = new Rectangle.Float(0, 0,
product.getSceneRasterWidth(),
product.getSceneRasterHeight());
}
Rectangle2D finalRegion = productBounds.createIntersection(region);
paramX1.setValue((int) finalRegion.getMinX(), ex -> true);
paramY1.setValue((int) finalRegion.getMinY(), ex -> true);
paramX2.setValue((int) finalRegion.getMaxX() - 1, ex -> true);
paramY2.setValue((int) finalRegion.getMaxY() - 1, ex -> true);
}
private Dimension getScaledImageSize() {
final int w;
final int h;
if(product.isMultiSize()) {
w = (product.getBand((String) referenceCombo.getSelectedItem()).getRasterWidth() - 1) / thumbNailSubSampling + 1;
h = (product.getBand((String) referenceCombo.getSelectedItem()).getRasterHeight() - 1) / thumbNailSubSampling + 1;
} else {
w = (product.getSceneRasterWidth() - 1) / thumbNailSubSampling + 1;
h = (product.getSceneRasterHeight() - 1) / thumbNailSubSampling + 1;
}
final Rectangle rectangle = new Rectangle(w, h);
return getScaledRectangle(rectangle).getSize();
}
private Rectangle getScaledRectangle(Rectangle rectangle) {
final AffineTransform i2mTransform ;
if(product.isMultiSize()) {
i2mTransform = Product.findImageToModelTransform(product.getBand((String) referenceCombo.getSelectedItem()).getGeoCoding());
} else {
i2mTransform = Product.findImageToModelTransform(product.getSceneGeoCoding());
}
final double scaleX = i2mTransform.getScaleX();
final double scaleY = i2mTransform.getScaleY();
double scaleFactorY = Math.abs(scaleY / scaleX);
final AffineTransform scaleTransform = AffineTransform.getScaleInstance(1.0, scaleFactorY);
return scaleTransform.createTransformedShape(rectangle).getBounds();
}
private BufferedImage createThumbNailImage(Dimension imgSize, ProgressMonitor pm) {
Assert.notNull(pm, "pm");
String thumbNailBandName = getThumbnailBandName();
Band thumbNailBand = product.getBand(thumbNailBandName);
Debug.trace("ProductSubsetDialog: Reading thumbnail data for band '" + thumbNailBandName + "'...");
pm.beginTask("Creating thumbnail image", 5);
BufferedImage image = null;
try {
MultiLevelSource multiLevelSource = ColoredBandImageMultiLevelSource.create(thumbNailBand,
SubProgressMonitor.create(pm, 1));
final ImageLayer imageLayer = new ImageLayer(multiLevelSource);
final int imageWidth = imgSize.width;
final int imageHeight = imgSize.height;
final int imageType = BufferedImage.TYPE_3BYTE_BGR;
image = new BufferedImage(imageWidth, imageHeight, imageType);
Viewport snapshotVp = new DefaultViewport(isModelYAxisDown(imageLayer));
final BufferedImageRendering imageRendering = new BufferedImageRendering(image, snapshotVp);
final Graphics2D graphics = imageRendering.getGraphics();
graphics.setColor(getBackground());
graphics.fillRect(0, 0, imageWidth, imageHeight);
snapshotVp.zoom(imageLayer.getModelBounds());
snapshotVp.moveViewDelta(snapshotVp.getViewBounds().x, snapshotVp.getViewBounds().y);
imageLayer.render(imageRendering);
pm.worked(4);
} finally {
pm.done();
}
return image;
}
private boolean isModelYAxisDown(ImageLayer baseImageLayer) {
return baseImageLayer.getImageToModelTransform().getDeterminant() > 0.0;
}
private String getThumbnailBandName() {
return ProductUtils.findSuitableQuicklookBandName(product);
}
}
private class ProductNodeSubsetPane extends JPanel {
private ProductNode[] productNodes;
private String[] includeAlways;
private List<JCheckBox> checkers;
private JCheckBox allCheck;
private JCheckBox noneCheck;
private boolean selected;
private ProductNodeSubsetPane(ProductNode[] productNodes, boolean selected) {
this(productNodes, null, selected);
}
private ProductNodeSubsetPane(ProductNode[] productNodes, String[] includeAlways, boolean selected) {
this.productNodes = productNodes;
this.includeAlways = includeAlways;
this.selected = selected;
createUI();
}
private void createUI() {
ActionListener productNodeCheckListener = e -> updateUIState();
checkers = new ArrayList<>(10);
JPanel checkersPane = GridBagUtils.createPanel();
setComponentName(checkersPane, "CheckersPane");
GridBagConstraints gbc = GridBagUtils.createConstraints("insets.left=4,anchor=WEST,fill=HORIZONTAL");
for (int i = 0; i < productNodes.length; i++) {
ProductNode productNode = productNodes[i];
String name = productNode.getName();
JCheckBox productNodeCheck = new JCheckBox(name);
productNodeCheck.setSelected(selected);
productNodeCheck.setFont(SMALL_PLAIN_FONT);
productNodeCheck.addActionListener(productNodeCheckListener);
if (includeAlways != null
&& StringUtils.containsIgnoreCase(includeAlways, name)) {
productNodeCheck.setSelected(true);
productNodeCheck.setEnabled(false);
} else if (givenProductSubsetDef != null) {
productNodeCheck.setSelected(givenProductSubsetDef.containsNodeName(name));
}
checkers.add(productNodeCheck);
String description = productNode.getDescription();
JLabel productNodeLabel = new JLabel(description != null ? description : " ");
productNodeLabel.setFont(SMALL_ITALIC_FONT);
GridBagUtils.addToPanel(checkersPane, productNodeCheck, gbc, "weightx=0,gridx=0,gridy=" + i);
GridBagUtils.addToPanel(checkersPane, productNodeLabel, gbc, "weightx=1,gridx=1,gridy=" + i);
}
// Add a last 'filler' row
GridBagUtils.addToPanel(checkersPane, new JLabel(" "), gbc,
"gridwidth=2,weightx=1,weighty=1,gridx=0,gridy=" + productNodes.length);
ActionListener allCheckListener = e -> {
if (e.getSource() == allCheck) {
checkAllProductNodes(true);
} else if (e.getSource() == noneCheck) {
checkAllProductNodes(false);
}
updateUIState();
};
allCheck = new JCheckBox("Select all");
allCheck.setName("selectAll");
allCheck.setMnemonic('a');
allCheck.addActionListener(allCheckListener);
noneCheck = new JCheckBox("Select none");
noneCheck.setName("SelectNone");
noneCheck.setMnemonic('n');
noneCheck.addActionListener(allCheckListener);
JScrollPane scrollPane = new JScrollPane(checkersPane);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPane.getVerticalScrollBar().setUnitIncrement(20);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.getHorizontalScrollBar().setUnitIncrement(20);
JPanel buttonRow = new JPanel(new FlowLayout(FlowLayout.LEFT, 4, 4));
buttonRow.add(allCheck);
buttonRow.add(noneCheck);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
add(buttonRow, BorderLayout.SOUTH);
setBorder(BorderFactory.createEmptyBorder(7, 7, 7, 7));
updateUIState();
}
void updateUIState() {
allCheck.setSelected(areAllProductNodesChecked(true));
noneCheck.setSelected(areAllProductNodesChecked(false));
updateSubsetDefNodeNameList();
}
String[] getSubsetNames() {
String[] names = new String[countChecked(true)];
int pos = 0;
for (int i = 0; i < checkers.size(); i++) {
JCheckBox checker = checkers.get(i);
if (checker.isSelected()) {
ProductNode productNode = productNodes[i];
names[pos] = productNode.getName();
pos++;
}
}
return names;
}
void checkAllProductNodes(boolean checked) {
for (JCheckBox checker : checkers) {
if (checker.isEnabled()) {
checker.setSelected(checked);
}
}
}
boolean areAllProductNodesChecked(boolean checked) {
return countChecked(checked) == checkers.size();
}
int countChecked(boolean checked) {
int counter = 0;
for (JCheckBox checker : checkers) {
if (checker.isSelected() == checked) {
counter++;
}
}
return counter;
}
}
}
| 62,486 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
TrackLayerTypeFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/TrackLayerTypeFactory.java | package org.esa.snap.ui.product;
import com.bc.ceres.core.ExtensionFactory;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.esa.snap.core.datamodel.VectorDataNode;
/**
* The {@link ExtensionFactory} that adapts {@link VectorDataNode}s using the {@code FeatureType} "org.esa.snap.TrackPoint"
* to the special {@link TrackLayerType}.
* <p>
* <i>Note: this is experimental code.</i>
*
* @author Norman Fomferra
* @since BEAM 4.10
*/
public class TrackLayerTypeFactory implements ExtensionFactory {
@Override
public Object getExtension(Object object, Class<?> extensionType) {
VectorDataNode node = (VectorDataNode) object;
if (TrackLayerType.isTrackPointNode(node)) {
return LayerTypeRegistry.getLayerType(TrackLayerType.class);
}
return null;
}
@Override
public Class<?>[] getExtensionTypes() {
return new Class<?>[]{VectorDataLayerType.class};
}
}
| 943 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleFeatureFigure.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/SimpleFeatureFigure.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.ui.product;
import com.bc.ceres.swing.figure.Figure;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.simple.SimpleFeature;
public interface SimpleFeatureFigure extends Figure {
SimpleFeature getSimpleFeature();
//todo remove this method - it is not needed and likely to cause confusion
Geometry getGeometry();
//todo remove this method - it is not needed and likely to cause confusion
void setGeometry(Geometry geometry);
void forceRegeneration();
}
| 1,246 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductPlacemarkView.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ProductPlacemarkView.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.ui.product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.ui.BasicView;
import org.esa.snap.ui.PopupMenuHandler;
import org.esa.snap.ui.io.TableModelCsvEncoder;
import org.openide.util.Utilities;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JLabel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableRowSorter;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Enumeration;
import java.util.List;
/**
* A view component used to display a product's metadata in tabular form.
*/
public class ProductPlacemarkView extends BasicView implements ProductNodeView {
private VectorDataNode vectorDataNode;
private final PlacemarkTableModel tableModel;
public ProductPlacemarkView(VectorDataNode vectorDataNode) {
this.vectorDataNode = vectorDataNode;
this.vectorDataNode.getProduct().addProductNodeListener(new PNL());
tableModel = new PlacemarkTableModel();
JTable placemarkTable = new JTable();
placemarkTable.setRowSorter(new TableRowSorter<>(tableModel));
placemarkTable.addMouseListener(new PopupMenuHandler(this));
placemarkTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
placemarkTable.setModel(tableModel);
final TableCellRenderer renderer = placemarkTable.getTableHeader().getDefaultRenderer();
final int margin = placemarkTable.getTableHeader().getColumnModel().getColumnMargin();
Enumeration<TableColumn> columns = placemarkTable.getColumnModel().getColumns();
while (columns.hasMoreElements()) {
TableColumn tableColumn = columns.nextElement();
final int width = getColumnMinWith(tableColumn, renderer, margin);
tableColumn.setMinWidth(width);
}
final JScrollPane scrollPane = new JScrollPane(placemarkTable);
setLayout(new BorderLayout());
add(scrollPane, BorderLayout.CENTER);
}
public VectorDataNode getVectorDataNode() {
return vectorDataNode;
}
/**
* Returns the currently visible product node.
*/
@Override
public ProductNode getVisibleProductNode() {
return vectorDataNode;
}
@Override
public JPopupMenu createPopupMenu(Component component) {
JPopupMenu popupMenu = new JPopupMenu();
List<? extends Action> viewActions = Utilities.actionsForPath("Context/ProductPlacemarkView");
for (Action action : viewActions) {
popupMenu.add(action);
}
popupMenu.add(new CopyToClipboardAction());
return popupMenu;
}
@Override
public JPopupMenu createPopupMenu(MouseEvent event) {
return null;
}
private int getColumnMinWith(TableColumn column, TableCellRenderer renderer, int margin) {
final Object headerValue = column.getHeaderValue();
final JLabel label = (JLabel) renderer.getTableCellRendererComponent(null, headerValue, false, false, 0, 0);
return label.getPreferredSize().width + margin;
}
private void onNodeChange(ProductNodeEvent event) {
ProductNode sourceNode = event.getSourceNode();
if (sourceNode == vectorDataNode) {
updateTable();
} else if (sourceNode.getOwner() == vectorDataNode.getPlacemarkGroup()) {
updateTable();
}
}
private class PlacemarkTableModel extends AbstractTableModel {
@Override
public int getRowCount() {
return vectorDataNode.getPlacemarkGroup().getNodeCount();
}
@Override
public int getColumnCount() {
return vectorDataNode.getFeatureType().getAttributeCount();
}
@Override
public String getColumnName(int columnIndex) {
return vectorDataNode.getFeatureType().getDescriptor(columnIndex).getLocalName();
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return vectorDataNode.getFeatureType().getDescriptor(columnIndex).getType().getBinding();
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return vectorDataNode.getPlacemarkGroup().get(rowIndex).getFeature().getAttribute(columnIndex);
}
}
private class PNL implements ProductNodeListener {
@Override
public void nodeChanged(ProductNodeEvent event) {
onNodeChange(event);
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
onNodeChange(event);
}
@Override
public void nodeAdded(ProductNodeEvent event) {
onNodeChange(event);
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
onNodeChange(event);
}
}
private void updateTable() {
tableModel.fireTableDataChanged();
}
private void copyTextDataToClipboard() {
final Cursor oldCursor = getCursor();
try {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
final String dataAsText = getDataAsText();
if (dataAsText != null) {
SystemUtils.copyToClipboard(dataAsText);
}
} finally {
setCursor(oldCursor);
}
}
private String getDataAsText() {
final StringWriter writer = new StringWriter();
try {
new TableModelCsvEncoder(tableModel).encodeCsv(writer);
writer.close();
} catch (IOException ignore) {
}
return writer.toString();
}
private class CopyToClipboardAction extends AbstractAction {
public CopyToClipboardAction() {
super("Copy to clipboard");
putValue(SHORT_DESCRIPTION, "The entire table content will be copied to the clipboard.");
}
@Override
public void actionPerformed(ActionEvent e) {
copyTextDataToClipboard();
}
}
}
| 7,283 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FileSelectionPatternDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/FileSelectionPatternDialog.java | package org.esa.snap.ui.product;
import org.esa.snap.ui.ModalDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Window;
class FileSelectionPatternDialog extends ModalDialog {
private final JTextField textField;
FileSelectionPatternDialog(String defaultPattern, Window parent) {
super(parent, "File/Directory Selection Pattern", ModalDialog.ID_OK_CANCEL_HELP, null);
final JPanel contentPane = new JPanel(new BorderLayout(8, 8));
contentPane.add(new JLabel("Please define a file/directory selection pattern. For example '*.nc'"), BorderLayout.NORTH);
contentPane.add(new JLabel("Pattern:"), BorderLayout.WEST);
textField = new JTextField(defaultPattern);
contentPane.add(textField, BorderLayout.CENTER);
setContent(contentPane);
}
public String getPattern() {
final String text = textField.getText();
return text != null ? text.trim() : null;
}
@Override
public int show() {
final int button = super.show();
if (button == ID_OK) {
final String text = getPattern();
if (text == null || text.length() == 0) {
showErrorDialog(getParent(), "Pattern field may not be empty.", "File/Directory Selection Pattern");
return ID_CANCEL;
}
}
return button;
}
}
| 1,447 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductSceneView.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ProductSceneView.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.ui.product;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.core.Assert;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.LayerFilter;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import com.bc.ceres.glayer.support.AbstractLayerListener;
import com.bc.ceres.glayer.support.ImageLayer;
import com.bc.ceres.glayer.support.LayerUtils;
import com.bc.ceres.glayer.swing.AdjustableViewScrollPane;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.glevel.MultiLevelSource;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.grender.ViewportAware;
import com.bc.ceres.grender.support.DefaultViewport;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.FigureChangeListener;
import com.bc.ceres.swing.figure.FigureCollection;
import com.bc.ceres.swing.figure.FigureEditor;
import com.bc.ceres.swing.figure.FigureEditorAware;
import com.bc.ceres.swing.figure.FigureSelection;
import com.bc.ceres.swing.figure.FigureStyle;
import com.bc.ceres.swing.figure.Handle;
import com.bc.ceres.swing.figure.ShapeFigure;
import com.bc.ceres.swing.selection.AbstractSelectionChangeListener;
import com.bc.ceres.swing.selection.Selection;
import com.bc.ceres.swing.selection.SelectionChangeEvent;
import com.bc.ceres.swing.selection.SelectionContext;
import com.bc.ceres.swing.undo.UndoContext;
import com.bc.ceres.swing.undo.support.DefaultUndoContext;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Placemark;
import org.esa.snap.core.datamodel.PlacemarkGroup;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.esa.snap.core.datamodel.RasterDataNode;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.image.ColoredMaskImageMultiLevelSource;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.layer.GraticuleLayer;
import org.esa.snap.core.layer.MaskCollectionLayer;
import org.esa.snap.core.layer.NoDataLayerType;
import org.esa.snap.core.layer.ProductLayerContext;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.ui.BasicView;
import org.esa.snap.ui.PixelPositionListener;
import org.esa.snap.ui.PopupMenuHandler;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.opengis.referencing.operation.TransformException;
import org.openide.util.Utilities;
import org.openide.util.actions.Presenter;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputListener;
import javax.swing.undo.UndoManager;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Area;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.RenderedImage;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Vector;
/**
* The class {@code ProductSceneView} is a high-level image display component for color index/RGB images created
* from one or more raster datasets of a data product.
* <p>
* <p>It is also capable of displaying a graticule (geographical grid) and a ROI associated with a displayed raster
* dataset.
*
* @author Norman Fomferra
*/
public class ProductSceneView extends BasicView
implements FigureEditorAware, ProductNodeView, PropertyChangeListener, ProductLayerContext, ViewportAware {
public static final String BASE_IMAGE_LAYER_ID = "org.esa.snap.layers.baseImage";
public static final String NO_DATA_LAYER_ID = "org.esa.snap.layers.noData";
public static final String VECTOR_DATA_LAYER_ID = VectorDataCollectionLayer.ID;
public static final String MASKS_LAYER_ID = MaskCollectionLayer.ID;
public static final String GRATICULE_LAYER_ID = "org.esa.snap.layers.graticule";
/**
* Property name for the pixel border
*/
public static final String PREFERENCE_KEY_PIXEL_BORDER_SHOWN = "pixel.border.shown";
/**
* Name of property which switches display of af a navigation control in the image view.
*/
public static final String PREFERENCE_KEY_IMAGE_NAV_CONTROL_SHOWN = "image.navControlShown";
/**
* Name of property which switches display of af a navigation control in the image view.
*/
public static final String PREFERENCE_KEY_IMAGE_SCROLL_BARS_SHOWN = "image.scrollBarsShown";
/**
* Name of property which inverts the zooming with the mouse wheel.
*/
public static final String PREFERENCE_KEY_INVERT_ZOOMING = "image.reverseZooming";
/**
* Name of property of image info
*/
public static final String PROPERTY_NAME_IMAGE_INFO = "imageInfo";
/**
* Name of property of selected layer
*/
public static final String PROPERTY_NAME_SELECTED_LAYER = "selectedLayer";
/**
* Name of property of selected pin
*/
public static final String PROPERTY_NAME_SELECTED_PIN = "selectedPin";
public static final Color DEFAULT_IMAGE_BACKGROUND_COLOR = new Color(51, 51, 51);
private ProductSceneImage sceneImage;
private LayerCanvas layerCanvas;
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Properties corresponding to the base image displaying the raster data returned by #getRaster()
//
// layer which displays the base image
private final ImageLayer baseImageLayer;
// current resolution level of the base image
private int currentLevel = 0;
// current pixel X (from mouse cursor) at current resolution level of the base image
private int currentLevelPixelX = -1;
// current pixel Y (from mouse cursor) at current resolution level of the base image
private int currentLevelPixelY = -1;
// current pixel X (from mouse cursor) at highest resolution level of the base image
private int currentPixelX = -1;
// current pixel Y (from mouse cursor) at highest resolution level of the base image
private int currentPixelY = -1;
// display properties for the current pixel (from mouse cursor)
private boolean pixelBorderShown; // can it be shown?
private boolean pixelBorderDrawn; // has it been drawn?
private double pixelBorderViewScale;
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private final Vector<PixelPositionListener> pixelPositionListeners;
private Layer selectedLayer;
private ComponentAdapter layerCanvasComponentHandler;
private LayerCanvasMouseHandler layerCanvasMouseHandler;
private RasterChangeHandler rasterChangeHandler;
private boolean scrollBarsShown;
private AdjustableViewScrollPane scrollPane;
private UndoContext undoContext;
private VectorDataFigureEditor figureEditor;
public ProductSceneView(ProductSceneImage sceneImage) {
this(sceneImage, new UndoManager());
}
public ProductSceneView(ProductSceneImage sceneImage, UndoManager undoManager) {
Assert.notNull(sceneImage, "sceneImage");
setOpaque(true);
setLayout(new BorderLayout());
// todo - use sceneImage.getConfiguration() (nf, 18.09.2008)
setBackground(DEFAULT_IMAGE_BACKGROUND_COLOR);
this.pixelBorderShown = sceneImage.getConfiguration().getPropertyBool(PREFERENCE_KEY_PIXEL_BORDER_SHOWN, true);
this.sceneImage = sceneImage;
this.baseImageLayer = sceneImage.getBaseImageLayer();
this.pixelBorderViewScale = 2.0;
this.pixelPositionListeners = new Vector<>();
undoContext = new DefaultUndoContext(this, undoManager);
DefaultViewport viewport = new DefaultViewport(isModelYAxisDown(baseImageLayer));
final Layer rootLayer = sceneImage.getRootLayer();
this.layerCanvas = new LayerCanvas(rootLayer, viewport);
rootLayer.addListener(new AbstractLayerListener() {
@Override
public void handleLayersRemoved(Layer parentLayer, Layer[] childLayers) {
for (Layer childLayer : childLayers) {
if (childLayer == selectedLayer) {
setSelectedLayer(null);
return;
}
}
}
});
final boolean navControlShown = sceneImage.getConfiguration().getPropertyBool(
PREFERENCE_KEY_IMAGE_NAV_CONTROL_SHOWN, true);
this.layerCanvas.setNavControlShown(navControlShown);
this.layerCanvas.setAntialiasing(true);
this.layerCanvas.setPreferredSize(new Dimension(400, 400));
this.layerCanvas.addOverlay((canvas, rendering) -> {
figureEditor.drawFigureSelection(rendering);
figureEditor.drawSelectionRectangle(rendering);
});
figureEditor = new VectorDataFigureEditor(this);
figureEditor.addSelectionChangeListener(new PinSelectionChangeListener());
this.scrollBarsShown = sceneImage.getConfiguration().getPropertyBool(PREFERENCE_KEY_IMAGE_SCROLL_BARS_SHOWN,
false);
if (scrollBarsShown) {
this.scrollPane = createScrollPane();
add(scrollPane, BorderLayout.CENTER);
} else {
add(layerCanvas, BorderLayout.CENTER);
}
registerLayerCanvasListeners();
this.rasterChangeHandler = new RasterChangeHandler();
getRaster().getProduct().addProductNodeListener(rasterChangeHandler);
setMaskOverlayEnabled(true);
setName(sceneImage.getName());
appyLayerProperties(sceneImage.getConfiguration());
sceneImage.getConfiguration().addPropertyChangeListener(this);
addDefaultLayers(sceneImage);
}
private void addDefaultLayers(final ProductSceneImage sceneImage) {
final Layer rootLayer = sceneImage.getRootLayer();
final Set<LayerType> layerTypes = LayerTypeRegistry.getLayerTypes();
for (LayerType layerType : layerTypes) {
if (layerType.isValidFor(sceneImage) && layerType.createWithSceneView(sceneImage)) {
PropertyContainer config = new PropertyContainer();
config.addProperty(Property.create("raster", getRaster()));
Layer layer = layerType.createLayer(sceneImage, config);
rootLayer.getChildren().add(0, layer);
layer.setVisible(true);
}
}
}
/**
* Called if the property map changed. Simply calls {@link #appyLayerProperties(PropertyMap)}.
*/
@Override
public void propertyChange(PropertyChangeEvent evt) {
appyLayerProperties(sceneImage.getConfiguration());
}
public UndoContext getUndoContext() {
return undoContext;
}
@Override
public FigureEditor getFigureEditor() {
return figureEditor;
}
@Override
public Viewport getViewport() {
return layerCanvas.getViewport();
}
public int getCurrentPixelX() {
return currentPixelX;
}
public int getCurrentPixelY() {
return currentPixelY;
}
public boolean isCurrentPixelPosValid() {
return isPixelPosValid(currentLevelPixelX, currentLevelPixelY, currentLevel);
}
private AdjustableViewScrollPane createScrollPane() {
AbstractButton zoomAllButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/ZoomAll13.gif"),
false);
zoomAllButton.setFocusable(false);
zoomAllButton.setFocusPainted(false);
zoomAllButton.addActionListener(e -> getLayerCanvas().zoomAll());
AdjustableViewScrollPane scrollPane = new AdjustableViewScrollPane(layerCanvas);
// todo - use sceneImage.getConfiguration() (nf, 18.09.2008)
scrollPane.setBackground(DEFAULT_IMAGE_BACKGROUND_COLOR);
scrollPane.setCornerComponent(zoomAllButton);
return scrollPane;
}
public ProductSceneImage getSceneImage() {
return sceneImage;
}
/**
* Gets the current selection context, if any.
*
* @return The current selection context, or {@code null} if none exists.
* @since BEAM 4.7
*/
@Override
public SelectionContext getSelectionContext() {
return getFigureEditor().getSelectionContext();
}
/**
* @return The root layer.
*/
@Override
public Layer getRootLayer() {
return sceneImage.getRootLayer();
}
/**
* The coordinate reference system (CRS) used by all the layers in this context.
* May be used by a {@link com.bc.ceres.glayer.LayerType} in order to decide whether
* the source can provide a new layer instance for this context.
*
* @return The CRS. May be {@code null}.
*/
@Override
public Object getCoordinateReferenceSystem() {
return sceneImage.getCoordinateReferenceSystem();
}
public LayerCanvas getLayerCanvas() {
return layerCanvas;
}
/**
* Returns the currently visible product node.
*/
@Override
public ProductNode getVisibleProductNode() {
if (isRGB()) {
return getProduct();
}
return getRaster();
}
/**
* If the {@code preferredSize} has been set to a
* non-{@code null} value just returns it.
* If the UI delegate's {@code getPreferredSize}
* method returns a non {@code null} value then return that;
* otherwise defer to the component's layout manager.
*
* @return the value of the {@code preferredSize} property
* @see #setPreferredSize
* @see javax.swing.plaf.ComponentUI
*/
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
} else {
if (getLayerCanvas() != null) {
return getLayerCanvas().getPreferredSize();
} else {
return super.getPreferredSize();
}
}
}
@Override
public JPopupMenu createPopupMenu(Component component) {
return null;
}
@Override
public JPopupMenu createPopupMenu(MouseEvent event) {
JPopupMenu popupMenu = new JPopupMenu();
List<? extends Action> viewActions = Utilities.actionsForPath("Context/ProductSceneView");
for (Action action : viewActions) {
if(action instanceof Presenter.Popup) {
popupMenu.add(((Presenter.Popup) action).getPopupPresenter());
}else {
JMenuItem menuItem = popupMenu.add(action);
String popupText = (String) action.getValue("popupText");
if (StringUtils.isNotNullAndNotEmpty(popupText)) {
menuItem.setText(popupText);
}
}
}
return popupMenu;
}
/**
* Releases all of the resources used by this object instance and all of its owned children. Its primary use is to
* allow the garbage collector to perform a vanilla job.
* <p>
* <p>This method should be called only if it is for sure that this object instance will never be used again. The
* results of referencing an instance of this class after a call to {@code dispose()} are undefined.
* <p>
* <p>Overrides of this method should always call {@code super.dispose();} after disposing this instance.
*/
@Override
public synchronized void dispose() {
if (pixelPositionListeners != null) {
pixelPositionListeners.clear();
}
deregisterLayerCanvasListeners();
if (sceneImage != null) {
sceneImage.getConfiguration().removePropertyChangeListener(this);
}
for (int i = 0; i < getSceneImage().getRasters().length; i++) {
final RasterDataNode raster = getSceneImage().getRasters()[i];
if (raster instanceof RGBChannel) {
RGBChannel rgbChannel = (RGBChannel) raster;
rgbChannel.dispose();
}
sceneImage.getRasters()[i] = null;
}
sceneImage = null;
if (getLayerCanvas() != null) {
// ensure that imageDisplay.dispose() is run in the EDT
SwingUtilities.invokeLater(this::disposeImageDisplayComponent);
}
super.dispose();
}
/**
* @return the associated product.
*/
@Override
public Product getProduct() {
return getRaster().getProduct();
}
@Override
public ProductNode getProductNode() {
return getRaster();
}
public String getSceneName() {
return getSceneImage().getName();
}
public ImageInfo getImageInfo() {
return getSceneImage().getImageInfo();
}
public void setImageInfo(ImageInfo imageInfo) {
final ImageInfo oldImageInfo = getImageInfo();
getSceneImage().setImageInfo(imageInfo);
updateImage();
firePropertyChange(PROPERTY_NAME_IMAGE_INFO, oldImageInfo, imageInfo);
}
/**
* Gets the number of raster datasets.
*
* @return the number of raster datasets, always {@code 1} for single banded palette images or {@code 3}
* for RGB images
*/
public int getNumRasters() {
return getSceneImage().getRasters().length;
}
/**
* Gets the product raster with the specified index.
*
* @param index the zero-based product raster index
* @return the product raster with the given index
*/
public RasterDataNode getRaster(int index) {
return getSceneImage().getRasters()[index];
}
/**
* Gets the product raster of a single banded view.
*
* @return the product raster, in case of a 3-banded RGB view it returns the first raster.
* @see #isRGB()
*/
public RasterDataNode getRaster() {
return getSceneImage().getRasters()[0];
}
/**
* Gets all rasters of this view.
*
* @return all rasters of this view, array size is either 1 or 3 (RGB)
*/
public RasterDataNode[] getRasters() {
return getSceneImage().getRasters();
}
public void setRasters(RasterDataNode[] rasters) {
getSceneImage().setRasters(rasters);
}
public boolean isRGB() {
return getSceneImage().getRasters().length >= 3;
}
public boolean isNoDataOverlayEnabled() {
final Layer noDataLayer = getNoDataLayer(false);
return noDataLayer != null && noDataLayer.isVisible();
}
public void setNoDataOverlayEnabled(boolean enabled) {
if (isNoDataOverlayEnabled() != enabled) {
getNoDataLayer(true).setVisible(enabled);
}
}
public ImageLayer getBaseImageLayer() {
return getSceneImage().getBaseImageLayer();
}
public boolean isGraticuleOverlayEnabled() {
final GraticuleLayer graticuleLayer = getGraticuleLayer(false);
return graticuleLayer != null && graticuleLayer.isVisible();
}
public void setGraticuleOverlayEnabled(boolean enabled) {
if (isGraticuleOverlayEnabled() != enabled) {
getGraticuleLayer(true).setVisible(enabled);
}
}
public boolean isPinOverlayEnabled() {
Layer pinLayer = getPinLayer(false);
return pinLayer != null && pinLayer.isVisible();
}
public void setPinOverlayEnabled(boolean enabled) {
if (isPinOverlayEnabled() != enabled) {
Layer layer = getPinLayer(true);
layer.setVisible(enabled);
setSelectedLayer(layer);
}
}
public boolean isGcpOverlayEnabled() {
Layer gcpLayer = getGcpLayer(false);
return gcpLayer != null && gcpLayer.isVisible();
}
public void setGcpOverlayEnabled(boolean enabled) {
if (isGcpOverlayEnabled() != enabled) {
Layer layer = getGcpLayer(true);
layer.setVisible(enabled);
setSelectedLayer(layer);
}
}
public boolean isMaskOverlayEnabled() {
final Layer layer = getMaskCollectionLayer(false);
return layer != null && layer.isVisible();
}
public void setMaskOverlayEnabled(boolean enabled) {
if (isMaskOverlayEnabled() != enabled) {
getMaskCollectionLayer(true).setVisible(enabled);
}
}
/**
* @param vectorDataNodes The vector data nodes whose layer shall be made visible.
* @since BEAM 4.10
*/
public void setLayersVisible(VectorDataNode... vectorDataNodes) {
for (VectorDataNode vectorDataNode : vectorDataNodes) {
final LayerFilter nodeFilter = VectorDataLayerFilterFactory.createNodeFilter(vectorDataNode);
Layer vectorDataLayer = LayerUtils.getChildLayer(getRootLayer(),
LayerUtils.SEARCH_DEEP,
nodeFilter);
if (vectorDataLayer != null) {
vectorDataLayer.setVisible(true);
}
}
}
public ShapeFigure getCurrentShapeFigure() {
FigureSelection figureSelection = getFigureEditor().getFigureSelection();
if (figureSelection.getFigureCount() > 0) {
Figure figure = figureSelection.getFigure(0);
if (figure instanceof ShapeFigure) {
return (ShapeFigure) figure;
}
} else {
Layer layer = null;
final Layer selLayer = getSelectedLayer();
if (selLayer instanceof VectorDataLayer) {
final VectorDataLayer vectorLayer = (VectorDataLayer) selLayer;
if (vectorLayer.getVectorDataNode() != null) {
final String typeName = vectorLayer.getVectorDataNode().getFeatureType().getTypeName();
if (Product.GEOMETRY_FEATURE_TYPE_NAME.equals(typeName)) {
layer = vectorLayer;
}
}
}
if (layer == null) {
layer = LayerUtils.getChildLayer(getRootLayer(), LayerUtils.SearchMode.DEEP,
VectorDataLayerFilterFactory.createGeometryFilter());
}
if (layer != null) {
final VectorDataLayer vectorDataLayer = (VectorDataLayer) layer;
if (vectorDataLayer.getFigureCollection().getFigureCount() > 0) {
Figure figure = vectorDataLayer.getFigureCollection().getFigure(0);
if (figure instanceof ShapeFigure) {
return (ShapeFigure) figure;
}
}
}
}
return null;
}
public void setScrollBarsShown(boolean scrollBarsShown) {
if (scrollBarsShown != this.scrollBarsShown) {
this.scrollBarsShown = scrollBarsShown;
if (scrollBarsShown) {
remove(layerCanvas);
scrollPane = createScrollPane();
add(scrollPane, BorderLayout.CENTER);
} else {
remove(scrollPane);
scrollPane = null;
add(layerCanvas, BorderLayout.CENTER);
}
invalidate();
validate();
repaint();
}
}
/**
* Called after SNAP preferences have changed.
* This behaviour is deprecated since we want to uswe separate style editors for each layers.
*
* @param configuration the configuration.
*/
public void appyLayerProperties(PropertyMap configuration) {
setScrollBarsShown(configuration.getPropertyBool(PREFERENCE_KEY_IMAGE_SCROLL_BARS_SHOWN, false));
layerCanvas.setAntialiasing(true);
layerCanvas.setNavControlShown(configuration.getPropertyBool(PREFERENCE_KEY_IMAGE_NAV_CONTROL_SHOWN, true));
layerCanvas.setBackground(
configuration.getPropertyColor("image.background.color", DEFAULT_IMAGE_BACKGROUND_COLOR));
layerCanvasMouseHandler.setInvertZooming(configuration.getPropertyBool(PREFERENCE_KEY_INVERT_ZOOMING, false));
ImageLayer imageLayer = getBaseImageLayer();
if (imageLayer != null) {
ProductSceneImage.applyBaseImageLayerStyle(configuration, imageLayer);
}
Layer noDataLayer = getNoDataLayer(false);
if (noDataLayer != null) {
ProductSceneImage.applyNoDataLayerStyle(configuration, noDataLayer);
}
Layer collectionLayer = getVectorDataCollectionLayer(false);
if (collectionLayer != null) {
ProductSceneImage.applyFigureLayerStyle(configuration, collectionLayer);
}
GraticuleLayer graticuleLayer = getGraticuleLayer(false);
if (graticuleLayer != null) {
ProductSceneImage.applyGraticuleLayerStyle(configuration, graticuleLayer);
}
}
/**
* Adds a new pixel position listener to this image display component. If
* the component already contains the given listener, the method does
* nothing.
*
* @param listener the pixel position listener to be added
*/
public final void addPixelPositionListener(PixelPositionListener listener) {
if (listener == null) {
return;
}
if (pixelPositionListeners.contains(listener)) {
return;
}
pixelPositionListeners.add(listener);
}
/**
* Removes a pixel position listener from this image display component.
*
* @param listener the pixel position listener to be removed
*/
public final void removePixelPositionListener(PixelPositionListener listener) {
if (listener == null || pixelPositionListeners.isEmpty()) {
return;
}
pixelPositionListeners.remove(listener);
}
public Layer getSelectedLayer() {
return selectedLayer;
}
public void setSelectedLayer(Layer layer) {
Layer oldLayer = selectedLayer;
if (oldLayer != layer) {
selectedLayer = layer;
firePropertyChange(PROPERTY_NAME_SELECTED_LAYER, oldLayer, selectedLayer);
maybeUpdateFigureEditor();
}
}
/**
* @param vectorDataNode The vector data node, whose layer shall be selected.
* @return The layer, or {@code null}.
* @since BEAM 4.7
*/
public VectorDataLayer selectVectorDataLayer(VectorDataNode vectorDataNode) {
LayerFilter layerFilter = new VectorDataLayerFilter(vectorDataNode);
VectorDataLayer layer = (VectorDataLayer) LayerUtils.getChildLayer(getRootLayer(),
LayerUtils.SEARCH_DEEP,
layerFilter);
if (layer != null) {
setSelectedLayer(layer);
}
return layer;
}
/**
* @param pin The pins to test.
* @return {@code true}, if the pin is selected.
* @since BEAM 4.7
*/
public boolean isPinSelected(Placemark pin) {
return isPlacemarkSelected(getProduct().getPinGroup(), pin);
}
/**
* @param gcp The ground control point to test.
* @return {@code true}, if the ground control point is selected.
* @since BEAM 4.7
*/
public boolean isGcpSelected(Placemark gcp) {
return isPlacemarkSelected(getProduct().getGcpGroup(), gcp);
}
/**
* @return The (first) selected pin.
* @since BEAM 4.7
*/
public Placemark getSelectedPin() {
final Product product = getProduct();
return product != null ? getSelectedPlacemark(product.getPinGroup()) : null;
}
/**
* @return The selected pins.
* @since BEAM 4.7
*/
public Placemark[] getSelectedPins() {
return getSelectedPlacemarks(getProduct().getPinGroup());
}
/**
* @return The selected ground control points.
* @since BEAM 4.7
*/
public Placemark[] getSelectedGcps() {
return getSelectedPlacemarks(getProduct().getGcpGroup());
}
/**
* @param pins The selected pins.
* @since BEAM 4.7
*/
public void selectPins(Placemark[] pins) {
selectPlacemarks(getProduct().getPinGroup(), pins);
}
/**
* @param gpcs The selected ground control points.
* @since BEAM 4.7
*/
public void selectGcps(Placemark[] gpcs) {
selectPlacemarks(getProduct().getGcpGroup(), gpcs);
}
/**
* @return The (first) selected feature figure.
* @since BEAM 4.7
*/
public SimpleFeatureFigure getSelectedFeatureFigure() {
Figure[] figures = figureEditor.getFigureSelection().getFigures();
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
return (SimpleFeatureFigure) figure;
}
}
return null;
}
/**
* Gets either the selected figures, or all the figures of the currently selected layer.
*
* @param selectedOnly If {@code true}, only selected figures are returned.
* @return The feature figures or an empty array.
* @since BEAM 4.10
*/
public SimpleFeatureFigure[] getFeatureFigures(boolean selectedOnly) {
ArrayList<SimpleFeatureFigure> selectedFigures = new ArrayList<>();
collectFeatureFigures(figureEditor.getFigureSelection(), selectedFigures);
if (selectedFigures.isEmpty()
&& !selectedOnly
&& getSelectedLayer() instanceof VectorDataLayer) {
VectorDataLayer vectorDataLayer = (VectorDataLayer) getSelectedLayer();
collectFeatureFigures(vectorDataLayer.getFigureCollection(), selectedFigures);
}
return selectedFigures.toArray(new SimpleFeatureFigure[selectedFigures.size()]);
}
private void collectFeatureFigures(FigureCollection figureCollection, List<SimpleFeatureFigure> selectedFigures) {
Figure[] figures = figureCollection.getFigures();
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
selectedFigures.add((SimpleFeatureFigure) figure);
}
}
}
public boolean selectPlacemarks(PlacemarkGroup placemarkGroup, Placemark[] placemarks) {
VectorDataLayer layer = selectVectorDataLayer(placemarkGroup.getVectorDataNode());
if (layer != null) {
FigureCollection figureCollection = layer.getFigureCollection();
Figure[] figures = figureCollection.getFigures();
ArrayList<SimpleFeatureFigure> selectedFigures = new ArrayList<>(figures.length);
HashSet<Placemark> placemarkSet = new HashSet<>(Arrays.asList(placemarks));
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure featureFigure = (SimpleFeatureFigure) figure;
Placemark placemark = placemarkGroup.getPlacemark(featureFigure.getSimpleFeature());
if (placemarkSet.contains(placemark)) {
selectedFigures.add(featureFigure);
}
}
}
figureEditor.getFigureSelection().removeAllFigures();
figureEditor.getFigureSelection().addFigures(selectedFigures.toArray(new Figure[selectedFigures.size()]));
final int selectionStage = Math.min(selectedFigures.size(), 2);
figureEditor.getFigureSelection().setSelectionStage(selectionStage);
return true;
}
return false;
}
private boolean isPlacemarkSelected(PlacemarkGroup placemarkGroup, Placemark placemark) {
Figure[] figures = figureEditor.getFigureSelection().getFigures();
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure featureFigure = (SimpleFeatureFigure) figure;
Placemark pin = placemarkGroup.getPlacemark(featureFigure.getSimpleFeature());
if (pin == placemark) {
return true;
}
}
}
return false;
}
private Placemark getSelectedPlacemark(PlacemarkGroup placemarkGroup) {
Figure[] figures = figureEditor.getFigureSelection().getFigures();
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure featureFigure = (SimpleFeatureFigure) figure;
Placemark placemark = placemarkGroup.getPlacemark(featureFigure.getSimpleFeature());
if (placemark != null) {
return placemark;
}
}
}
return null;
}
private Placemark[] getSelectedPlacemarks(PlacemarkGroup placemarkGroup) {
Figure[] figures = figureEditor.getFigureSelection().getFigures();
ArrayList<Placemark> selectedPlacemarks = new ArrayList<>(figures.length);
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure featureFigure = (SimpleFeatureFigure) figure;
Placemark placemark = placemarkGroup.getPlacemark(featureFigure.getSimpleFeature());
if (placemark != null) {
selectedPlacemarks.add(placemark);
}
}
}
return selectedPlacemarks.toArray(new Placemark[selectedPlacemarks.size()]);
}
private void maybeUpdateFigureEditor() {
if (selectedLayer instanceof VectorDataLayer) {
VectorDataLayer vectorDataLayer = (VectorDataLayer) selectedLayer;
figureEditor.vectorDataLayerSelected(vectorDataLayer);
}
}
public void disposeLayers() {
getSceneImage().getRootLayer().dispose();
}
public AffineTransform getBaseImageToViewTransform() {
AffineTransform viewToModelTransform = layerCanvas.getViewport().getViewToModelTransform();
AffineTransform modelToImageTransform = getBaseImageLayer().getModelToImageTransform();
viewToModelTransform.concatenate(modelToImageTransform);
try {
return viewToModelTransform.createInverse();
} catch (NoninvertibleTransformException e) {
throw new RuntimeException(e);
}
}
/**
* @return the visible image area in pixel coordinates
*/
public Rectangle getVisibleImageBounds() {
final ImageLayer imageLayer = getBaseImageLayer();
if (imageLayer != null) {
final RenderedImage image = imageLayer.getImage();
final Area imageArea = new Area(new Rectangle(0, 0, image.getWidth(), image.getHeight()));
final Area visibleImageArea = new Area(
imageLayer.getModelToImageTransform().createTransformedShape(getVisibleModelBounds()));
imageArea.intersect(visibleImageArea);
return imageArea.getBounds();
}
return null;
}
/**
* @return the visible area in model coordinates
*/
public Rectangle2D getVisibleModelBounds() {
final Viewport viewport = layerCanvas.getViewport();
return viewport.getViewToModelTransform().createTransformedShape(viewport.getViewBounds()).getBounds2D();
}
/**
* @return the model bounds in model coordinates
*/
public Rectangle2D getModelBounds() {
return layerCanvas.getLayer().getModelBounds();
}
public double getOrientation() {
return layerCanvas.getViewport().getOrientation();
}
public double getZoomFactor() {
return layerCanvas.getViewport().getZoomFactor();
}
public void zoom(Rectangle2D modelRect) {
layerCanvas.getViewport().zoom(modelRect);
}
public void zoom(double x, double y, double viewScale) {
if (viewScale > 0) {
layerCanvas.getViewport().setZoomFactor(viewScale, x, y);
}
}
public boolean synchronizeViewportIfPossible(ProductSceneView thatView) {
final RasterDataNode thisRaster = getRaster();
final RasterDataNode thatRaster = thatView.getRaster();
final Product thisProduct = thisRaster.getProduct();
if (thisProduct.isSceneCrsEqualToModelCrsOf(thatRaster)) {
final Viewport thisViewport = layerCanvas.getViewport();
final Viewport thatViewport = thatView.layerCanvas.getViewport();
thatViewport.setTransform(thisViewport);
return true;
} else if (thisProduct == thatRaster.getProduct()) {
final Viewport thisViewport = layerCanvas.getViewport();
final Viewport thatViewport = thatView.layerCanvas.getViewport();
final Rectangle thisViewBounds = thisViewport.getViewBounds();
final Rectangle thisModelBounds = thisViewport.getViewToModelTransform().createTransformedShape(thisViewBounds).getBounds();
try {
final Rectangle sceneBounds = thisRaster.getModelToSceneTransform().createTransformedShape(thisModelBounds).getBounds();
final Rectangle thatModelBounds = thatRaster.getSceneToModelTransform().createTransformedShape(sceneBounds).getBounds();
thatViewport.zoom(thatModelBounds);
return true;
} catch (TransformException e) {
//try code below
}
}
final GeoCoding thisGeoCoding = thisRaster.getGeoCoding();
final GeoCoding thatGeoCoding = thatRaster.getGeoCoding();
if (thisGeoCoding != null && thatGeoCoding != null && thisGeoCoding.canGetGeoPos() && thatGeoCoding.canGetPixelPos()) {
final Viewport thisViewport = layerCanvas.getViewport();
final Viewport thatViewport = thatView.layerCanvas.getViewport();
final double viewCenterX = thisViewport.getViewBounds().getCenterX();
final double viewCenterY = thisViewport.getViewBounds().getCenterY();
final Point2D viewCenter = new Point2D.Double(viewCenterX, viewCenterY);
final Point2D modelCenter = thisViewport.getViewToModelTransform().transform(viewCenter, null);
final PixelPos imageCenter = new PixelPos();
getBaseImageLayer().getModelToImageTransform().transform(modelCenter, imageCenter);
final GeoPos geoCenter = new GeoPos();
thisGeoCoding.getGeoPos(imageCenter, geoCenter);
thatGeoCoding.getPixelPos(geoCenter, imageCenter);
if (imageCenter.isValid()) {
thatView.getBaseImageLayer().getImageToModelTransform().transform(imageCenter, modelCenter);
thatViewport.setZoomFactor(thisViewport.getZoomFactor(), modelCenter.getX(), modelCenter.getY());
return true;
}
}
return false;
}
protected void disposeImageDisplayComponent() {
layerCanvas.dispose();
}
// only called from VISAT
public void updateImage() {
getBaseImageLayer().regenerate();
}
// used by PropertyEditor
public void updateNoDataImage() {
// change configuration of layer ; not setting MultiLevelSource
final String expression = getRaster().getValidMaskExpression();
final ImageLayer noDataLayer = (ImageLayer) getNoDataLayer(false);
if (noDataLayer != null) {
if (expression != null) {
final Color color = noDataLayer.getConfiguration().getValue(
NoDataLayerType.PROPERTY_NAME_COLOR);
final MultiLevelSource multiLevelSource = ColoredMaskImageMultiLevelSource.create(getRaster().getProduct(),
color, expression, true,
getBaseImageLayer().getImageToModelTransform());
noDataLayer.setMultiLevelSource(multiLevelSource);
} else {
noDataLayer.setMultiLevelSource(MultiLevelSource.NULL);
}
}
}
public int getFirstImageLayerIndex() {
return sceneImage.getFirstImageLayerIndex();
}
/**
* A band that is used as an RGB channel for RGB image views.
* These bands shall not be added to {@link Product}s but they are always owned by the {@link Product}
* passed into the constructor.
*/
public static class RGBChannel extends VirtualBand {
/**
* Constructs a new RGB image view band.
*
* @param product the product which takes the ownership
* @param width the width of the image
* @param height the height of the image
* @param name the band's name
* @param expression the expression
* @param products the products used to evaluate the expression
*/
public RGBChannel(final Product product, final int width, final int height, final String name, final String expression, Product[] products) {
super(name,
ProductData.TYPE_FLOAT32,
width,
height,
expression);
if (products == null || products.length == 0) {
deriveRasterPropertiesFromExpression(expression, product);
} else {
deriveRasterPropertiesFromExpression(expression, products);
}
setOwner(product);
setModified(false);
}
/**
* Constructs a new RGB image view band.
*
* @param product the product which takes the ownership
* @param width the width of the image
* @param height the height of the image
* @param name the band's name
* @param expression the expression
*/
public RGBChannel(final Product product, final int width, final int height, final String name, final String expression) {
this(product, product.getSceneRasterWidth(), product.getSceneRasterHeight(), name, expression, null);
}
/**
* Constructs a new RGB image view band.
*
* @param product the product which takes the ownership
* @param name the band's name
* @param expression the expression
* @param products the products used to evaluate the expression
*/
public RGBChannel(final Product product, final String name, final String expression, Product[] products) {
this(product, product.getSceneRasterWidth(), product.getSceneRasterHeight(), name, expression, products);
}
/**
* Constructs a new RGB image view band.
*
* @param product the product which takes the ownership
* @param name the band's name
* @param expression the expression
*/
public RGBChannel(final Product product, final String name, final String expression) {
this(product, product.getSceneRasterWidth(), product.getSceneRasterHeight(), name, expression, null);
}
private void deriveRasterPropertiesFromExpression(String expression, Product... products) {
if (products != null) {
try {
String validMaskExpression = BandArithmetic.getValidMaskExpression(getExpression(), products, 0, null);
setValidPixelExpression(validMaskExpression);
final RasterDataNode[] refRasters = BandArithmetic.getRefRasters(expression, products);
if (refRasters.length > 0) {
setGeoCoding(refRasters[0].getGeoCoding());
setImageToModelTransform(refRasters[0].getImageToModelTransform());
setSceneToModelTransform(refRasters[0].getSceneToModelTransform());
setModelToSceneTransform(refRasters[0].getModelToSceneTransform());
}
} catch (ParseException e) {
// do not set geocoding then
}
}
}
}
private final class RasterChangeHandler implements ProductNodeListener {
@Override
public void nodeChanged(final ProductNodeEvent event) {
repaintView();
}
@Override
public void nodeDataChanged(final ProductNodeEvent event) {
repaintView();
}
@Override
public void nodeAdded(final ProductNodeEvent event) {
repaintView();
}
@Override
public void nodeRemoved(final ProductNodeEvent event) {
repaintView();
}
private void repaintView() {
repaint(100);
}
}
private Layer getNoDataLayer(boolean create) {
return getSceneImage().getNoDataLayer(create);
}
public Layer getVectorDataCollectionLayer(boolean create) {
return getSceneImage().getVectorDataCollectionLayer(create);
}
private Layer getMaskCollectionLayer(boolean create) {
return getSceneImage().getMaskCollectionLayer(create);
}
private GraticuleLayer getGraticuleLayer(boolean create) {
return getSceneImage().getGraticuleLayer(create);
}
private Layer getPinLayer(boolean create) {
return getSceneImage().getPinLayer(create);
}
private Layer getGcpLayer(boolean create) {
return getSceneImage().getGcpLayer(create);
}
private static boolean isModelYAxisDown(ImageLayer baseImageLayer) {
return baseImageLayer.getImageToModelTransform().getDeterminant() > 0.0;
}
private void registerLayerCanvasListeners() {
layerCanvasComponentHandler = new LayerCanvasComponentHandler();
layerCanvasMouseHandler = new LayerCanvasMouseHandler();
layerCanvas.addComponentListener(layerCanvasComponentHandler);
layerCanvas.addMouseListener(layerCanvasMouseHandler);
layerCanvas.addMouseMotionListener(layerCanvasMouseHandler);
layerCanvas.addMouseWheelListener(layerCanvasMouseHandler);
PopupMenuHandler popupMenuHandler = new PopupMenuHandler(this);
layerCanvas.addMouseListener(popupMenuHandler);
layerCanvas.addKeyListener(popupMenuHandler);
}
private void deregisterLayerCanvasListeners() {
getRaster().getProduct().removeProductNodeListener(rasterChangeHandler);
layerCanvas.removeComponentListener(layerCanvasComponentHandler);
layerCanvas.removeMouseListener(layerCanvasMouseHandler);
layerCanvas.removeMouseMotionListener(layerCanvasMouseHandler);
}
private boolean isPixelPosValid(int currentPixelX, int currentPixelY, int currentLevel) {
return currentPixelX >= 0 && currentPixelX < baseImageLayer.getImage(
currentLevel).getWidth() && currentPixelY >= 0
&& currentPixelY < baseImageLayer.getImage(currentLevel).getHeight();
}
private void firePixelPosChanged(MouseEvent e, int currentPixelX, int currentPixelY, int currentLevel) {
boolean pixelPosValid = isPixelPosValid(currentPixelX, currentPixelY, currentLevel);
for (PixelPositionListener listener : pixelPositionListeners) {
listener.pixelPosChanged(baseImageLayer, currentPixelX, currentPixelY, currentLevel, pixelPosValid, e);
}
}
private void firePixelPosNotAvailable() {
for (PixelPositionListener listener : pixelPositionListeners) {
listener.pixelPosNotAvailable();
}
}
private void setPixelPos(MouseEvent e, boolean showBorder) {
if (e.getID() == MouseEvent.MOUSE_EXITED) {
currentLevelPixelX = -1;
firePixelPosNotAvailable();
} else {
Point2D p = new Point2D.Double(e.getX() + 0.5, e.getY() + 0.5);
Viewport viewport = getLayerCanvas().getViewport();
AffineTransform v2mTransform = viewport.getViewToModelTransform();
final Point2D modelP = v2mTransform.transform(p, null);
AffineTransform m2iTransform = baseImageLayer.getModelToImageTransform();
Point2D imageP = m2iTransform.transform(modelP, null);
currentPixelX = (int) Math.floor(imageP.getX());
currentPixelY = (int) Math.floor(imageP.getY());
int currentLevel = baseImageLayer.getLevel(viewport);
AffineTransform m2iLevelTransform = baseImageLayer.getModelToImageTransform(currentLevel);
Point2D imageLevelP = m2iLevelTransform.transform(modelP, null);
int currentPixelX = (int) Math.floor(imageLevelP.getX());
int currentPixelY = (int) Math.floor(imageLevelP.getY());
if (currentPixelX != currentLevelPixelX || currentPixelY != currentLevelPixelY || currentLevel != this.currentLevel) {
if (isPixelBorderDisplayEnabled() && (showBorder || pixelBorderDrawn)) {
drawPixelBorder(currentPixelX, currentPixelY, currentLevel, showBorder);
}
currentLevelPixelX = currentPixelX;
currentLevelPixelY = currentPixelY;
this.currentLevel = currentLevel;
firePixelPosChanged(e, currentLevelPixelX, currentLevelPixelY, this.currentLevel);
}
}
}
private boolean isPixelBorderDisplayEnabled() {
return pixelBorderShown &&
getLayerCanvas().getViewport().getZoomFactor() >= pixelBorderViewScale;
}
private void drawPixelBorder(int currentPixelX, int currentPixelY, int currentLevel, boolean showBorder) {
final Graphics g = getGraphics();
g.setXORMode(Color.white);
if (pixelBorderDrawn) {
drawPixelBorder(g, currentLevelPixelX, currentLevelPixelY, this.currentLevel);
pixelBorderDrawn = false;
}
if (showBorder) {
drawPixelBorder(g, currentPixelX, currentPixelY, currentLevel);
pixelBorderDrawn = true;
}
g.setPaintMode();
g.dispose();
}
private void drawPixelBorder(final Graphics g, final int x, final int y, final int l) {
if (g instanceof Graphics2D) {
Graphics2D g2d = (Graphics2D) g;
AffineTransform i2m = getBaseImageLayer().getImageToModelTransform(l);
AffineTransform m2v = getLayerCanvas().getViewport().getModelToViewTransform();
Rectangle imageRect = new Rectangle(x, y, 1, 1);
Shape modelRect = i2m.createTransformedShape(imageRect);
Shape transformedShape = m2v.createTransformedShape(modelRect);
g2d.draw(transformedShape);
}
}
private final class LayerCanvasMouseHandler implements MouseInputListener, MouseWheelListener {
private boolean invertZooming;
public LayerCanvasMouseHandler() {
invertZooming = sceneImage.getConfiguration().getPropertyBool(PREFERENCE_KEY_INVERT_ZOOMING, false);
}
public void setInvertZooming(boolean invertZooming) {
this.invertZooming = invertZooming;
}
@Override
public void mouseClicked(MouseEvent e) {
updatePixelPos(e, false);
}
@Override
public void mouseEntered(MouseEvent e) {
updatePixelPos(e, false);
}
@Override
public void mousePressed(MouseEvent e) {
updatePixelPos(e, false);
}
@Override
public void mouseReleased(MouseEvent e) {
updatePixelPos(e, false);
}
@Override
public void mouseExited(MouseEvent e) {
updatePixelPos(e, false);
}
@Override
public void mouseDragged(MouseEvent e) {
updatePixelPos(e, true);
}
@Override
public void mouseMoved(MouseEvent e) {
updatePixelPos(e, true);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (e.isAltDown() || e.isAltGraphDown() || e.isControlDown() || e.isShiftDown()) {
return;
}
Viewport viewport = layerCanvas.getViewport();
int wheelRotation = e.getWheelRotation();
if (invertZooming) {
wheelRotation *= -1;
}
double oldZoomFactor = viewport.getZoomFactor();
double newZoomFactor = oldZoomFactor * Math.pow(1.1, wheelRotation);
viewport.setZoomFactor(newZoomFactor);
}
private void updatePixelPos(MouseEvent e, boolean showBorder) {
setPixelPos(e, showBorder);
}
}
private class LayerCanvasComponentHandler extends ComponentAdapter {
/**
* Invoked when the component has been made invisible.
*/
@Override
public void componentHidden(ComponentEvent e) {
firePixelPosNotAvailable();
}
}
static class NullFigureCollection implements FigureCollection {
static final FigureCollection INSTANCE = new NullFigureCollection();
private NullFigureCollection() {
}
@Override
public boolean isCollection() {
return false;
}
@Override
public boolean contains(Figure figure) {
return false;
}
@Override
public boolean isCloseTo(Point2D point, AffineTransform m2v) {
return false;
}
@Override
public Rectangle2D getBounds() {
return new Rectangle();
}
@Override
public Rank getRank() {
return Figure.Rank.NOT_SPECIFIED;
}
@Override
public void move(double dx, double dy) {
}
@Override
public void scale(Point2D point, double sx, double sy) {
}
@Override
public void rotate(Point2D point, double theta) {
}
@Override
public double[] getSegment(int index) {
return null;
}
@Override
public void setSegment(int index, double[] segment) {
}
@Override
public void addSegment(int index, double[] segment) {
}
@Override
public void removeSegment(int index) {
}
@Override
public boolean isSelectable() {
return false;
}
@Override
public boolean isSelected() {
return false;
}
@Override
public void setSelected(boolean selected) {
}
@Override
public void draw(Rendering rendering) {
}
@Override
public int getFigureCount() {
return 0;
}
@Override
public int getFigureIndex(Figure figure) {
return 0;
}
@Override
public Figure getFigure(int index) {
return null;
}
@Override
public Figure getFigure(Point2D point, AffineTransform m2v) {
return null;
}
@Override
public Figure[] getFigures() {
return new Figure[0];
}
@Override
public Figure[] getFigures(Shape shape) {
return new Figure[0];
}
@Override
public boolean addFigure(Figure figure) {
return false;
}
@Override
public boolean addFigure(int index, Figure figure) {
return false;
}
@Override
public Figure[] addFigures(Figure... figures) {
return new Figure[0];
}
@Override
public boolean removeFigure(Figure figure) {
return false;
}
@Override
public Figure[] removeFigures(Figure... figures) {
return new Figure[0];
}
@Override
public Figure[] removeAllFigures() {
return new Figure[0];
}
@Override
public int getMaxSelectionStage() {
return 0;
}
@Override
public Handle[] createHandles(int selectionStage) {
return new Handle[0];
}
@Override
public void addChangeListener(FigureChangeListener listener) {
}
@Override
public void removeChangeListener(FigureChangeListener listener) {
}
@Override
public FigureChangeListener[] getChangeListeners() {
return new FigureChangeListener[0];
}
@Override
public void dispose() {
}
@Override
public Object createMemento() {
return null;
}
@Override
public void setMemento(Object memento) {
}
@Override
public FigureStyle getNormalStyle() {
return null;
}
@Override
public void setNormalStyle(FigureStyle normalStyle) {
}
@Override
public FigureStyle getSelectedStyle() {
return null;
}
@Override
public void setSelectedStyle(FigureStyle selectedStyle) {
}
@Override
public FigureStyle getEffectiveStyle() {
return null;
}
@Override
public Object clone() {
return INSTANCE;
}
}
private static class VectorDataLayerFilter implements LayerFilter {
private final VectorDataNode vectorDataNode;
public VectorDataLayerFilter(VectorDataNode vectorDataNode) {
this.vectorDataNode = vectorDataNode;
}
@Override
public boolean accept(Layer layer) {
return layer instanceof VectorDataLayer && ((VectorDataLayer) layer).getVectorDataNode() == vectorDataNode;
}
}
private class PinSelectionChangeListener extends AbstractSelectionChangeListener {
private boolean firedNoPinSelected = false;
@Override
public void selectionChanged(SelectionChangeEvent event) {
Selection selection = event.getSelection();
if (selection.isEmpty()) {
if (!firedNoPinSelected) {
firePropertyChange(PROPERTY_NAME_SELECTED_PIN, null, null);
firedNoPinSelected = true;
}
} else {
Object selectedValue = selection.getSelectedValue();
if (selectedValue instanceof SimpleFeatureFigure) {
SimpleFeatureFigure featureFigure = (SimpleFeatureFigure) selectedValue;
PlacemarkGroup pinGroup = getProduct().getPinGroup();
Placemark pin = pinGroup.getPlacemark(featureFigure.getSimpleFeature());
if (pin != null) {
firePropertyChange(PROPERTY_NAME_SELECTED_PIN, null, pin);
firedNoPinSelected = false;
}
}
}
}
}
}
| 61,201 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BandChooser.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/BandChooser.java | package org.esa.snap.ui.product;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.ui.ModalDialog;
import javax.swing.AbstractButton;
import javax.swing.JCheckBox;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.HashSet;
import java.util.Set;
/**
* A dialog which lets the user select from a product's bands and tie-point grids.
*/
public class BandChooser extends ModalDialog implements LoadSaveRasterDataNodesConfigurationsComponent {
private final boolean selectAtLeastOneBand;
private BandChoosingStrategy strategy;
private boolean addLoadSaveConfigurationButtons;
public BandChooser(Window parent, String title, String helpID,
Band[] allBands, Band[] selectedBands, Product.AutoGrouping autoGrouping,
boolean addLoadSaveConfigurationButtons) {
super(parent, title, ModalDialog.ID_OK_CANCEL, helpID);
this.addLoadSaveConfigurationButtons = addLoadSaveConfigurationButtons;
boolean multipleProducts = bandsAndGridsFromMoreThanOneProduct(allBands, null);
strategy = new GroupedBandChoosingStrategy(allBands, selectedBands, null, null, autoGrouping, multipleProducts);
selectAtLeastOneBand = false;
initUI();
}
public BandChooser(Window parent, String title, String helpID,
Band[] allBands, Band[] selectedBands, boolean addLoadSaveConfigurationButtons) {
this(parent, title, helpID, true, allBands, selectedBands, null, null, addLoadSaveConfigurationButtons);
}
public BandChooser(Window parent, String title, String helpID, boolean selectAtLeastOneBand,
Band[] allBands, Band[] selectedBands,
TiePointGrid[] allTiePointGrids, TiePointGrid[] selectedTiePointGrids,
boolean addLoadSaveConfigurationButtons) {
super(parent, title, ModalDialog.ID_OK_CANCEL, helpID);
this.addLoadSaveConfigurationButtons = addLoadSaveConfigurationButtons;
boolean multipleProducts = bandsAndGridsFromMoreThanOneProduct(allBands, allTiePointGrids);
strategy = new DefaultBandChoosingStrategy(allBands, selectedBands, allTiePointGrids, selectedTiePointGrids,
multipleProducts);
this.selectAtLeastOneBand = selectAtLeastOneBand;
initUI();
}
private boolean bandsAndGridsFromMoreThanOneProduct(Band[] allBands, TiePointGrid[] allTiePointGrids) {
Set<Product> productSet = new HashSet<>();
if (allBands != null) {
for (Band allBand : allBands) {
productSet.add(allBand.getProduct());
}
}
if (allTiePointGrids != null) {
for (TiePointGrid allTiePointGrid : allTiePointGrids) {
productSet.add(allTiePointGrid.getProduct());
}
}
return productSet.size() > 1;
}
@Override
public int show() {
strategy.updateCheckBoxStates();
return super.show();
}
private void initUI() {
JPanel checkersPane = strategy.createCheckersPane();
JCheckBox selectAllCheckBox = new JCheckBox("Select all");
selectAllCheckBox.setMnemonic('a');
selectAllCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
strategy.selectAll();
}
});
JCheckBox selectNoneCheckBox = new JCheckBox("Select none");
selectNoneCheckBox.setMnemonic('n');
selectNoneCheckBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
strategy.selectNone();
}
});
strategy.setCheckBoxes(selectAllCheckBox, selectNoneCheckBox);
final JPanel checkPane = new JPanel(new BorderLayout());
checkPane.add(selectAllCheckBox, BorderLayout.WEST);
checkPane.add(selectNoneCheckBox, BorderLayout.CENTER);
TableLayout layout = new TableLayout(1);
layout.setTablePadding(4, 4);
JPanel buttonPanel = new JPanel(layout);
if (addLoadSaveConfigurationButtons) {
LoadSaveRasterDataNodesConfigurationsProvider provider = new LoadSaveRasterDataNodesConfigurationsProvider(this);
AbstractButton loadButton = provider.getLoadButton();
AbstractButton saveButton = provider.getSaveButton();
buttonPanel.add(loadButton);
buttonPanel.add(saveButton);
buttonPanel.add(layout.createVerticalSpacer());
}
final JPanel content = new JPanel(new BorderLayout());
JScrollPane scrollPane = new JScrollPane(checkersPane);
final Dimension preferredSize = checkersPane.getPreferredSize();
scrollPane.setPreferredSize(new Dimension(Math.min(preferredSize.width + 20, 400),
Math.min(preferredSize.height + 10, 300)));
scrollPane.getVerticalScrollBar().setUnitIncrement(20);
content.add(scrollPane, BorderLayout.CENTER);
content.add(buttonPanel, BorderLayout.EAST);
content.add(checkPane, BorderLayout.SOUTH);
content.setMinimumSize(new Dimension(0, 100));
setContent(content);
}
@Override
protected boolean verifyUserInput() {
if (!strategy.atLeastOneBandSelected() && selectAtLeastOneBand) {
showInformationDialog("No bands selected.\nPlease select at least one band.");
return false;
}
return true;
}
public Band[] getSelectedBands() {
return strategy.getSelectedBands();
}
public TiePointGrid[] getSelectedTiePointGrids() {
return strategy.getSelectedTiePointGrids();
}
@Override
public void setReadRasterDataNodeNames(String[] readRasterDataNodeNames) {
strategy.selectNone();
strategy.selectRasterDataNodes(readRasterDataNodeNames);
}
@Override
public String[] getRasterDataNodeNamesToWrite() {
Band[] selectedBands = strategy.getSelectedBands();
TiePointGrid[] selectedTiePointGrids = strategy.getSelectedTiePointGrids();
String[] nodeNames = new String[selectedBands.length + selectedTiePointGrids.length];
for (int i = 0; i < selectedBands.length; i++) {
nodeNames[i] = selectedBands[i].getName();
}
for (int i = 0; i < selectedTiePointGrids.length; i++) {
nodeNames[selectedBands.length + i] = selectedTiePointGrids[i].getName();
}
return nodeNames;
}
}
| 6,876 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/VectorDataLayer.java | /*
* Copyright (C) 2013 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.product;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.LayerTypeRegistry;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.FigureChangeEvent;
import com.bc.ceres.swing.figure.FigureChangeListener;
import com.bc.ceres.swing.figure.FigureCollection;
import com.bc.ceres.swing.figure.FigureStyle;
import com.bc.ceres.swing.figure.support.DefaultFigureCollection;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.esa.snap.core.datamodel.Placemark;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeListenerAdapter;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.Debug;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.awt.geom.Rectangle2D;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
* A layer for vector data nodes.
*
* @author Norman Fomferra
*/
public class VectorDataLayer extends Layer {
private static final VectorDataLayerType TYPE = LayerTypeRegistry.getLayerType(VectorDataLayerType.class);
private VectorDataNode vectorDataNode;
private final SimpleFeatureFigureFactory figureFactory;
private FigureCollection figureCollection;
private VectorDataChangeHandler vectorDataChangeHandler;
private boolean reactingAgainstFigureChange;
private static int id;
public VectorDataLayer(LayerContext ctx, VectorDataNode vectorDataNode, SceneTransformProvider provider) {
this(TYPE, vectorDataNode, provider, TYPE.createLayerConfig(ctx));
getConfiguration().setValue(VectorDataLayerType.PROPERTY_NAME_VECTOR_DATA, vectorDataNode.getName());
}
protected VectorDataLayer(VectorDataLayerType vectorDataLayerType, VectorDataNode vectorDataNode,
SceneTransformProvider provider, PropertySet configuration) {
super(vectorDataLayerType, configuration);
setUniqueId();
this.vectorDataNode = vectorDataNode;
setName(vectorDataNode.getName());
figureFactory = new SimpleFeatureFigureFactory(vectorDataNode.getFeatureType(), provider);
figureCollection = new DefaultFigureCollection();
updateFigureCollection();
vectorDataChangeHandler = new VectorDataChangeHandler();
vectorDataNode.getProduct().addProductNodeListener(vectorDataChangeHandler);
figureCollection.addChangeListener(new FigureChangeHandler());
}
private void setUniqueId() {
setId(VectorDataLayerType.VECTOR_DATA_LAYER_ID_PREFIX + (++id));
}
public VectorDataNode getVectorDataNode() {
return vectorDataNode;
}
@Override
protected void disposeLayer() {
Product product = vectorDataNode.getProduct();
if (product != null) {
product.removeProductNodeListener(vectorDataChangeHandler);
}
vectorDataNode = null;
super.disposeLayer();
}
private void updateFigureCollection() {
FeatureCollection<SimpleFeatureType, SimpleFeature> featureCollection = vectorDataNode.getFeatureCollection();
Figure[] figures = figureCollection.getFigures();
Map<SimpleFeature, SimpleFeatureFigure> figureMap = new HashMap<>();
for (Figure figure : figures) {
if (figure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure simpleFeatureFigure = (SimpleFeatureFigure) figure;
figureMap.put(simpleFeatureFigure.getSimpleFeature(), simpleFeatureFigure);
}
}
FeatureIterator<SimpleFeature> featureIterator = featureCollection.features();
while (featureIterator.hasNext()) {
SimpleFeature simpleFeature = featureIterator.next();
SimpleFeatureFigure featureFigure = figureMap.get(simpleFeature);
if (featureFigure != null) {
figureMap.remove(simpleFeature);
Placemark placemark = vectorDataNode.getPlacemarkGroup().getPlacemark(simpleFeature);
if(placemark != null) {
String css = placemark.getStyleCss();
final FigureStyle normalStyle = DefaultFigureStyle.createFromCss(css);
final FigureStyle selectedStyle = getFigureFactory().deriveSelectedStyle(normalStyle);
featureFigure.setNormalStyle(normalStyle);
featureFigure.setSelectedStyle(selectedStyle);
}
} else {
featureFigure = getFigureFactory().createSimpleFeatureFigure(simpleFeature, vectorDataNode.getDefaultStyleCss());
figureCollection.addFigure(featureFigure);
}
featureFigure.forceRegeneration();
}
Collection<SimpleFeatureFigure> remainingFigures = figureMap.values();
figureCollection.removeFigures(remainingFigures.toArray(new Figure[remainingFigures.size()]));
}
private void setLayerStyle(String styleCss) {
// todo - implement me (nf)
// this method is called if no figure is selected, but the layer editor is showing and users can modify style settings
Debug.trace("VectorDataLayer.setLayerStyle: styleCss = " + styleCss);
}
public SimpleFeatureFigureFactory getFigureFactory() {
return figureFactory;
}
public FigureCollection getFigureCollection() {
return figureCollection;
}
@Override
protected Rectangle2D getLayerModelBounds() {
if (figureCollection.getFigureCount() == 0) {
return null;
} else {
return figureCollection.getBounds();
}
}
@Override
protected void renderLayer(Rendering rendering) {
figureCollection.draw(rendering);
}
private class VectorDataChangeHandler extends ProductNodeListenerAdapter {
@Override
public void nodeChanged(ProductNodeEvent event) {
if (event.getSourceNode() == getVectorDataNode()) {
Debug.trace("VectorDataLayer$VectorDataChangeHandler.nodeChanged: event = " + event);
if (ProductNode.PROPERTY_NAME_NAME.equals(event.getPropertyName())) {
setName(getVectorDataNode().getName());
} else if (VectorDataNode.PROPERTY_NAME_STYLE_CSS.equals(event.getPropertyName())) {
if (event.getNewValue() != null) {
setLayerStyle(event.getNewValue().toString());
}
} else if (VectorDataNode.PROPERTY_NAME_FEATURE_COLLECTION.equals(event.getPropertyName())) {
if (!reactingAgainstFigureChange) {
updateFigureCollection();
// checkme - we could do better by computing changed modelRegion instead of passing null (nf)
fireLayerDataChanged(null);
}
}
} else if (event.getSourceNode() instanceof Placemark) {
final Placemark sourceNode = (Placemark) event.getSourceNode();
if (getVectorDataNode().getPlacemarkGroup().contains(sourceNode))
if (event.getPropertyName().equals(Placemark.PROPERTY_NAME_STYLE_CSS)) {
updateFigureCollection();
} else if (event.getPropertyName().equals("geometry")) {
updateFigureCollection();
} else if (event.getPropertyName().equals(Placemark.PROPERTY_NAME_GEOPOS)) {
updateFigureCollection();
} else if (event.getPropertyName().equals(Placemark.PROPERTY_NAME_PIXELPOS)) {
updateFigureCollection();
}
}
}
}
private class FigureChangeHandler implements FigureChangeListener {
@Override
public void figureChanged(FigureChangeEvent event) {
final Figure sourceFigure = event.getSourceFigure();
if (sourceFigure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure featureFigure = (SimpleFeatureFigure) sourceFigure;
try {
final VectorDataNode vectorDataNode = getVectorDataNode();
if (vectorDataNode != null ) {
final SimpleFeature simpleFeature = featureFigure.getSimpleFeature();
Debug.trace("VectorDataLayer$FigureChangeHandler: vectorDataNode=" + vectorDataNode.getName() +
", featureType=" + simpleFeature.getFeatureType().getTypeName());
reactingAgainstFigureChange = true;
vectorDataNode.fireFeaturesChanged(simpleFeature);
// checkme - we could do better by computing changed modelRegion instead of passing null (nf)
fireLayerDataChanged(null);
}
} finally {
reactingAgainstFigureChange = false;
}
}
}
}
}
| 10,233 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
InputListModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/InputListModel.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.ui.product;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.ValidationException;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.SystemUtils;
import javax.swing.AbstractListModel;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
/**
* @author Thomas Storm
*/
class InputListModel extends AbstractListModel<Object> {
private final List<Object> list = new ArrayList<>();
private List<Product> sourceProducts = new ArrayList<>();
private Property sourceProductPaths;
private boolean internalPropertyChange;
@Override
public Object getElementAt(int index) {
return list.get(index);
}
int getIndexOf(Object object) {
return list.indexOf(object);
}
@Override
public int getSize() {
return list.size();
}
Product[] getSourceProducts() {
return sourceProducts.toArray(new Product[sourceProducts.size()]);
}
void setPaths(String[] elements) throws ValidationException {
if (!list.isEmpty()) {
final int endIndex = list.size() - 1;
list.clear();
fireIntervalRemoved(this, 0, endIndex);
}
final File[] files = new File[elements.length];
for (int i = 0; i < files.length; i++) {
files[i] = new File(elements[i]);
}
addElements((Object[]) getSourceProducts());
addElements((Object[]) files);
}
void addElements(Object... elements) throws ValidationException {
if (elements == null || elements.length == 0) {
return;
}
final int startIndex = list.size();
for (Object element : elements) {
if (!(element instanceof File || element instanceof Product)) {
throw new IllegalStateException(
"Only java.io.File or Product allowed.");
}
if (mayAdd(element)) {
list.add(element);
}
}
updateProperty();
fireIntervalAdded(this, startIndex, list.size() - 1);
}
void clear() {
if (!list.isEmpty()) {
final int endIndex = list.size() - 1;
list.clear();
try {
updateProperty();
} catch (ValidationException ignored) {
}
fireIntervalRemoved(this, 0, endIndex);
}
}
void removeElementsAt(int[] selectedIndices) {
List<Object> toRemove = new ArrayList<>();
int startIndex = Integer.MAX_VALUE;
int endIndex = Integer.MIN_VALUE;
for (int selectedIndex : selectedIndices) {
startIndex = Math.min(startIndex, selectedIndex);
endIndex = Math.max(endIndex, selectedIndex);
toRemove.add(list.get(selectedIndex));
}
if (list.removeAll(toRemove)) {
try {
updateProperty();
} catch (ValidationException ignored) {
}
fireIntervalRemoved(this, startIndex, endIndex);
}
}
private void updateProperty() throws ValidationException {
final List<String> files = new ArrayList<>();
final List<Product> products = new ArrayList<>();
for (Object element : list) {
if (element instanceof File) {
files.add(((File) element).getPath());
} else if (element instanceof Product) {
products.add((Product) element);
}
}
internalPropertyChange = true;
sourceProductPaths.setValue(files.toArray(new String[files.size()]));
internalPropertyChange = false;
sourceProducts = products;
}
private boolean mayAdd(Object element) {
if (list.contains(element)) {
return false;
}
if (element instanceof Product) {
return true;
}
File file = (File) element;
return file.isDirectory() || !alreadyContained(file);
}
private boolean alreadyContained(File file) {
for (Product sourceProduct : sourceProducts) {
File fileLocation = sourceProduct.getFileLocation();
if (fileLocation != null && fileLocation.getAbsolutePath().equals(file.getAbsolutePath())) {
return true;
}
}
return false;
}
public void setProperty(Property property) {
this.sourceProductPaths = property;
if (sourceProductPaths != null && sourceProductPaths.getContainer() != null) {
sourceProductPaths.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (!internalPropertyChange) {
Object newValue = evt.getNewValue();
try {
if (newValue == null) {
final Object[] sourceProducts = getSourceProducts();
clear();
addElements(sourceProducts);
} else {
setPaths((String[]) newValue);
}
} catch (ValidationException e) {
SystemUtils.LOG.log(Level.SEVERE, "Problems at setPaths.", e);
}
}
}
});
}
}
public Property getProperty() {
return sourceProductPaths;
}
}
| 6,420 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductNodeView.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ProductNodeView.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.ui.product;
import org.esa.snap.core.datamodel.ProductNode;
import java.awt.Rectangle;
/**
* An interface which can be used to mark a visible component as a view displaying a product node. Applications can ask
* a component whether it implements this interface in order to find out which product node is currently displayed.
*/
public interface ProductNodeView {
/**
* @return The currently visible product node.
*/
ProductNode getVisibleProductNode();
/**
* Releases all of the resources used by this view and all of its owned children. Its primary use is to allow the
* garbage collector to perform a vanilla job.
* <p>This method should be called only if it is for sure that this object instance will never be used again. The
* results of referencing an instance of this class after a call to <code>dispose()</code> are undefined.
*/
void dispose();
/**
* Gets the bounds of this view in the form of a
* <code>Rectangle</code> object. The bounds specify this
* view's width, height, and location relative to
* its parent GUI widget.
*
* @return a rectangle indicating this view's bounds
*/
public Rectangle getBounds();
}
| 1,970 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataCollectionLayer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/VectorDataCollectionLayer.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.ui.product;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.core.Assert;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerFilter;
import com.bc.ceres.glayer.support.LayerUtils;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNode;
import org.esa.snap.core.datamodel.ProductNodeEvent;
import org.esa.snap.core.datamodel.ProductNodeGroup;
import org.esa.snap.core.datamodel.ProductNodeListener;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.layer.ProductLayerContext;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class VectorDataCollectionLayer extends CollectionLayer {
public static final String ID = VectorDataCollectionLayer.class.getName();
private final ProductNodeListener pnl;
private final transient WeakReference<ProductNodeGroup<VectorDataNode>> reference;
private final ProductLayerContext plc;
public VectorDataCollectionLayer(VectorDataCollectionLayerType layerType,
ProductNodeGroup<VectorDataNode> vectorDataGroup,
PropertySet configuration,
ProductLayerContext plc) {
super(layerType, configuration, "Vector data");
Assert.notNull(vectorDataGroup, "vectorDataGroup");
reference = new WeakReference<>(vectorDataGroup);
pnl = new PNL();
this.plc = plc;
setId(ID);
vectorDataGroup.getProduct().addProductNodeListener(pnl);
}
@Override
public void disposeLayer() {
ProductNodeGroup<VectorDataNode> productNodeGroup = reference.get();
if (productNodeGroup != null) {
Product product = productNodeGroup.getProduct();
if (product != null) {
product.removeProductNodeListener(pnl);
}
}
reference.clear();
}
private Layer createLayer(final VectorDataNode vectorDataNode) {
final Layer layer = VectorDataLayerType.createLayer(plc, vectorDataNode);
layer.setVisible(false);
return layer;
}
private Layer getLayer(final VectorDataNode vectorDataNode) {
LayerFilter layerFilter = VectorDataLayerFilterFactory.createNodeFilter(vectorDataNode);
return LayerUtils.getChildLayer(LayerUtils.getRootLayer(this), LayerUtils.SEARCH_DEEP, layerFilter);
}
synchronized void updateChildren() {
final ProductNodeGroup<VectorDataNode> vectorDataGroup = reference.get();
if (vectorDataGroup == null) {
return;
}
// Collect all current vector layers
LayerFilter layerFilter = layer -> {
PropertySet conf = layer.getConfiguration();
return conf.isPropertyDefined(VectorDataLayerType.PROPERTY_NAME_VECTOR_DATA) && conf.getValue(VectorDataLayerType.PROPERTY_NAME_VECTOR_DATA) != null;
};
List<Layer> vectorLayers = LayerUtils.getChildLayers(LayerUtils.getRootLayer(this), LayerUtils.SEARCH_DEEP, layerFilter);
final Map<VectorDataNode, Layer> currentLayers = new HashMap<>();
for (final Layer child : vectorLayers) {
final String name = child.getConfiguration().getValue(VectorDataLayerType.PROPERTY_NAME_VECTOR_DATA);
final VectorDataNode vectorDataNode = vectorDataGroup.get(name);
currentLayers.put(vectorDataNode, child);
}
// Align vector layers with available vectors
final Set<Layer> unusedLayers = new HashSet<>(vectorLayers);
VectorDataNode[] vectorDataNodes = vectorDataGroup.toArray(new VectorDataNode[vectorDataGroup.getNodeCount()]);
for (final VectorDataNode vectorDataNode : vectorDataNodes) {
Layer layer = currentLayers.get(vectorDataNode);
if (layer != null) {
unusedLayers.remove(layer);
} else {
layer = createLayer(vectorDataNode);
getChildren().add(layer);
}
}
// Remove unused layers
for (Layer layer : unusedLayers) {
layer.dispose();
Layer layerParent = layer.getParent();
if (layerParent != null) {
layerParent.getChildren().remove(layer);
}
}
}
private class PNL implements ProductNodeListener {
@Override
public synchronized void nodeChanged(ProductNodeEvent event) {
final ProductNode sourceNode = event.getSourceNode();
if (sourceNode instanceof VectorDataNode) {
final VectorDataNode vectorDataNode = (VectorDataNode) sourceNode;
final Layer layer = getLayer(vectorDataNode);
if (layer != null) {
layer.regenerate();
}
}
}
@Override
public void nodeDataChanged(ProductNodeEvent event) {
nodeChanged(event);
}
@Override
public void nodeAdded(ProductNodeEvent event) {
updateChildren();
}
@Override
public void nodeRemoved(ProductNodeEvent event) {
updateChildren();
}
}
}
| 6,094 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LoadSaveRasterDataNodesConfigurationsComponent.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/LoadSaveRasterDataNodesConfigurationsComponent.java | package org.esa.snap.ui.product;
import java.awt.Window;
public interface LoadSaveRasterDataNodesConfigurationsComponent {
void setReadRasterDataNodeNames(String[] readRasterDataNodeNames);
String[] getRasterDataNodeNamesToWrite();
Window getParent();
}
| 272 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataFigureEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/VectorDataFigureEditor.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.ui.product;
import com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.support.DefaultFigureEditor;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import com.bc.ceres.swing.figure.support.FigureDeleteEdit;
import com.bc.ceres.swing.figure.support.FigureInsertEdit;
import org.esa.snap.core.datamodel.VectorDataNode;
import org.esa.snap.core.util.Debug;
import org.opengis.feature.simple.SimpleFeature;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import java.util.Arrays;
import java.util.List;
/**
* A figure editor for vector data nodes.
*
* @author Norman Fomferra
*/
public class VectorDataFigureEditor extends DefaultFigureEditor {
private final ProductSceneView productSceneView;
private VectorDataNode vectorDataNode;
public VectorDataFigureEditor(ProductSceneView productSceneView) {
super(productSceneView.getLayerCanvas(),
productSceneView.getLayerCanvas().getViewport(),
productSceneView.getUndoContext(),
ProductSceneView.NullFigureCollection.INSTANCE,
null);
this.productSceneView = productSceneView;
}
public ProductSceneView getProductSceneView() {
return productSceneView;
}
public VectorDataNode getVectorDataNode() {
return vectorDataNode;
}
public void vectorDataLayerSelected(VectorDataLayer vectorDataLayer) {
Debug.trace("VectorDataFigureEditor.vectorDataLayerSelected: " + vectorDataLayer.getName());
this.vectorDataNode = vectorDataLayer.getVectorDataNode();
setFigureCollection(vectorDataLayer.getFigureCollection());
setFigureFactory(vectorDataLayer.getFigureFactory());
final DefaultFigureStyle style = new DefaultFigureStyle();
style.fromCssString(vectorDataLayer.getVectorDataNode().getDefaultStyleCss());
setDefaultLineStyle(style);
setDefaultPolygonStyle(style);
}
@Override
public void insertFigures(boolean performInsert, Figure... figures) {
Debug.trace("VectorDataFigureEditor.insertFigures " + performInsert + ", " + figures.length);
if (vectorDataNode != null) {
List<SimpleFeature> simpleFeatures = toSimpleFeatureList(figures);
vectorDataNode.getFeatureCollection().addAll(simpleFeatures);
getUndoContext().postEdit(new FigureInsertEdit(this, performInsert, figures) {
@Override
public void undo() throws CannotUndoException {
super.undo();
vectorDataNode.getFeatureCollection().removeAll(simpleFeatures);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
vectorDataNode.getFeatureCollection().addAll(simpleFeatures);
}
});
} else {
// warn
super.insertFigures(performInsert, figures);
}
}
@Override
public void deleteFigures(boolean performDelete, Figure... figures) {
Debug.trace("VectorDataFigureEditor.deleteFigures " + performDelete + ", " + figures.length);
if (vectorDataNode != null) {
List<SimpleFeature> simpleFeatures = toSimpleFeatureList(figures);
vectorDataNode.getFeatureCollection().removeAll(simpleFeatures);
getUndoContext().postEdit(new FigureDeleteEdit(this, performDelete, figures) {
@Override
public void undo() throws CannotUndoException {
super.undo();
vectorDataNode.getFeatureCollection().addAll(simpleFeatures);
}
@Override
public void redo() throws CannotRedoException {
super.redo();
vectorDataNode.getFeatureCollection().removeAll(simpleFeatures);
}
});
} else {
// warn
super.deleteFigures(performDelete, figures);
}
}
@Override
public void changeFigure(Figure figure, Object figureMemento, String presentationName) {
Debug.trace("VectorDataFigureEditor.changeFigure " + figure + ", " + presentationName);
super.changeFigure(figure, figureMemento, presentationName);
if (vectorDataNode != null) {
if (figure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure featureFigure = (SimpleFeatureFigure) figure;
vectorDataNode.fireFeaturesChanged(featureFigure.getSimpleFeature());
}
} else {
// warn
}
}
private List<SimpleFeature> toSimpleFeatureList(Figure[] figures) {
SimpleFeature[] features = new SimpleFeature[figures.length];
for (int i = 0, figuresLength = figures.length; i < figuresLength; i++) {
Figure figure = figures[i];
if (figure instanceof SimpleFeatureFigure) {
SimpleFeatureFigure simpleFeatureFigure = (SimpleFeatureFigure) figure;
features[i] = simpleFeatureFigure.getSimpleFeature();
}
}
return Arrays.asList(features);
}
}
| 5,982 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleFeatureShapeFigure.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/SimpleFeatureShapeFigure.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.ui.product;
import com.bc.ceres.swing.figure.AbstractShapeFigure;
import com.bc.ceres.swing.figure.FigureStyle;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.Lineal;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Polygon;
import org.locationtech.jts.geom.Polygonal;
import org.locationtech.jts.geom.Puntal;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.util.AwtGeomToJtsGeomConverter;
import org.esa.snap.core.util.Debug;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.geometry.jts.LiteShape2;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;
import java.awt.Shape;
/**
* A figure representing shape features.
*
* @author Norman Fomferra
*/
public class SimpleFeatureShapeFigure extends AbstractShapeFigure implements SimpleFeatureFigure {
private SimpleFeature simpleFeature;
private Shape shape;
private final Class<?> geometryType;
private SceneTransformProvider sceneTransformProvider;
private static final Shape EMPTY_SHAPE = new java.awt.Polygon(new int[0], new int[0], 0);
public SimpleFeatureShapeFigure(SimpleFeature simpleFeature, SceneTransformProvider provider, FigureStyle style) {
this(simpleFeature, provider, style, style);
}
public SimpleFeatureShapeFigure(SimpleFeature simpleFeature, SceneTransformProvider provider,
FigureStyle normalStyle, FigureStyle selectedStyle) {
super(getRank(simpleFeature), normalStyle, selectedStyle);
this.simpleFeature = simpleFeature;
this.geometryType = simpleFeature.getDefaultGeometry().getClass();
this.shape = null;
sceneTransformProvider = provider;
}
@Override
public Object createMemento() {
return getGeometry().clone();
}
@Override
public void setMemento(Object memento) {
simpleFeature.setDefaultGeometry(memento);
forceRegeneration();
fireFigureChanged();
}
@Override
public SimpleFeature getSimpleFeature() {
return simpleFeature;
}
@Override
public Geometry getGeometry() {
return (Geometry) simpleFeature.getDefaultGeometry();
}
@Override
public void setGeometry(Geometry geometry) {
if (!geometryType.isAssignableFrom(geometry.getClass())) {
Debug.trace("WARNING: Assigning a geometry of type " + geometry.getClass() + ", should actually be a " + geometryType);
}
simpleFeature.setDefaultGeometry(geometry);
forceRegeneration();
fireFigureChanged();
}
@Override
public Shape getShape() {
if (shape == null) {
final Geometry featureGeometry = (Geometry) simpleFeature.getDefaultGeometry();
try {
Geometry modelGeometry = sceneTransformProvider.getSceneToModelTransform().transform(featureGeometry);
shape = new LiteShape2(modelGeometry, null, null, true);
} catch (TransformException | FactoryException e) {
//return empty shape for drawing
return EMPTY_SHAPE;
}
}
return shape;
}
@Override
public void forceRegeneration() {
shape = null;
}
@Override
public void setShape(Shape shape) {
this.shape = shape;
Geometry modelGeometry = getGeometryFromShape(shape);
try {
final Geometry sceneGeometry = sceneTransformProvider.getModelToSceneTransform().transform(modelGeometry);
simpleFeature.setDefaultGeometry(sceneGeometry);
fireFigureChanged();
} catch (TransformException e) {
this.shape = null;
}
}
private Geometry getGeometryFromShape(Shape shape) {
AwtGeomToJtsGeomConverter converter = new AwtGeomToJtsGeomConverter();
Geometry geometry;
// May need to handle more cases here in the future! (nf)
if (Polygon.class.isAssignableFrom(geometryType)) {
geometry = converter.createPolygon(shape);
} else if (MultiPolygon.class.isAssignableFrom(geometryType)) {
geometry = converter.createMultiPolygon(shape);
} else if (LinearRing.class.isAssignableFrom(geometryType)) {
geometry = converter.createLinearRingList(shape).get(0);
} else if (LineString.class.isAssignableFrom(geometryType)) {
geometry = converter.createLineStringList(shape).get(0);
} else {
geometry = converter.createMultiLineString(shape);
}
return geometry;
}
@Override
public Object clone() {
SimpleFeatureShapeFigure clone = (SimpleFeatureShapeFigure) super.clone();
SimpleFeatureBuilder builder = new SimpleFeatureBuilder(simpleFeature.getFeatureType());
builder.init(simpleFeature);
clone.simpleFeature = builder.buildFeature(null);
clone.simpleFeature.setDefaultGeometry(getGeometry().clone());
clone.shape = getShape();
return clone;
}
static Rank getRank(SimpleFeature simpleFeature) {
final Object geometry = simpleFeature.getDefaultGeometry();
if (!(geometry instanceof Geometry)) {
throw new IllegalArgumentException("simpleFeature: geometry type must be a " + Geometry.class);
}
return getRank((Geometry) geometry);
}
static Rank getRank(Geometry geometry) {
if (geometry instanceof Puntal) {
return Rank.POINT;
} else if (geometry instanceof Lineal) {
return Rank.LINE;
} else if (geometry instanceof Polygonal) {
return Rank.AREA;
} else {
return Rank.NOT_SPECIFIED;
}
}
}
| 6,727 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExpressionEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ExpressionEditor.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.ui.product;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.swing.binding.Binding;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.ComponentAdapter;
import com.bc.ceres.swing.binding.PropertyEditor;
import com.bc.ceres.swing.binding.internal.TextComponentAdapter;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.converters.BooleanExpressionConverter;
import org.esa.snap.core.util.converters.GeneralExpressionConverter;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* A value editor for band arithmetic expressions
*
* @author Marco Zuehlke
* @since BEAM 4.6
*/
public abstract class ExpressionEditor extends PropertyEditor {
private Product currentProduct;
@Override
public JComponent createEditorComponent(PropertyDescriptor propertyDescriptor, BindingContext bindingContext) {
JTextField textField = new JTextField();
textField.setPreferredSize(new Dimension(100, textField.getPreferredSize().height));
ComponentAdapter adapter = new TextComponentAdapter(textField);
final Binding binding = bindingContext.bind(propertyDescriptor.getName(), adapter);
final JPanel subPanel = new JPanel(new BorderLayout(2, 2));
subPanel.add(textField, BorderLayout.CENTER);
final JButton etcButton = new JButton("...");
etcButton.setEnabled(false);
etcButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProductExpressionPane expressionPane = getProductExpressionPane(currentProduct);
expressionPane.setCode((String) binding.getPropertyValue());
if (expressionPane.showModalDialog(null, "Expression Editor") == ModalDialog.ID_OK) {
binding.setPropertyValue(expressionPane.getCode());
}
}
});
Property property = Property.create(UIUtils.PROPERTY_SOURCE_PRODUCT, Product.class, null, false);
property.getDescriptor().setTransient(true);
bindingContext.getPropertySet().addProperty(property);
bindingContext.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equals(UIUtils.PROPERTY_SOURCE_PRODUCT)) {
currentProduct = (Product) evt.getNewValue();
etcButton.setEnabled(currentProduct != null);
}
}
});
subPanel.add(etcButton, BorderLayout.EAST);
return subPanel;
}
abstract ProductExpressionPane getProductExpressionPane(Product currentProduct);
public static class GeneralExpressionEditor extends ExpressionEditor {
@Override
public boolean isValidFor(PropertyDescriptor propertyDescriptor) {
return propertyDescriptor.getConverter() instanceof GeneralExpressionConverter;
}
@Override
ProductExpressionPane getProductExpressionPane(Product currentProduct) {
return ProductExpressionPane.createGeneralExpressionPane(
new Product[]{currentProduct}, currentProduct, null);
}
}
public static class BooleanExpressionEditor extends ExpressionEditor {
@Override
public boolean isValidFor(PropertyDescriptor propertyDescriptor) {
return propertyDescriptor.getConverter() instanceof BooleanExpressionConverter;
}
@Override
ProductExpressionPane getProductExpressionPane(Product currentProduct) {
return ProductExpressionPane.createBooleanExpressionPane(
new Product[]{currentProduct}, currentProduct, null);
}
}
}
| 4,936 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BandSorter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/BandSorter.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.ui.product;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.ProductNode;
import java.util.Arrays;
import java.util.Comparator;
/**
* @author Thomas Storm
*/
class BandSorter {
static Comparator<Band> createComparator() {
return Comparator.comparing(ProductNode::getName);
}
static void sort(Band[] allBands) {
Arrays.parallelSort(allBands, createComparator());
}
}
| 1,177 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LoadSaveRasterDataNodesConfigurationsProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/LoadSaveRasterDataNodesConfigurationsProvider.java | package org.esa.snap.ui.product;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.tool.ToolButtonFactory;
import org.openide.util.ImageUtilities;
import javax.swing.AbstractButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class LoadSaveRasterDataNodesConfigurationsProvider {
private final LoadSaveRasterDataNodesConfigurationsComponent component;
private AbstractButton loadButton;
private AbstractButton saveButton;
public LoadSaveRasterDataNodesConfigurationsProvider(LoadSaveRasterDataNodesConfigurationsComponent component) {
this.component = component;
}
public AbstractButton getLoadButton() {
if (loadButton == null) {
loadButton = createButton("tango/22x22/actions/document-open.png");
loadButton.setToolTipText("Load configuration");
loadButton.addActionListener(new LoadConfigurationActionListener());
}
return loadButton;
}
public AbstractButton getSaveButton() {
if (saveButton == null) {
saveButton = createButton("tango/22x22/actions/document-save-as.png");
saveButton.setToolTipText("Save configuration");
saveButton.addActionListener(new SaveConfigurationActionListener());
}
return saveButton;
}
private static AbstractButton createButton(String s) {
return ToolButtonFactory.createButton(ImageUtilities.loadImageIcon(s, false), false);
}
@SuppressWarnings("ResultOfMethodCallIgnored")
private static File getBandSetsDataDir() {
File file = new File(SystemUtils.getAuxDataPath().toFile(), "band_sets");
if (!file.exists()) {
file.mkdirs();
}
return file;
}
private class LoadConfigurationActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
File currentDirectory = getBandSetsDataDir();
JFileChooser fileChooser = new JFileChooser(currentDirectory);
if (fileChooser.showOpenDialog(component.getParent()) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
List<String> bandNameList = new ArrayList<>();
String readBandName;
while ((readBandName = reader.readLine()) != null) {
bandNameList.add(readBandName);
}
reader.close();
String[] bandNames = bandNameList.toArray(new String[bandNameList.size()]);
component.setReadRasterDataNodeNames(bandNames);
} catch (IOException e1) {
AbstractDialog.showInformationDialog(component.getParent(), "Could not load configuration", "Information");
}
}
}
}
private class SaveConfigurationActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
File currentDirectory = getBandSetsDataDir();
JFileChooser fileChooser = new JFileChooser(currentDirectory);
File suggestedFile = new File(currentDirectory + File.separator + "config.txt");
int fileCounter = 1;
while (suggestedFile.exists()) {
suggestedFile = new File("config" + fileCounter + ".txt");
}
fileChooser.setSelectedFile(suggestedFile);
if (fileChooser.showSaveDialog(component.getParent()) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
String[] bandNames = component.getRasterDataNodeNamesToWrite();
for (String bandName : bandNames) {
writer.write(bandName + "\n");
}
writer.close();
} catch (IOException e1) {
JOptionPane.showMessageDialog(component.getParent(), "Could not save configuration");
}
}
}
}
}
| 4,646 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductChooser.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/ProductChooser.java | /*
* Copyright (C) 2010 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui.product;
import com.bc.ceres.swing.TableLayout;
import com.jidesoft.swing.CheckBoxList;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.ModalDialog;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
/**
* @author Thomas Storm
*/
class ProductChooser extends ModalDialog {
private final CheckBoxList productsList;
private final JCheckBox selectAll;
private final JCheckBox selectNone;
ProductChooser(Window parent, String title, int buttonMask, String helpID, Product[] products) {
super(parent, title, buttonMask, helpID);
TableLayout layout = new TableLayout(1);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setRowWeightY(0, 1.0);
layout.setRowWeightY(1, 0.0);
layout.setTableWeightX(1.0);
JPanel panel = new JPanel(layout);
ProductListModel listModel = new ProductListModel();
selectAll = new JCheckBox("Select all");
selectNone = new JCheckBox("Select none", true);
selectNone.setEnabled(false);
productsList = new CheckBoxList(listModel);
productsList.setCellRenderer(new ProductListCellRenderer());
productsList.getCheckBoxListSelectionModel().addListSelectionListener(new ListSelectionListener() {
@Override
public void valueChanged(ListSelectionEvent e) {
final int length = productsList.getCheckBoxListSelectedIndices().length;
if (length == 0) {
selectNone.setSelected(true);
selectAll.setSelected(false);
} else if (length == productsList.getModel().getSize()) {
selectAll.setSelected(true);
selectNone.setSelected(false);
} else {
selectAll.setSelected(false);
selectNone.setSelected(false);
}
selectAll.setEnabled(!selectAll.isSelected());
selectNone.setEnabled(!selectNone.isSelected());
}
});
for (Product product : products) {
listModel.addElement(product);
}
panel.add(new JScrollPane(productsList));
panel.add(createButtonsPanel());
setContent(panel);
}
List<Product> getSelectedProducts() {
List<Product> selectedProducts = new ArrayList<>();
for (int i = 0; i < productsList.getModel().getSize(); i++) {
if (productsList.getCheckBoxListSelectionModel().isSelectedIndex(i)) {
selectedProducts.add((Product) productsList.getModel().getElementAt(i));
}
}
return selectedProducts;
}
private JPanel createButtonsPanel() {
JPanel buttonsPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
selectAll.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectNone.setSelected(false);
selectAll.setEnabled(false);
selectNone.setEnabled(true);
productsList.getCheckBoxListSelectionModel().setSelectionInterval(0,
productsList.getModel().getSize() - 1);
}
});
selectNone.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
selectAll.setSelected(false);
selectAll.setEnabled(true);
selectNone.setEnabled(false);
productsList.getCheckBoxListSelectionModel().clearSelection();
}
});
selectAll.setMnemonic('a');
selectNone.setMnemonic('n');
buttonsPanel.add(selectAll);
buttonsPanel.add(selectNone);
return buttonsPanel;
}
private static class ProductListCellRenderer implements ListCellRenderer<Product> {
private DefaultListCellRenderer delegate = new DefaultListCellRenderer();
@Override
public Component getListCellRendererComponent(JList list, Product value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) delegate.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setText(value.getDisplayName());
return label;
}
}
private static class ProductListModel extends DefaultListModel<Product> {
@Override
public void addElement(Product product) {
boolean alreadyContained = false;
for (int i = 0; i < getSize(); i++) {
String currentProductName = get(i).getName();
String newProductName = product.getName();
alreadyContained |= currentProductName.equals(newProductName);
}
if (!alreadyContained) {
super.addElement(product);
}
}
}
}
| 6,289 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumSelectionAdmin.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/spectrum/SpectrumSelectionAdmin.java | package org.esa.snap.ui.product.spectrum;
import com.jidesoft.swing.TristateCheckBox;
import java.util.ArrayList;
import java.util.List;
class SpectrumSelectionAdmin {
private List<List<Boolean>> bandSelectionStates;
private List<Integer> numbersOfSelectedBands;
private List<Integer> currentStates;
SpectrumSelectionAdmin() {
bandSelectionStates = new ArrayList<List<Boolean>>();
numbersOfSelectedBands = new ArrayList<Integer>();
currentStates = new ArrayList<Integer>();
}
void evaluateSpectrumSelections(DisplayableSpectrum spectrum) {
List<Boolean> selected = new ArrayList<Boolean>();
int numberOfSelectedBands = 0;
for (int i = 0; i < spectrum.getSpectralBands().length; i++) {
final boolean bandSelected = spectrum.isBandSelected(i);
selected.add(bandSelected);
if (bandSelected) {
numberOfSelectedBands++;
}
}
bandSelectionStates.add(selected);
numbersOfSelectedBands.add(numberOfSelectedBands);
currentStates.add(-1);
evaluateState(bandSelectionStates.size() - 1);
}
boolean isBandSelected(int row, int i) {
if (currentStates.get(row) == TristateCheckBox.STATE_MIXED) {
return bandSelectionStates.get(row).get(i);
} else return currentStates.get(row) == TristateCheckBox.STATE_SELECTED;
}
private void evaluateState(int index) {
final Integer numberOfBands = numbersOfSelectedBands.get(index);
if (numberOfBands == 0) {
currentStates.set(index, TristateCheckBox.STATE_UNSELECTED);
} else if (numberOfBands == bandSelectionStates.get(index).size()) {
currentStates.set(index, TristateCheckBox.STATE_SELECTED);
} else {
currentStates.set(index, TristateCheckBox.STATE_MIXED);
}
}
int getState(int index) {
return currentStates.get(index);
}
boolean isSpectrumSelected(int row) {
return currentStates.get(row) != TristateCheckBox.STATE_UNSELECTED;
}
void setBandSelected(int row, int bandRow, boolean selected) {
if (isBandSelected(row, bandRow) != selected) {
updateBandSelections(row, bandRow, selected);
updateNumberOfSelectedBands(selected, row);
evaluateState(row);
}
}
private void updateBandSelections(int row, int bandRow, boolean selected) {
bandSelectionStates.get(row).set(bandRow, selected);
if (currentStates.get(row) != TristateCheckBox.STATE_MIXED) {
for (int i = 0; i < bandSelectionStates.get(row).size(); i++) {
if (i != bandRow) {
bandSelectionStates.get(row).set(i, !selected);
}
}
}
}
void updateSpectrumSelectionState(int row, int newState) {
if (newState == TristateCheckBox.STATE_MIXED) {
if (numbersOfSelectedBands.get(row) == bandSelectionStates.get(row).size() ||
numbersOfSelectedBands.get(row) == 0) {
newState = TristateCheckBox.STATE_UNSELECTED;
}
}
currentStates.set(row, newState);
}
private void updateNumberOfSelectedBands(Boolean selected, int row) {
if (currentStates.get(row) == TristateCheckBox.STATE_MIXED) {
if (selected) {
numbersOfSelectedBands.set(row, numbersOfSelectedBands.get(row) + 1);
} else {
numbersOfSelectedBands.set(row, numbersOfSelectedBands.get(row) - 1);
}
} else {
if (selected) {
numbersOfSelectedBands.set(row, 1);
} else {
numbersOfSelectedBands.set(row, bandSelectionStates.get(row).size() - 1);
}
}
}
}
| 3,850 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumStrokeProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/spectrum/SpectrumStrokeProvider.java | package org.esa.snap.ui.product.spectrum;
import org.esa.snap.core.util.ArrayUtils;
import javax.swing.ImageIcon;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import java.awt.image.BufferedImage;
public class SpectrumStrokeProvider {
private static final Stroke[] strokes = new Stroke[]{
new BasicStroke(),
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{10.0f}, 0.0f),
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{1.0f}, 0.0f),
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{10.0f, 1.0f}, 0.0f),
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{20.0f, 5.0f}, 0.0f),
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{1.0f, 5.0f}, 0.0f),
new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, new float[]{10.0f, 10.0f, 1.0f, 10.0f}, 0.0f)
};
private static final ImageIcon[] strokeIcons = convertStrokesToIcons();
public static final Stroke EMPTY_STROKE = new EmptyStroke();
private static ImageIcon[] convertStrokesToIcons() {
ImageIcon[] icons = new ImageIcon[strokes.length];
for (int i = 0; i < strokes.length; i++) {
icons[i] = convertStrokeToIcon(strokes[i]);
}
return icons;
}
private static ImageIcon convertStrokeToIcon(Stroke stroke) {
Shape strokeShape = new Line2D.Double(-40, 0, 40, 0);
final Rectangle rectangle = strokeShape.getBounds();
BufferedImage image = new BufferedImage((int) (rectangle.getWidth() - rectangle.getX()),
1,
BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = image.createGraphics();
graphics.translate(-rectangle.x, -rectangle.y);
graphics.setColor(Color.BLACK);
graphics.setStroke(stroke);
graphics.draw(strokeShape);
graphics.dispose();
return new ImageIcon(image);
}
public static Stroke getStroke(int i) {
return strokes[i % strokes.length];
}
public static ImageIcon getStrokeIcon(Stroke lineStyle) {
if(lineStyle == EMPTY_STROKE) {
return new ImageIcon();
}
return strokeIcons[ArrayUtils.getElementIndex(lineStyle, strokes)];
}
public static ImageIcon[] getStrokeIcons() {
return strokeIcons;
}
public static Stroke getStroke(ImageIcon strokeIcon) {
return strokes[ArrayUtils.getElementIndex(strokeIcon, strokeIcons)];
}
private static class EmptyStroke implements Stroke {
@Override
public Shape createStrokedShape(Shape p) {
return new GeneralPath();
}
}
}
| 3,081 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Spectrum.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/spectrum/Spectrum.java | package org.esa.snap.ui.product.spectrum;
import org.esa.snap.core.datamodel.Band;
public interface Spectrum {
String getName();
Band[] getSpectralBands();
boolean hasBands();
}
| 196 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DisplayableSpectrum.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/spectrum/DisplayableSpectrum.java | package org.esa.snap.ui.product.spectrum;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.Band;
import java.awt.Shape;
import java.awt.Stroke;
import java.util.ArrayList;
import java.util.List;
public class DisplayableSpectrum implements Spectrum {
public final static String NO_UNIT = "";
public final static String MIXED_UNITS = "mixed units";
public final static String DEFAULT_SPECTRUM_NAME = "Bands";
public final static String REMAINING_BANDS_NAME = "Other";
private List<SpectrumBand> bands;
private String name;
private Stroke lineStyle;
private int symbolIndex;
private int symbolSize;
private boolean isSelected;
private String unit;
public DisplayableSpectrum(String spectrumName, int symbolIndex) {
this(spectrumName, new SpectrumBand[]{}, symbolIndex);
}
public DisplayableSpectrum(String spectrumName, SpectrumBand[] spectralBands, int symbolIndex) {
this.name = spectrumName;
bands = new ArrayList<SpectrumBand>(spectralBands.length);
this.symbolIndex = symbolIndex;
symbolSize = SpectrumShapeProvider.DEFAULT_SCALE_GRADE;
unit = NO_UNIT;
for (SpectrumBand spectralBand : spectralBands) {
addBand(spectralBand);
}
setSelected(true);
}
public void addBand(SpectrumBand band) {
Assert.notNull(band);
bands.add(band);
if(band.isSelected()) {
setSelected(true);
}
updateUnit();
}
public Shape getScaledShape() {
return SpectrumShapeProvider.getScaledShape(getSymbolIndex(), getSymbolSize());
}
public boolean isDefaultOrRemainingBandsSpectrum() {
return isRemainingBandsSpectrum() || name.equals(DEFAULT_SPECTRUM_NAME);
}
public boolean isRemainingBandsSpectrum() {
return name.equals(REMAINING_BANDS_NAME);
}
public boolean hasBands() {
return !bands.isEmpty();
}
public boolean hasSelectedBands() {
for (SpectrumBand band : bands) {
if (band.isSelected()) {
return true;
}
}
return false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Band[] getSpectralBands() {
Band[] spectralBands = new Band[bands.size()];
for (int i = 0; i < bands.size(); i++) {
spectralBands[i] = bands.get(i).getOriginalBand();
}
return spectralBands;
}
public Band[] getSelectedBands() {
List<Band> selectedBands = new ArrayList<Band>();
for (SpectrumBand band : bands) {
if (band.isSelected()) {
selectedBands.add(band.getOriginalBand());
}
}
return selectedBands.toArray(new Band[selectedBands.size()]);
}
public void setBandSelected(int index, boolean selected) {
bands.get(index).setSelected(selected);
}
public boolean isBandSelected(int index) {
return bands.get(index).isSelected();
}
public Stroke getLineStyle() {
if (isRemainingBandsSpectrum()) {
return SpectrumStrokeProvider.EMPTY_STROKE;
}
return lineStyle;
}
public void setLineStyle(Stroke lineStyle) {
this.lineStyle = lineStyle;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
public boolean isSelected() {
return isSelected;
}
public String getUnit() {
return unit;
}
public int getSymbolSize() {
return symbolSize;
}
public void setSymbolSize(int symbolSize) {
this.symbolSize = symbolSize;
}
public int getSymbolIndex() {
return symbolIndex;
}
public void setSymbolIndex(int symbolIndex) {
this.symbolIndex = symbolIndex;
}
public void updateUnit() {
if (bands.size() > 0) {
unit = getUnit(bands.get(0));
}
if (bands.size() > 1) {
for (int i = 1; i < bands.size(); i++) {
if (!unit.equals(getUnit(bands.get(i)))) {
unit = MIXED_UNITS;
return;
}
}
}
}
private String getUnit(SpectrumBand band) {
String bandUnit = band.getUnit();
if(bandUnit == null) {
bandUnit = "";
}
return bandUnit;
}
public void remove(int j) {
bands.remove(j);
}
}
| 4,553 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumBand.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/spectrum/SpectrumBand.java | package org.esa.snap.ui.product.spectrum;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.Band;
/**
* @author Tonio Fincke
*/
public class SpectrumBand {
private final Band band;
private boolean isSelected;
public SpectrumBand(Band band, boolean isSelected) {
Assert.notNull(band);
this.band = band;
this.isSelected = isSelected;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
String getUnit() {
return band.getUnit();
}
public Band getOriginalBand() {
return band;
}
public String getName() {
return band.getName();
}
}
| 748 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumChooser.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/spectrum/SpectrumChooser.java | package org.esa.snap.ui.product.spectrum;
import com.bc.ceres.swing.TableLayout;
import com.jidesoft.swing.TristateCheckBox;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.util.ArrayUtils;
import org.esa.snap.ui.DecimalTableCellRenderer;
import org.esa.snap.ui.ModalDialog;
import org.esa.snap.ui.UIUtils;
import org.esa.snap.ui.product.LoadSaveRasterDataNodesConfigurationsComponent;
import org.esa.snap.ui.product.LoadSaveRasterDataNodesConfigurationsProvider;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.ImageIcon;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class SpectrumChooser extends ModalDialog implements LoadSaveRasterDataNodesConfigurationsComponent {
private static final int band_selected_index = 0;
private static final int band_name_index = 1;
private static final int band_description_index = 2;
private static final int band_wavelength_index = 3;
private static final int band_bandwidth_ndex = 4;
private static final int band_unit_index = 5;
private final String[] band_columns =
new String[]{"", "Band name", "Band description", "Spectral wavelength (nm)", "Spectral bandwidth (nm)", "Unit"};
private final static ImageIcon[] icons = new ImageIcon[]{
UIUtils.loadImageIcon("icons/PanelDown12.png"),
UIUtils.loadImageIcon("icons/PanelUp12.png"),
};
private final static ImageIcon[] roll_over_icons = new ImageIcon[]{
ToolButtonFactory.createRolloverIcon(icons[0]),
ToolButtonFactory.createRolloverIcon(icons[1]),
};
private final DisplayableSpectrum[] originalSpectra;
private DisplayableSpectrum[] spectra;
private static SpectrumSelectionAdmin selectionAdmin;
private static boolean selectionChangeLock;
private JPanel spectraPanel;
private final JPanel[] bandTablePanels;
private final JTable[] bandTables;
private final TristateCheckBox[] tristateCheckBoxes;
private boolean[] collapsed;
private TableLayout spectraPanelLayout;
public SpectrumChooser(Window parent, DisplayableSpectrum[] originalSpectra) {
super(parent, "Available Spectra", ModalDialog.ID_OK_CANCEL_HELP, "spectrumChooser");
if (originalSpectra != null) {
this.originalSpectra = originalSpectra;
List<DisplayableSpectrum> spectraWithBands = new ArrayList<>();
for (DisplayableSpectrum spectrum : originalSpectra) {
if (spectrum.hasBands()) {
spectraWithBands.add(spectrum);
}
}
this.spectra = spectraWithBands.toArray(new DisplayableSpectrum[spectraWithBands.size()]);
} else {
this.originalSpectra = new DisplayableSpectrum[0];
this.spectra = new DisplayableSpectrum[0];
}
selectionAdmin = new SpectrumSelectionAdmin();
selectionChangeLock = false;
bandTables = new JTable[spectra.length];
collapsed = new boolean[spectra.length];
Arrays.fill(collapsed, true);
bandTablePanels = new JPanel[spectra.length];
tristateCheckBoxes = new TristateCheckBox[spectra.length];
initUI();
}
private void initUI() {
final JPanel content = new JPanel(new BorderLayout());
initSpectraPanel();
final JScrollPane spectraScrollPane = new JScrollPane(spectraPanel);
spectraScrollPane.getHorizontalScrollBar().setUnitIncrement(20);
spectraScrollPane.getVerticalScrollBar().setUnitIncrement(20);
spectraScrollPane.setPreferredSize(new Dimension(spectraScrollPane.getPreferredSize().width, 180));
content.add(spectraScrollPane, BorderLayout.CENTER);
LoadSaveRasterDataNodesConfigurationsProvider provider = new LoadSaveRasterDataNodesConfigurationsProvider(this);
AbstractButton loadButton = provider.getLoadButton();
AbstractButton saveButton = provider.getSaveButton();
TableLayout layout = new TableLayout(1);
layout.setTablePadding(4, 4);
JPanel buttonPanel = new JPanel(layout);
buttonPanel.add(loadButton);
buttonPanel.add(saveButton);
buttonPanel.add(layout.createVerticalSpacer());
content.add(buttonPanel, BorderLayout.EAST);
setContent(content);
}
private void initSpectraPanel() {
spectraPanelLayout = new TableLayout(7);
spectraPanelLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
spectraPanelLayout.setTableWeightY(0.0);
spectraPanelLayout.setTableWeightX(1.0);
spectraPanelLayout.setColumnWeightX(0, 0.0);
spectraPanelLayout.setColumnWeightX(1, 0.0);
spectraPanelLayout.setTablePadding(3, 3);
spectraPanel = new JPanel(spectraPanelLayout);
spectraPanel.add(new JLabel(""));
spectraPanel.add(new JLabel(""));
spectraPanel.add(new JLabel("Spectrum Name"));
spectraPanel.add(new JLabel("Unit"));
spectraPanel.add(new JLabel("Line Style"));
spectraPanel.add(new JLabel("Symbol"));
spectraPanel.add(new JLabel("Symbol Size"));
for (int i = 0; i < spectra.length; i++) {
selectionAdmin.evaluateSpectrumSelections(spectra[i]);
addSpectrumComponentsToSpectraPanel(i);
spectraPanelLayout.setCellColspan((i * 2) + 2, 1, 6);
spectraPanel.add(new JLabel());
bandTablePanels[i] = new JPanel(new BorderLayout());
bandTablePanels[i].setBorder(BorderFactory.createLineBorder(Color.BLACK, 1));
spectraPanel.add(bandTablePanels[i]);
bandTables[i] = createBandsTable(i);
}
spectraPanel.add(spectraPanelLayout.createVerticalSpacer());
spectraPanel.updateUI();
}
private void addSpectrumComponentsToSpectraPanel(int index) {
DisplayableSpectrum spectrum = spectra[index];
ImageIcon strokeIcon;
if (spectrum.isDefaultOrRemainingBandsSpectrum()) {
strokeIcon = new ImageIcon();
} else {
strokeIcon = SpectrumStrokeProvider.getStrokeIcon(spectrum.getLineStyle());
}
AbstractButton collapseButton = ToolButtonFactory.createButton(icons[0], false);
collapseButton.addActionListener(new CollapseListener(index));
final ImageIcon shapeIcon = SpectrumShapeProvider.getShapeIcon(spectrum.getSymbolIndex());
spectraPanel.add(collapseButton);
final TristateCheckBox tristateCheckBox = new TristateCheckBox();
tristateCheckBox.setState(selectionAdmin.getState(index));
tristateCheckBox.addActionListener(new TristateCheckboxListener(index));
tristateCheckBoxes[index] = tristateCheckBox;
spectraPanel.add(tristateCheckBox);
final JLabel spectrumNameLabel = new JLabel(spectrum.getName());
Font font = spectrumNameLabel.getFont();
font = new Font(font.getName(), Font.BOLD, font.getSize());
spectrumNameLabel.setFont(font);
spectraPanel.add(spectrumNameLabel);
spectraPanel.add(new JLabel(spectrum.getUnit()));
JComboBox<ImageIcon> strokeComboBox;
if (spectrum.isDefaultOrRemainingBandsSpectrum()) {
strokeComboBox = new JComboBox<>(new ImageIcon[]{strokeIcon});
strokeComboBox.setEnabled(false);
} else {
strokeComboBox = new JComboBox<>(SpectrumStrokeProvider.getStrokeIcons());
strokeComboBox.addActionListener(
e -> spectrum.setLineStyle(
SpectrumStrokeProvider.getStroke((ImageIcon) strokeComboBox.getSelectedItem())));
}
strokeComboBox.setPreferredSize(new Dimension(100, 20));
strokeComboBox.setSelectedItem(strokeIcon);
spectraPanel.add(strokeComboBox);
JComboBox<ImageIcon> shapeComboBox = new JComboBox<>(SpectrumShapeProvider.getShapeIcons());
JComboBox<Integer> shapeSizeComboBox = new JComboBox<>(SpectrumShapeProvider.getScaleGrades());
shapeComboBox.setPreferredSize(new Dimension(100, 20));
shapeSizeComboBox.setPreferredSize(new Dimension(100, 20));
shapeComboBox.setSelectedItem(shapeIcon);
shapeComboBox.addActionListener(e -> {
final int shapeIndex = SpectrumShapeProvider.getShape((ImageIcon) shapeComboBox.getSelectedItem());
spectrum.setSymbolIndex(shapeIndex);
if (shapeIndex == SpectrumShapeProvider.EMPTY_SHAPE_INDEX) {
shapeSizeComboBox.setSelectedItem("");
} else {
shapeSizeComboBox.setSelectedItem(spectrum.getSymbolSize());
}
});
spectraPanel.add(shapeComboBox);
shapeSizeComboBox.setSelectedItem(spectrum.getSymbolSize());
shapeSizeComboBox.addActionListener(e -> {
final String selectedItem = shapeSizeComboBox.getSelectedItem().toString();
if (!selectedItem.equals("")) {
spectrum.setSymbolSize(Integer.parseInt(selectedItem));
}
});
spectraPanel.add(shapeSizeComboBox);
}
private void toggleCollapsed(int index) {
final boolean isCollapsed = !collapsed[index];
collapsed[index] = isCollapsed;
int rowIndex = (index * 2) + 2;
if (isCollapsed) {
spectraPanelLayout.setRowFill(rowIndex, TableLayout.Fill.HORIZONTAL);
spectraPanelLayout.setRowWeightY(rowIndex, 0.0);
bandTablePanels[index].removeAll();
} else {
spectraPanelLayout.setRowFill(rowIndex, TableLayout.Fill.BOTH);
spectraPanelLayout.setRowWeightY(rowIndex, 1.0);
bandTablePanels[index].add(bandTables[index].getTableHeader(), BorderLayout.NORTH);
bandTablePanels[index].add(bandTables[index], BorderLayout.CENTER);
}
bandTablePanels[index].updateUI();
spectraPanel.updateUI();
}
private JTable createBandsTable(int index) {
DisplayableSpectrum spectrum = spectra[index];
final Band[] spectralBands = spectrum.getSpectralBands();
Object[][] spectrumData = new Object[spectralBands.length][band_columns.length];
for (int i = 0; i < spectralBands.length; i++) {
Band spectralBand = spectralBands[i];
final boolean selected = spectrum.isBandSelected(i) && spectrum.isSelected();
spectrumData[i][band_selected_index] = selected;
spectrumData[i][band_name_index] = spectralBand.getName();
spectrumData[i][band_description_index] = spectralBand.getDescription();
spectrumData[i][band_wavelength_index] = spectralBand.getSpectralWavelength();
spectrumData[i][band_bandwidth_ndex] = spectralBand.getSpectralBandwidth();
spectrumData[i][band_unit_index] = spectralBand.getUnit();
}
final BandTableModel bandTableModel = new BandTableModel(spectrumData, band_columns);
bandTableModel.addTableModelListener(e -> {
e.getSource();
if (e.getColumn() == band_selected_index) {
final DisplayableSpectrum spectrum1 = spectra[index];
final int bandRow = e.getFirstRow();
final Boolean selected = (Boolean) bandTableModel.getValueAt(bandRow, e.getColumn());
spectrum1.setBandSelected(bandRow, selected);
if (!selectionChangeLock) {
selectionChangeLock = true;
selectionAdmin.setBandSelected(index, bandRow, selected);
selectionAdmin.updateSpectrumSelectionState(index, selectionAdmin.getState(index));
tristateCheckBoxes[index].setState(selectionAdmin.getState(index));
spectrum1.setSelected(selectionAdmin.isSpectrumSelected(index));
selectionChangeLock = false;
}
}
});
JTable bandsTable = new JTable(bandTableModel);
bandsTable.setRowSorter(new TableRowSorter<>(bandTableModel));
final TableColumn selectionColumn = bandsTable.getColumnModel().getColumn(band_selected_index);
final JCheckBox selectionCheckBox = new JCheckBox();
selectionColumn.setCellEditor(new DefaultCellEditor(selectionCheckBox));
selectionColumn.setMinWidth(20);
selectionColumn.setMaxWidth(20);
BooleanRenderer booleanRenderer = new BooleanRenderer();
selectionColumn.setCellRenderer(booleanRenderer);
final TableColumn wavelengthColumn = bandsTable.getColumnModel().getColumn(band_wavelength_index);
wavelengthColumn.setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("###0.0##")));
final TableColumn bandwidthColumn = bandsTable.getColumnModel().getColumn(band_bandwidth_ndex);
bandwidthColumn.setCellRenderer(new DecimalTableCellRenderer(new DecimalFormat("###0.0##")));
return bandsTable;
}
private void updateBandsTable(int index) {
final TableModel tableModel = bandTables[index].getModel();
for (int i = 0; i < tableModel.getRowCount(); i++) {
tableModel.setValueAt(selectionAdmin.isBandSelected(index, i), i, band_selected_index);
}
}
public DisplayableSpectrum[] getSpectra() {
return originalSpectra;
}
@Override
public void setReadRasterDataNodeNames(String[] readRasterDataNodeNames) {
for (JTable bandTable : bandTables) {
BandTableModel bandTableModel = (BandTableModel) bandTable.getModel();
for (int j = 0; j < bandTableModel.getRowCount(); j++) {
String bandName = bandTableModel.getValueAt(j, band_name_index).toString();
boolean selected = ArrayUtils.isMemberOf(bandName, readRasterDataNodeNames);
bandTableModel.setValueAt(selected, j, band_selected_index);
}
}
}
@Override
public String[] getRasterDataNodeNamesToWrite() {
List<String> bandNames = new ArrayList<>();
for (JTable bandTable : bandTables) {
BandTableModel bandTableModel = (BandTableModel) bandTable.getModel();
for (int j = 0; j < bandTableModel.getRowCount(); j++) {
if ((boolean) bandTableModel.getValueAt(j, band_selected_index)) {
bandNames.add(bandTableModel.getValueAt(j, band_name_index).toString());
}
}
}
return bandNames.toArray(new String[bandNames.size()]);
}
private static class BandTableModel extends DefaultTableModel {
private BandTableModel(Object[][] spectrumData, String[] bandColumns) {
super(spectrumData, bandColumns);
}
@Override
public boolean isCellEditable(int row, int column) {
return column == band_selected_index;
}
}
private class BooleanRenderer extends JCheckBox implements TableCellRenderer {
private BooleanRenderer() {
this.setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
} else {
setBackground(table.getBackground());
setForeground(table.getForeground());
}
boolean selected = (Boolean) value;
setSelected(selected);
return this;
}
}
private class CollapseListener implements ActionListener {
private final int index;
CollapseListener(int index) {
this.index = index;
}
@Override
public void actionPerformed(ActionEvent e) {
final Object source = e.getSource();
if (source instanceof AbstractButton) {
AbstractButton collapseButton = (AbstractButton) source;
toggleCollapsed(index);
if (collapsed[index]) {
collapseButton.setIcon(icons[0]);
collapseButton.setRolloverIcon(roll_over_icons[0]);
} else {
collapseButton.setIcon(icons[1]);
collapseButton.setRolloverIcon(roll_over_icons[1]);
}
}
}
}
private class TristateCheckboxListener implements ActionListener {
private final int index;
TristateCheckboxListener(int index) {
this.index = index;
}
@Override
public void actionPerformed(ActionEvent e) {
if (!selectionChangeLock) {
selectionChangeLock = true;
selectionAdmin.updateSpectrumSelectionState(index, tristateCheckBoxes[index].getState());
tristateCheckBoxes[index].setState(selectionAdmin.getState(index));
updateBandsTable(index);
spectra[index].setSelected(selectionAdmin.isSpectrumSelected(index));
selectionChangeLock = false;
}
}
}
}
| 17,966 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumShapeProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/spectrum/SpectrumShapeProvider.java | package org.esa.snap.ui.product.spectrum;
import org.esa.snap.core.util.ArrayUtils;
import javax.swing.ImageIcon;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Polygon;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Path2D;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
public class SpectrumShapeProvider {
private static final int starXPoints[] = {0, 1, 6, 2, 3, 0, -3, -2, -6, -1};
private static final int starYPoints[] = {-6, -2, -2, 0, 5, 2, 5, 0, -2, -2};
private static final int xXPoints[] = {-5, -4, 0, 4, 5, 1, 5, 4, 0, -4, -5, -1};
private static final int xYPoints[] = {-4, -5, -1, -5, -4, 0, 4, 5, 1, 5, 4, 0};
private static final int crossXPoints[] = {-5, -1, -1, 1, 1, 5, 5, 1, 1, -1, -1, -5};
private static final int crossYPoints[] = {-1, -1, -5, -5, -1, -1, 1, 1, 5, 5, 1, 1};
private static final Shape[] shapes = new Shape[]{
/*0*/ new Polygon(),
/*1*/ new Polygon(new int[]{-4, 0, 4, 0}, new int[]{0, -4, 0, 4}, 4),
/*2*/ new Polygon(new int[]{-4, 0, 4}, new int[]{4, -4, 4}, 3),
/*3*/ new Polygon(new int[]{-4, 0, 4}, new int[]{-4, 4, -4}, 3),
/*4*/ new Polygon(starXPoints, starYPoints, starXPoints.length),
/*5*/ new Polygon(xXPoints, xYPoints, xXPoints.length),
/*6*/ new Polygon(crossXPoints, crossYPoints, crossXPoints.length),
/*7*/ new Ellipse2D.Double(-3, -3, 6, 6),
/*8*/ new Rectangle2D.Double(-3.0, -3.0, 6.0, 6.0),
/*9*/ new Rectangle2D.Double(-2.0, -5.0, 4.0, 10.0),
/*10*/ new Rectangle2D.Double(-5.0, -2.0, 10.0, 4.0)
};
private static final ImageIcon[] shapeIcons = convertShapesToIcons();
public static final int DEFAULT_SCALE_GRADE = 3;
public static final int EMPTY_SHAPE_INDEX = 0;
private static final Integer[] scale_grades = new Integer[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
private static final double[] scaleFactors = new double[]{0.6, 0.8, 1, 1.5, 2, 2.5, 3, 3.5, 4};
private static ImageIcon[] convertShapesToIcons() {
ImageIcon[] icons = new ImageIcon[shapes.length];
for (int i = 0; i < shapes.length; i++) {
icons[i] = convertShapeToIcon(shapes[i]);
}
return icons;
}
private static ImageIcon convertShapeToIcon(Shape seriesShape) {
Rectangle rectangle = seriesShape.getBounds();
if (rectangle.getWidth() > 0 && rectangle.getHeight() > 0) {
BufferedImage image = new BufferedImage((int) (rectangle.getWidth() - rectangle.getX()),
(int) (rectangle.getHeight() - rectangle.getY()), BufferedImage.TYPE_INT_ARGB);
final Graphics2D graphics = image.createGraphics();
graphics.translate(-rectangle.x, -rectangle.y);
graphics.setColor(Color.BLACK);
graphics.draw(seriesShape);
graphics.dispose();
return new ImageIcon(image);
}
return new ImageIcon();
}
public static Shape getScaledShape(int shapeIndex, int scaleGrade) {
if (scaleGrade == DEFAULT_SCALE_GRADE) {
return shapes[shapeIndex];
} else {
final Path2D.Double convertedShape = new Path2D.Double(shapes[shapeIndex]);
final AffineTransform affineTransform = new AffineTransform();
affineTransform.scale(scaleFactors[scaleGrade - 1], scaleFactors[scaleGrade - 1]);
return convertedShape.createTransformedShape(affineTransform);
}
}
public static int getValidIndex(int i, boolean allowEmptySymbol) {
if(allowEmptySymbol) {
return i % shapes.length;
} else {
return i % (shapes.length - 1) + 1;
}
}
public static ImageIcon getShapeIcon(int symbolIndex) {
return shapeIcons[symbolIndex];
}
public static ImageIcon[] getShapeIcons() {
return shapeIcons;
}
public static Integer[] getScaleGrades() {
return scale_grades;
}
public static int getShape(ImageIcon shapeIcon) {
return ArrayUtils.getElementIndex(shapeIcon, shapeIcons);
}
}
| 4,290 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataElementChildFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/metadata/MetadataElementChildFactory.java | package org.esa.snap.ui.product.metadata;
import org.openide.nodes.ChildFactory;
import org.openide.nodes.Node;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Tonio Fincke
*/
class MetadataElementChildFactory extends ChildFactory.Detachable<MetadataTableElement> {
private List<MetadataTableElement> metadataTableElementList;
public MetadataElementChildFactory(MetadataTableElement[] metadataElements) {
metadataTableElementList = new ArrayList<>();
Collections.addAll(metadataTableElementList, metadataElements);
}
@Override
protected boolean createKeys(List<MetadataTableElement> toPopulate) {
if (metadataTableElementList.size() == 0) {
return true;
}
return toPopulate.addAll(metadataTableElementList);
}
@Override
protected Node createNodeForKey(MetadataTableElement metadataElement) {
return metadataElement.createNode();
}
}
| 986 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataElementLeafNode.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/metadata/MetadataElementLeafNode.java | package org.esa.snap.ui.product.metadata;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.util.StringUtils;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.PropertySupport;
import org.openide.nodes.Sheet;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
/**
* @author Tonio Fincke
*/
class MetadataElementLeafNode extends AbstractNode {
private final MetadataTableLeaf leaf;
MetadataElementLeafNode(MetadataTableLeaf leaf) {
this(leaf, new InstanceContent());
}
private MetadataElementLeafNode(MetadataTableLeaf leaf, InstanceContent content) {
super(Children.LEAF, new AbstractLookup(content));
this.leaf = leaf;
content.add(leaf);
setName(leaf.getName());
createSheet();
}
@Override
protected final Sheet createSheet() {
Sheet sheet = Sheet.createDefault();
Sheet.Set set = Sheet.createPropertiesSet();
PropertySupport[] properties = createAttributeProperties();
for (PropertySupport attributeProperty : properties) {
set.put(attributeProperty);
}
sheet.put(set);
return sheet;
}
private PropertySupport[] createAttributeProperties() {
List<PropertySupport> attributePropertyList = new ArrayList<>();
final int numElems = leaf.getData().getNumElems();
if (numElems > 0) {
addDataTypeSpecificProperty(leaf, attributePropertyList);
} else {
attributePropertyList.add(new EmptyProperty("Value"));
}
PropertySupport.ReadOnly<String> typeProperty =
new PropertySupport.ReadOnly<String>("Type", String.class, "Type", null) {
@Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return ProductData.getTypeString(leaf.getDataType());
}
};
attributePropertyList.add(typeProperty);
String unit = leaf.getUnit();
if (StringUtils.isNotNullAndNotEmpty(unit)) {
PropertySupport.ReadOnly<String> unitProperty =
new PropertySupport.ReadOnly<String>("Unit", String.class, "Unit", null) {
@Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return leaf.getUnit();
}
};
attributePropertyList.add(unitProperty);
}
String description = leaf.getDescription();
if (StringUtils.isNotNullAndNotEmpty(description)) {
PropertySupport.ReadOnly<String> descriptionProperty =
new PropertySupport.ReadOnly<String>("Description", String.class, "Description", null) {
@Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return leaf.getDescription();
}
};
attributePropertyList.add(descriptionProperty);
}
return attributePropertyList.toArray(new PropertySupport[attributePropertyList.size()]);
}
void addDataTypeSpecificProperty(MetadataTableLeaf leaf, List<PropertySupport> attributePropertyList) {
final int dataType = leaf.getDataType();
switch (dataType) {
case ProductData.TYPE_INT32:
attributePropertyList.add(new IntegerProperty("Value"));
break;
case ProductData.TYPE_UINT32:
if (leaf.getData() instanceof ProductData.UTC) {
attributePropertyList.add(new StringProperty("Value"));
break;
}
attributePropertyList.add(new UIntegerProperty("Value"));
break;
case ProductData.TYPE_FLOAT64:
attributePropertyList.add(new DoubleProperty("Value"));
break;
default:
attributePropertyList.add(new StringProperty("Value"));
}
}
public class IntegerProperty extends PropertySupport.ReadOnly<Integer> {
public IntegerProperty(String name) {
super(name, Integer.class, name, null);
}
@Override
public Integer getValue() throws IllegalAccessException, InvocationTargetException {
return leaf.getData().getElemInt();
}
}
public class UIntegerProperty extends PropertySupport.ReadOnly<Long> {
public UIntegerProperty(String name) {
super(name, Long.class, name, null);
}
@Override
public Long getValue() throws IllegalAccessException, InvocationTargetException {
return leaf.getData().getElemUInt();
}
}
public class DoubleProperty extends PropertySupport.ReadOnly<Double> {
public DoubleProperty(String name) {
super(name, Double.class, name, null);
}
@Override
public Double getValue() throws IllegalAccessException, InvocationTargetException {
return leaf.getData().getElemDouble();
}
}
public class StringProperty extends PropertySupport.ReadOnly<String> {
public StringProperty(String name) {
super(name, String.class, name, null);
}
@Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return leaf.getData().getElemString();
}
}
public static class EmptyProperty extends PropertySupport.ReadOnly<String> {
public EmptyProperty(String name) {
super(name, String.class, name, null);
}
@Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return "<empty>";
}
}
}
| 6,147 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataTableLeaf.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/metadata/MetadataTableLeaf.java | package org.esa.snap.ui.product.metadata;
import org.esa.snap.core.datamodel.MetadataAttribute;
import org.esa.snap.core.datamodel.ProductData;
import org.openide.nodes.AbstractNode;
/**
* @author Tonio Fincke
*/
class MetadataTableLeaf implements MetadataTableElement {
private String name;
private int dataType;
private ProductData data;
private String unit;
private String description;
public MetadataTableLeaf(MetadataAttribute attribute) {
this(attribute.getName(), attribute.getDataType(), attribute.getData(),
attribute.getUnit(), attribute.getDescription());
}
public MetadataTableLeaf(String name, int dataType, ProductData data, String unit, String description) {
this.name = name;
this.dataType = dataType;
this.data = data;
this.unit = unit;
this.description = description;
}
@Override
public MetadataTableElement[] getMetadataTableElements() {
return new MetadataTableElement[0];
}
@Override
public String getName() {
return name;
}
public int getDataType() {
return dataType;
}
public ProductData getData() {
return data;
}
public String getUnit() {
return unit;
}
public String getDescription() {
return description;
}
@Override
public AbstractNode createNode() {
return new MetadataElementLeafNode(this);
}
}
| 1,459 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataTableArrayElemLeaf.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/metadata/MetadataTableArrayElemLeaf.java | package org.esa.snap.ui.product.metadata;
import org.esa.snap.core.datamodel.ProductData;
import org.openide.nodes.AbstractNode;
import static org.esa.snap.core.datamodel.ProductData.TYPE_FLOAT32;
import static org.esa.snap.core.datamodel.ProductData.TYPE_FLOAT64;
import static org.esa.snap.core.datamodel.ProductData.TYPE_INT16;
import static org.esa.snap.core.datamodel.ProductData.TYPE_INT32;
import static org.esa.snap.core.datamodel.ProductData.TYPE_INT64;
import static org.esa.snap.core.datamodel.ProductData.TYPE_INT8;
import static org.esa.snap.core.datamodel.ProductData.TYPE_UINT16;
import static org.esa.snap.core.datamodel.ProductData.TYPE_UINT32;
import static org.esa.snap.core.datamodel.ProductData.TYPE_UINT8;
/**
* @author Tonio Fincke
*/
class MetadataTableArrayElemLeaf extends MetadataTableLeaf {
private ProductData data;
private final int elemIndex;
public MetadataTableArrayElemLeaf(String name, String unit, String description, ProductData data, int elemIndex) {
super(name, data.getType(), data, unit, description);
this.data = data;
this.elemIndex = elemIndex;
}
@Override
public MetadataTableElement[] getMetadataTableElements() {
return new MetadataTableElement[0];
}
public ProductData getData() {
Object dataElemArray = getDataElemArray(data, elemIndex);
return ProductData.createInstance(data.getType(), dataElemArray);
}
@Override
public AbstractNode createNode() {
return new MetadataElementLeafNode(this);
}
private static Object getDataElemArray(ProductData data, int index) {
switch (data.getType()) {
case TYPE_INT8:
return new byte[]{(byte)data.getElemIntAt(index)};
case TYPE_INT16:
return new short[]{(short)data.getElemIntAt(index)};
case TYPE_INT32:
return new int[]{data.getElemIntAt(index)};
case TYPE_UINT8:
return new byte[]{(byte)data.getElemUIntAt(index)};
case TYPE_UINT16:
return new short[]{(short)data.getElemUIntAt(index)};
case TYPE_UINT32:
return new int[]{(int)data.getElemUIntAt(index)};
case TYPE_INT64:
return new long[]{data.getElemLongAt(index)};
case TYPE_FLOAT32:
return new float[]{data.getElemFloatAt(index)};
case TYPE_FLOAT64:
return new double[]{data.getElemDoubleAt(index)};
default:
return null;
}
}
}
| 2,595 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataTableElement.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/metadata/MetadataTableElement.java | package org.esa.snap.ui.product.metadata;
import org.openide.nodes.AbstractNode;
/**
* @author Tonio Fincke
*/
interface MetadataTableElement {
MetadataTableElement[] getMetadataTableElements();
String getName();
AbstractNode createNode();
}
| 261 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataElementInnerNode.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/metadata/MetadataElementInnerNode.java | package org.esa.snap.ui.product.metadata;
import org.openide.nodes.AbstractNode;
import org.openide.nodes.Children;
import org.openide.nodes.Sheet;
import org.openide.util.lookup.AbstractLookup;
import org.openide.util.lookup.InstanceContent;
/**
* @author Tonio Fincke
*/
class MetadataElementInnerNode extends AbstractNode {
public MetadataElementInnerNode(MetadataTableInnerElement element) {
this(element, new InstanceContent());
}
private MetadataElementInnerNode(MetadataTableInnerElement element, InstanceContent content) {
super(Children.create(new MetadataElementChildFactory(element.getMetadataTableElements()), false),
new AbstractLookup(content));
content.add(element);
setName(element.getName());
createSheet();
}
@Override
protected final Sheet createSheet() {
Sheet sheet = Sheet.createDefault();
Sheet.Set set = Sheet.createPropertiesSet();
sheet.put(set);
return sheet;
}
}
| 1,015 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataTableInnerElement.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/product/metadata/MetadataTableInnerElement.java | package org.esa.snap.ui.product.metadata;
import org.esa.snap.core.datamodel.MetadataAttribute;
import org.esa.snap.core.datamodel.MetadataElement;
import org.esa.snap.core.datamodel.ProductData;
import org.openide.nodes.AbstractNode;
import java.util.ArrayList;
import java.util.List;
/**
* @author Tonio Fincke
*/
public class MetadataTableInnerElement implements MetadataTableElement {
private final MetadataElement metadataElement;
private final MetadataTableElement[] metadataTableElements;
public MetadataTableInnerElement(MetadataElement metadataElement) {
this.metadataElement = metadataElement;
metadataTableElements = getChildrenElementsFromElement(metadataElement);
}
@Override
public MetadataTableElement[] getMetadataTableElements() {
return metadataTableElements;
}
@Override
public String getName() {
return metadataElement.getName();
}
@Override
public AbstractNode createNode() {
return new MetadataElementInnerNode(this);
}
private static MetadataTableElement[] getChildrenElementsFromElement(MetadataElement metadataElement) {
MetadataElement[] elements = metadataElement.getElements();
MetadataAttribute[] attributes = metadataElement.getAttributes();
List<MetadataTableElement> metadataTableElementList = new ArrayList<>();
for (MetadataElement element : elements) {
metadataTableElementList.add(new MetadataTableInnerElement(element));
}
for (MetadataAttribute attribute : attributes) {
final long dataElemSize = attribute.getNumDataElems();
if (dataElemSize > 1) {
final int dataType = attribute.getDataType();
ProductData data = attribute.getData();
if ((ProductData.isFloatingPointType(dataType) || ProductData.isIntType(dataType)) && !(data instanceof ProductData.UTC)) {
addMetadataAttributes(attribute, data, metadataTableElementList);
} else {
metadataTableElementList.add(new MetadataTableLeaf(attribute));
}
} else {
metadataTableElementList.add(new MetadataTableLeaf(attribute));
}
}
return metadataTableElementList.toArray(new MetadataTableElement[metadataTableElementList.size()]);
}
private static void addMetadataAttributes(MetadataAttribute attribute, ProductData data,
List<MetadataTableElement> metadataTableElementList) {
final String name = attribute.getName();
final String unit = attribute.getUnit();
final String description = attribute.getDescription();
for (int j = 0; j < data.getNumElems(); j++) {
String elemName = String.format("%s.%d", name, j + 1);
metadataTableElementList.add(new MetadataTableArrayElemLeaf(elemName, unit, description, data, j));
}
}
}
| 2,998 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
KeyStrokeConverter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/xstream/converters/KeyStrokeConverter.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.ui.xstream.converters;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import javax.swing.KeyStroke;
/**
* An {@link com.thoughtworks.xstream.XStream XStream} converter for {@link KeyStroke}s.
*/
public class KeyStrokeConverter implements Converter {
public boolean canConvert(Class aClass) {
return KeyStroke.class.equals(aClass);
}
public void marshal(Object object, HierarchicalStreamWriter hierarchicalStreamWriter, MarshallingContext marshallingContext) {
if (object != null) {
hierarchicalStreamWriter.setValue(object.toString());
}
}
public Object unmarshal(HierarchicalStreamReader hierarchicalStreamReader, UnmarshallingContext unmarshallingContext) {
String text = hierarchicalStreamReader.getValue();
if (text != null) {
return KeyStroke.getKeyStroke(text);
}
return null;
}
}
| 1,900 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OutputGeometryFormModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/OutputGeometryFormModel.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.ui.crs;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValueSet;
import org.esa.snap.core.datamodel.ImageGeometry;
import org.esa.snap.core.datamodel.Product;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import java.awt.Rectangle;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* @author Marco Zuehlke
* @since BEAM 4.7
*/
public class OutputGeometryFormModel {
public static final int REFERENCE_PIXEL_UPPER_LEFT = 0;
public static final int REFERENCE_PIXEL_SCENE_CENTER = 1;
public static final int REFERENCE_PIXEL_USER = 2;
private static final int REFERENCE_PIXEL_DEFAULT = REFERENCE_PIXEL_SCENE_CENTER;
private static final boolean FIT_PRODUCT_SIZE_DEFAULT = true;
private transient Product sourceProduct;
private transient CoordinateReferenceSystem targetCrs;
private transient PropertySet propertyContainer;
private int referencePixelLocation;
private boolean fitProductSize;
public OutputGeometryFormModel(PropertySet sourcePropertySet) {
init(null, null, sourcePropertySet);
}
public OutputGeometryFormModel(Product sourceProduct, Product collocationProduct) {
this(sourceProduct, ImageGeometry.createCollocationTargetGeometry(sourceProduct, collocationProduct));
}
public OutputGeometryFormModel(Product sourceProduct, CoordinateReferenceSystem targetCrs) {
this(sourceProduct, ImageGeometry.createTargetGeometry(sourceProduct, targetCrs,
null, null, null, null,
null, null, null, null, null));
}
public OutputGeometryFormModel(Product sourceProduct, CoordinateReferenceSystem targetCrs, PropertySet ps) {
this(sourceProduct, ImageGeometry.createTargetGeometry(sourceProduct, targetCrs,
ps.getValue("pixelSizeX"),
ps.getValue("pixelSizeY"),
ps.getValue("width"),
ps.getValue("height"),
ps.getValue("orientation"),
ps.getValue("easting"),
ps.getValue("northing"),
ps.getValue("referencePixelX"),
ps.getValue("referencePixelY")));
}
public OutputGeometryFormModel(OutputGeometryFormModel formModel) {
init(formModel.sourceProduct, formModel.targetCrs, formModel.getPropertySet());
}
private OutputGeometryFormModel(Product sourceProduct, ImageGeometry imageGeometry) {
init(sourceProduct, imageGeometry.getMapCrs(), PropertyContainer.createObjectBacked(imageGeometry));
}
private void init(Product sourceProduct, CoordinateReferenceSystem targetCrs,
PropertySet sourcePropertySet) {
this.sourceProduct = sourceProduct;
this.targetCrs = targetCrs;
this.setFitProductSize(getFitProductSize(sourceProduct, sourcePropertySet, targetCrs));
this.setReferencePixelLocation(getReferencePixelLocation(sourcePropertySet));
this.propertyContainer = PropertyContainer.createValueBacked(ImageGeometry.class);
configurePropertyContainer(propertyContainer);
Property[] properties = sourcePropertySet.getProperties();
for (Property property : properties) {
if (propertyContainer.isPropertyDefined(property.getName())) {
propertyContainer.setValue(property.getName(), property.getValue());
}
}
}
public PropertySet getPropertySet() {
return propertyContainer;
}
public void setSourceProduct(Product sourceProduct) {
this.sourceProduct = sourceProduct;
updateProductSize();
}
public void setTargetCrs(CoordinateReferenceSystem targetCrs) {
this.targetCrs = targetCrs;
updateProductSize();
setAxisUnits(propertyContainer);
}
public void resetToDefaults(ImageGeometry ig) {
PropertyContainer pc = PropertyContainer.createObjectBacked(ig);
Property[] properties = pc.getProperties();
for (Property property : properties) {
propertyContainer.setValue(property.getName(), property.getValue());
}
propertyContainer.setValue("referencePixelLocation", REFERENCE_PIXEL_DEFAULT);
propertyContainer.setValue("fitProductSize", FIT_PRODUCT_SIZE_DEFAULT);
}
private void configurePropertyContainer(PropertySet ps) {
PropertySet thisPS = PropertyContainer.createObjectBacked(this);
ps.addProperties(thisPS.getProperties());
ps.getDescriptor("referencePixelLocation").setValueSet(new ValueSet(new Integer[]{0, 1, 2}));
setAxisUnits(ps);
ps.getDescriptor("orientation").setUnit("°");
ps.addPropertyChangeListener(new ChangeListener());
}
private void setAxisUnits(PropertySet pc) {
if (targetCrs != null) {
String crsAxisUnit = targetCrs.getCoordinateSystem().getAxis(0).getUnit().toString();
pc.getDescriptor("easting").setUnit(crsAxisUnit);
pc.getDescriptor("northing").setUnit(crsAxisUnit);
pc.getDescriptor("pixelSizeX").setUnit(crsAxisUnit);
pc.getDescriptor("pixelSizeY").setUnit(crsAxisUnit);
}
}
private void updateProductSize() {
if (targetCrs != null && sourceProduct != null) {
Double pixelSizeX = propertyContainer.getValue("pixelSizeX");
Double pixelSizeY = propertyContainer.getValue("pixelSizeY");
Rectangle productSize = ImageGeometry.calculateProductSize(sourceProduct, targetCrs, pixelSizeX, pixelSizeY);
propertyContainer.setValue("width", productSize.width);
propertyContainer.setValue("height", productSize.height);
}
}
private void updateReferencePixel() {
double referencePixelX = propertyContainer.getValue("referencePixelX");
double referencePixelY = propertyContainer.getValue("referencePixelY");
if (getReferencePixelLocation() == REFERENCE_PIXEL_UPPER_LEFT) {
referencePixelX = 0.5;
referencePixelY = 0.5;
} else if (getReferencePixelLocation() == REFERENCE_PIXEL_SCENE_CENTER) {
referencePixelX = 0.5 * (Integer) propertyContainer.getValue("width");
referencePixelY = 0.5 * (Integer) propertyContainer.getValue("height");
}
propertyContainer.setValue("referencePixelX", referencePixelX);
propertyContainer.setValue("referencePixelY", referencePixelY);
}
private static boolean getFitProductSize(Product sourceProduct, PropertySet sourcePropertySet, CoordinateReferenceSystem targetCrs) {
// if either width or height is set then don't set fit product size
if (sourceProduct != null) {
int width = sourcePropertySet.getValue("width");
int height = sourcePropertySet.getValue("height");
ImageGeometry iGeometry;
iGeometry = ImageGeometry.createTargetGeometry(sourceProduct, targetCrs,
null, null, null, null,
null, null, null, null,
null);
// }
Rectangle imageRect = iGeometry.getImageRect();
return width == imageRect.width && height == imageRect.height;
} else {
return !(sourcePropertySet.getProperty("width") != null || sourcePropertySet.getProperty("height") != null);
}
}
private static int getReferencePixelLocation(PropertySet sourcePropertySet) {
if (sourcePropertySet != null) {
double referencePixelX = sourcePropertySet.getValue("referencePixelX");
double referencePixelY = sourcePropertySet.getValue("referencePixelY");
int width = sourcePropertySet.getValue("width");
int height = sourcePropertySet.getValue("height");
if (referencePixelX == 0.5 && referencePixelY == 0.5) {
return REFERENCE_PIXEL_UPPER_LEFT;
} else if (referencePixelX == width / 2.0 && referencePixelY == height / 2.0) {
return REFERENCE_PIXEL_SCENE_CENTER;
} else {
return REFERENCE_PIXEL_USER;
}
} else {
return REFERENCE_PIXEL_DEFAULT;
}
}
/**
* @return The reference location id. Possible values are
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_UPPER_LEFT REFERENCE_PIXEL_UPPER_LEFT[0]]},
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_SCENE_CENTER REFERENCE_PIXEL_SCENE_CENTER[1]},
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_USER REFERENCE_PIXEL_USER[2]}.
*/
public int getReferencePixelLocation() {
return referencePixelLocation;
}
/**
* Sets the reference location id. Possible values are
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_UPPER_LEFT REFERENCE_PIXEL_UPPER_LEFT[0]]},
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_SCENE_CENTER REFERENCE_PIXEL_SCENE_CENTER[1]},
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_USER REFERENCE_PIXEL_USER[2]}.
*/
public void setReferencePixelLocation(int referencePixelLocation) {
this.referencePixelLocation = referencePixelLocation;
}
/**
* Checks if the reference pixel location is set to the specified ID.
*
* @param referencePixelLocationId - known values are
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_UPPER_LEFT REFERENCE_PIXEL_UPPER_LEFT[0]]},
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_SCENE_CENTER REFERENCE_PIXEL_SCENE_CENTER[1]},
* {@link OutputGeometryFormModel#REFERENCE_PIXEL_USER REFERENCE_PIXEL_USER[2]}.
* @return true, only if the location is set to the specified reference id.
*/
boolean isReferencePixelLocationSetTo(int referencePixelLocationId) {
return getReferencePixelLocation() == referencePixelLocationId;
}
public boolean isFitProductSize() {
return fitProductSize;
}
public void setFitProductSize(boolean fitProductSize) {
this.fitProductSize = fitProductSize;
}
private class ChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent event) {
String propertyName = event.getPropertyName();
if (isFitProductSize()) {
if (propertyName.startsWith("pixelSize") || propertyName.startsWith("fitProductSize")) {
updateProductSize();
updateReferencePixel();
}
} else if (propertyName.startsWith("referencePixelLocation")
|| ((propertyName.startsWith("width") || propertyName.startsWith("height"))
&& getReferencePixelLocation() == REFERENCE_PIXEL_SCENE_CENTER)) {
updateReferencePixel();
}
}
}
}
| 11,776 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CrsInfo.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/CrsInfo.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.ui.crs;
import org.esa.snap.core.datamodel.GeoPos;
import org.geotools.util.factory.Hints;
import org.geotools.metadata.iso.citation.Citations;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.geotools.referencing.factory.FallbackAuthorityFactory;
import org.geotools.referencing.factory.wms.AutoCRSFactory;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CRSAuthorityFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.crs.GeodeticCRS;
import org.opengis.referencing.crs.ProjectedCRS;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author Marco Peters
* @author Marco Zühlke
* @since BEAM 4.7
*/
class CrsInfo implements Comparable<CrsInfo> {
private static final String AUTHORITY = "EPSG";
private final String crsCode;
private final CRSAuthorityFactory factory;
CrsInfo(String crsCode, CRSAuthorityFactory factory) {
this.crsCode = crsCode;
this.factory = factory;
}
public CoordinateReferenceSystem getCrs(GeoPos referencePos) throws FactoryException {
return factory.createCoordinateReferenceSystem(crsCode);
}
@Override
public int compareTo(CrsInfo o) {
return crsCode.compareTo(o.crsCode);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof CrsInfo)) {
return false;
}
CrsInfo crsInfo = (CrsInfo) o;
return !(crsCode != null ? !crsCode.equals(crsInfo.crsCode) : crsInfo.crsCode != null);
}
@Override
public int hashCode() {
return crsCode != null ? crsCode.hashCode() : 0;
}
@Override
public String toString() {
String crsDescription = crsCode + " - ";
try {
crsDescription += factory.getDescriptionText(crsCode).toString();
} catch (Exception e) {
crsDescription += e.getLocalizedMessage();
}
return crsDescription;
}
public String getDescription() {
try {
return getCrs(null).toString();
} catch (FactoryException e) {
return e.getMessage();
}
}
private static class AutoCrsInfo extends CrsInfo {
AutoCrsInfo(String epsgCode, CRSAuthorityFactory factory) {
super(epsgCode, factory);
}
@Override
public CoordinateReferenceSystem getCrs(GeoPos referencePos) throws FactoryException {
if (referencePos == null) {
referencePos = new GeoPos(0, 0);
}
String code = String.format("%s,%s,%s", super.crsCode, referencePos.lon, referencePos.lat);
return super.factory.createCoordinateReferenceSystem(code);
}
@Override
public String toString() {
String crsDescription = super.crsCode + " - ";
try {
String code = super.crsCode + ",0,0";
crsDescription += super.factory.getDescriptionText(code).toString();
} catch (Exception e) {
crsDescription += e.getLocalizedMessage();
}
return crsDescription;
}
@Override
public String getDescription() {
return toString();
}
}
static List<CrsInfo> generateCRSList() {
// todo - (mp/mz) this method takes time (2 sec.) try to speed up
Hints hints = new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, true);
Set<CRSAuthorityFactory> factories = ReferencingFactoryFinder.getCRSAuthorityFactories(hints);
final List<CRSAuthorityFactory> filtered = new ArrayList<CRSAuthorityFactory>();
for (final CRSAuthorityFactory factory : factories) {
if (Citations.identifierMatches(factory.getAuthority(), AUTHORITY)) {
filtered.add(factory);
}
}
CRSAuthorityFactory crsAuthorityFactory = FallbackAuthorityFactory.create(CRSAuthorityFactory.class, filtered);
Set<String> codes = new HashSet<String>();
List<CrsInfo> crsList = new ArrayList<CrsInfo>(1024);
retrieveCodes(codes, GeodeticCRS.class, crsAuthorityFactory);
retrieveCodes(codes, ProjectedCRS.class, crsAuthorityFactory);
for (String code : codes) {
final String authCode = String.format("%s:%s", AUTHORITY, code);
crsList.add(new CrsInfo(authCode, crsAuthorityFactory));
}
codes.clear();
AutoCRSFactory autoCRSFactory = new AutoCRSFactory();
retrieveCodes(codes, ProjectedCRS.class, autoCRSFactory);
for (String code : codes) {
final String authCode = String.format("AUTO:%s", code);
crsList.add(new AutoCrsInfo(authCode, autoCRSFactory));
}
Collections.sort(crsList);
return crsList;
}
private static void retrieveCodes(Set<String> codes, Class<? extends CoordinateReferenceSystem> crsType,
CRSAuthorityFactory factory) {
Set<String> localCodes;
try {
localCodes = factory.getAuthorityCodes(crsType);
} catch (FactoryException ignore) {
return;
}
codes.addAll(localCodes);
}
}
| 6,142 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PredefinedCrsPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/PredefinedCrsPanel.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.ui.crs;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.TableLayout.Anchor;
import com.bc.ceres.swing.TableLayout.Fill;
import com.jidesoft.swing.LabeledTextField;
import org.esa.snap.ui.util.FilteredListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import java.awt.Container;
import java.awt.Dimension;
import java.util.logging.Logger;
class PredefinedCrsPanel extends JPanel {
public static final Logger LOG = Logger.getLogger(PredefinedCrsPanel.class.getName());
private final CrsInfoListModel crsListModel;
private JTextArea infoArea;
private JList<CrsInfo> crsList;
private LabeledTextField filterField;
private CrsInfo selectedCrsInfo;
private FilteredListModel<CrsInfo> filteredListModel;
// for testing the UI
public static void main(String[] args) {
final JFrame frame = new JFrame("CRS Selection Panel");
Container contentPane = frame.getContentPane();
final CrsInfoListModel listModel = new CrsInfoListModel(CrsInfo.generateCRSList());
PredefinedCrsPanel predefinedCrsForm = new PredefinedCrsPanel(listModel);
contentPane.add(predefinedCrsForm);
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(() -> frame.setVisible(true));
}
PredefinedCrsPanel(CrsInfoListModel model) {
crsListModel = model;
createUI();
}
private void createUI() {
filterField = new LabeledTextField();
filterField.setHintText("Type here to filter CRS");
filterField.getTextField().getDocument().addDocumentListener(new FilterDocumentListener());
filteredListModel = new FilteredListModel<>(crsListModel);
crsList = new JList<>(filteredListModel);
crsList.setVisibleRowCount(15);
crsList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final JLabel filterLabel = new JLabel("Filter:");
final JLabel infoLabel = new JLabel("Well-Known Text (WKT):");
final JScrollPane crsListScrollPane = new JScrollPane(crsList);
crsListScrollPane.setPreferredSize(new Dimension(200, 150));
infoArea = new JTextArea(15, 30);
infoArea.setEditable(false);
crsList.addListSelectionListener(new CrsListSelectionListener());
crsList.setSelectedIndex(0);
final JScrollPane infoAreaScrollPane = new JScrollPane(infoArea);
TableLayout tableLayout = new TableLayout(3);
setLayout(tableLayout);
tableLayout.setTableFill(Fill.BOTH);
tableLayout.setTableAnchor(Anchor.NORTHWEST);
tableLayout.setTableWeightX(1.0);
tableLayout.setTablePadding(4, 4);
tableLayout.setRowWeightY(0, 0.0); // no weight Y for first row
tableLayout.setCellWeightX(0, 0, 0.0); // filter label; no grow in X
tableLayout.setRowWeightY(1, 1.0); // second row grow in Y
tableLayout.setCellColspan(1, 0, 2); // CRS list; spans 2 cols
tableLayout.setCellRowspan(1, 2, 2); // info area; spans 2 rows
tableLayout.setCellColspan(2, 0, 2); // defineCrsBtn button; spans to cols
add(filterLabel);
add(filterField);
add(infoLabel);
add(crsListScrollPane);
add(infoAreaScrollPane);
addPropertyChangeListener("enabled", evt -> {
filterLabel.setEnabled((Boolean) evt.getNewValue());
filterField.setEnabled((Boolean) evt.getNewValue());
infoLabel.setEnabled((Boolean) evt.getNewValue());
crsList.setEnabled((Boolean) evt.getNewValue());
crsListScrollPane.setEnabled((Boolean) evt.getNewValue());
infoArea.setEnabled((Boolean) evt.getNewValue());
infoAreaScrollPane.setEnabled((Boolean) evt.getNewValue());
});
crsList.getSelectionModel().setSelectionInterval(0, 0);
}
private class FilterDocumentListener implements DocumentListener {
@Override
public void insertUpdate(DocumentEvent e) {
updateFilter(getFilterText(e));
clearListSelection();
}
@Override
public void removeUpdate(DocumentEvent e) {
updateFilter(getFilterText(e));
clearListSelection();
}
private void clearListSelection() {
crsList.clearSelection();
setInfoText("");
}
@Override
public void changedUpdate(DocumentEvent e) {
}
private void updateFilter(String text) {
filteredListModel.setFilter(crsInfo -> {
String description = crsInfo.toString().toLowerCase();
return description.contains(text.trim().toLowerCase());
});
}
private String getFilterText(DocumentEvent e) {
Document document = e.getDocument();
String text = null;
try {
text = document.getText(0, document.getLength());
} catch (BadLocationException e1) {
LOG.severe(e1.getMessage());
}
return text;
}
}
private class CrsListSelectionListener implements ListSelectionListener {
@Override
public void valueChanged(ListSelectionEvent e) {
final JList list = (JList) e.getSource();
selectedCrsInfo = (CrsInfo) list.getSelectedValue();
if (selectedCrsInfo != null) {
try {
setInfoText(selectedCrsInfo.getDescription());
} catch (Exception e1) {
String message = e1.getMessage();
if (message != null) {
setInfoText("Error while creating CRS:\n\n" + message);
}
}
}
}
}
CrsInfo getSelectedCrsInfo() {
return selectedCrsInfo;
}
private void setInfoText(String infoText) {
infoArea.setText(infoText);
infoArea.setCaretPosition(0);
}
}
| 7,335 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OutputGeometryForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/OutputGeometryForm.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.ui.crs;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyEditor;
import com.bc.ceres.swing.binding.PropertyEditorRegistry;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.GridBagUtils;
import org.geotools.referencing.CRS;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.ButtonGroup;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
/**
* @author Marco Zuehlke
* @since BEAM 4.7
*/
public class OutputGeometryForm extends JPanel {
private final BindingContext context;
private JCheckBox fitProductSizeCheckBox;
private JTextField widthTextfield;
private JTextField heightTextfield;
private final OutputGeometryFormModel model;
public OutputGeometryForm(OutputGeometryFormModel model) {
context = new BindingContext(model.getPropertySet());
this.model = model;
createUI();
}
private void createUI() {
int line = 0;
JPanel dialogPane = GridBagUtils.createPanel();
dialogPane.setBorder(new EmptyBorder(7, 7, 7, 7));
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
GridBagUtils.setAttributes(gbc, "insets.top=0,gridwidth=3");
JRadioButton pixelRefULeftButton = new JRadioButton("Reference pixel is at scene upper left", false);
JRadioButton pixelRefCenterButton = new JRadioButton("Reference pixel is at scene center", false);
JRadioButton pixelRefOtherButton = new JRadioButton("Other reference pixel position", false);
ButtonGroup g = new ButtonGroup();
g.add(pixelRefULeftButton);
g.add(pixelRefCenterButton);
g.add(pixelRefOtherButton);
context.bind("referencePixelLocation", g);
context.bindEnabledState("referencePixelX", true, "referencePixelLocation", 2);
context.bindEnabledState("referencePixelY", true, "referencePixelLocation", 2);
if (model.isReferencePixelLocationSetTo(OutputGeometryFormModel.REFERENCE_PIXEL_UPPER_LEFT)) {
pixelRefULeftButton.setSelected(true);
} else if (model.isReferencePixelLocationSetTo(OutputGeometryFormModel.REFERENCE_PIXEL_SCENE_CENTER)) {
pixelRefCenterButton.setSelected(true);
} else {
pixelRefOtherButton.setSelected(true);
}
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, pixelRefULeftButton, gbc, "fill=HORIZONTAL,weightx=1");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, pixelRefCenterButton, gbc);
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, pixelRefOtherButton, gbc);
gbc.gridy = ++line;
JComponent[] components = createComponents("referencePixelX");
JComponent unitcomponent = createUnitComponent("referencePixelX");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=1,gridwidth=1,fill=NONE,weightx=0");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
JTextField referencePixelXTextfield = (JTextField) components[0];
if (pixelRefCenterButton.isSelected()) {
referencePixelXTextfield.setEnabled(false);
}
gbc.gridy = ++line;
components = createComponents("referencePixelY");
unitcomponent = createUnitComponent("referencePixelY");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=3");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
JTextField referencePixelYTextfield = (JTextField) components[0];
if (pixelRefCenterButton.isSelected()) {
referencePixelYTextfield.setEnabled(false);
}
gbc.gridy = ++line;
components = createComponents("easting");
unitcomponent = createUnitComponent("easting");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=12");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
JTextField eastingTextfield = (JTextField) components[0];
String original = eastingTextfield.getText();
eastingTextfield.setText("0.01234567890123456789");
Dimension size = eastingTextfield.getPreferredSize();
eastingTextfield.setText(original);
eastingTextfield.setPreferredSize(size);
gbc.gridy = ++line;
components = createComponents("northing");
unitcomponent = createUnitComponent("northing");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=3");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
gbc.gridy = ++line;
components = createComponents("orientation");
unitcomponent = createUnitComponent("orientation");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=3");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
gbc.gridy = ++line;
components = createComponents("pixelSizeX");
unitcomponent = createUnitComponent("pixelSizeX");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=12");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
gbc.gridy = ++line;
components = createComponents("pixelSizeY");
unitcomponent = createUnitComponent("pixelSizeY");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=3");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
gbc.gridy = ++line;
components = createComponents("fitProductSize");
context.bindEnabledState("width", false, "fitProductSize", true);
context.bindEnabledState("height", false, "fitProductSize", true);
fitProductSizeCheckBox = ((JCheckBox) components[0]);
GridBagUtils.addToPanel(dialogPane, fitProductSizeCheckBox, gbc, "insets.top=12, gridwidth=3,fill=HORIZONTAL,weightx=1");
gbc.gridy = ++line;
components = createComponents("width");
unitcomponent = createUnitComponent("width");
GridBagUtils.addToPanel(dialogPane, components[1], gbc, "insets.top=3, gridwidth=1,fill=NONE,weightx=0");
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
widthTextfield = (JTextField) components[0];
if (model.isFitProductSize()) {
widthTextfield.setEnabled(false);
}
gbc.gridy = ++line;
components = createComponents("height");
unitcomponent = createUnitComponent("height");
GridBagUtils.addToPanel(dialogPane, components[1], gbc);
GridBagUtils.addToPanel(dialogPane, components[0], gbc, "fill=HORIZONTAL,weightx=1");
GridBagUtils.addToPanel(dialogPane, unitcomponent, gbc, "fill=NONE,weightx=0");
heightTextfield = (JTextField) components[0];
if (model.isFitProductSize()) {
heightTextfield.setEnabled(false);
}
//Add Listener
fitProductSizeCheckBox.addActionListener(e -> {
if (fitProductSizeCheckBox.isSelected()) {
// reset width and height
// disable width and height
widthTextfield.setEnabled(false);
heightTextfield.setEnabled(false);
} else {
// don't reset width and height
// enable width and height
widthTextfield.setEnabled(true);
heightTextfield.setEnabled(true);
}
}
);
if (model.isFitProductSize()) {
fitProductSizeCheckBox.setSelected(true);
}
add(dialogPane);
}
private JComponent[] createComponents(String propertyName) {
PropertyDescriptor descriptor = context.getPropertySet().getDescriptor(propertyName);
PropertyEditorRegistry propertyEditorRegistry = PropertyEditorRegistry.getInstance();
PropertyEditor editor = propertyEditorRegistry.findPropertyEditor(descriptor);
return editor.createComponents(descriptor, context);
}
private JComponent createUnitComponent(String propertyName) {
PropertyDescriptor descriptor = context.getPropertySet().getDescriptor(propertyName);
JLabel unitLabel = new JLabel(descriptor.getUnit());
context.getBinding(propertyName).addComponent(unitLabel);
return unitLabel;
}
// for testing the UI
public static void main(String[] args) throws Exception {
final JFrame jFrame = new JFrame("Output parameter Definition Form");
Container contentPane = jFrame.getContentPane();
if (args.length == 0) {
throw new IllegalArgumentException("Missing argument to product file.");
}
Product sourceProduct = ProductIO.readProduct(args[0]);
CoordinateReferenceSystem targetCrs = CRS.decode("EPSG:32632");
OutputGeometryFormModel model = new OutputGeometryFormModel(sourceProduct, targetCrs);
OutputGeometryForm form = new OutputGeometryForm(model);
contentPane.add(form);
jFrame.setSize(400, 600);
jFrame.setLocationRelativeTo(null);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(() -> jFrame.setVisible(true));
}
}
| 11,382 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PredefinedCrsForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/PredefinedCrsForm.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.ui.crs;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.ModalDialog;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
public class PredefinedCrsForm extends CrsForm {
private CrsInfo selectedCrsInfo;
public PredefinedCrsForm(AppContext appContext) {
super(appContext);
}
@Override
protected String getLabelText() {
return "Predefined CRS";
}
@Override
public CoordinateReferenceSystem getCRS(GeoPos referencePos) throws FactoryException {
if (selectedCrsInfo != null) {
return selectedCrsInfo.getCrs(referencePos);
} else {
return null;
}
}
@Override
public void prepareShow() {
}
@Override
public void prepareHide() {
}
@Override
protected JComponent createCrsComponent() {
final TableLayout tableLayout = new TableLayout(2);
final JPanel panel = new JPanel(tableLayout);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setColumnWeightX(0, 1.0);
tableLayout.setColumnWeightX(1, 0.0);
final JTextField crsCodeField = new JTextField();
crsCodeField.setEditable(false);
final JButton crsButton = new JButton("Select...");
final PredefinedCrsPanel predefinedCrsForm = new PredefinedCrsPanel(
new CrsInfoListModel(CrsInfo.generateCRSList()));
crsButton.addActionListener(e -> {
final ModalDialog dialog = new ModalDialog(null,
"Select Coordinate Reference System",
predefinedCrsForm,
ModalDialog.ID_OK_CANCEL, null);
if (dialog.show() == ModalDialog.ID_OK) {
selectedCrsInfo = predefinedCrsForm.getSelectedCrsInfo();
if (selectedCrsInfo != null) {
crsCodeField.setText(selectedCrsInfo.toString());
fireCrsChanged();
}
}
});
panel.add(crsCodeField);
panel.add(crsButton);
panel.addPropertyChangeListener("enabled", evt -> {
crsCodeField.setEnabled((Boolean) evt.getNewValue());
crsButton.setEnabled((Boolean) evt.getNewValue());
});
return panel;
}
}
| 3,497 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomCrsForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/CustomCrsForm.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.ui.crs;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.crs.projdef.CustomCrsPanel;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.GeodeticDatum;
import org.opengis.referencing.operation.OperationMethod;
import org.openide.windows.WindowManager;
import javax.swing.JComponent;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
public class CustomCrsForm extends CrsForm {
public CustomCrsForm(AppContext appContext) {
super(appContext);
}
@Override
protected String getLabelText() {
return "Custom CRS";
}
@Override
boolean wrapAfterButton() {
return true;
}
@Override
public CoordinateReferenceSystem getCRS(GeoPos referencePos) throws FactoryException {
return ((CustomCrsPanel)getCrsUI()).getCRS(referencePos);
}
@Override
protected JComponent createCrsComponent() {
final CustomCrsPanel panel = new CustomCrsPanel(WindowManager.getDefault().getMainWindow(),
CustomCrsPanel.createDatumSet(), CustomCrsPanel.createCrsProviderSet());
panel.addPropertyChangeListener("crs", evt -> fireCrsChanged());
return panel;
}
@Override
public void prepareShow() {
}
@Override
public void prepareHide() {
}
public void setCustom(GeodeticDatum geodeticDatum, OperationMethod mapProjection, ParameterValueGroup parameterValues) {
CustomCrsPanel customCrsPanel = (CustomCrsPanel) getCrsUI();
customCrsPanel.setCustom(geodeticDatum, mapProjection, parameterValues);
}
}
| 2,531 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CrsForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/CrsForm.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.ui.crs;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.AppContext;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.JComponent;
import javax.swing.JRadioButton;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
public abstract class CrsForm {
private AppContext appContext;
private Product referenceProduct;
private ArrayList<PropertyChangeListener> changeListeners;
private JComponent crsComponent;
private JRadioButton radioButton;
protected CrsForm(AppContext appContext) {
this.appContext = appContext;
changeListeners = new ArrayList<PropertyChangeListener>();
}
protected abstract String getLabelText();
boolean wrapAfterButton() {
return false;
}
public final JRadioButton getRadioButton(){
if(radioButton == null) {
radioButton = createRadioButton();
}
return radioButton;
}
protected JRadioButton createRadioButton() {
return new JRadioButton(getLabelText());
}
public abstract CoordinateReferenceSystem getCRS(GeoPos referencePos) throws FactoryException;
public final JComponent getCrsUI() {
if(crsComponent == null) {
crsComponent = createCrsComponent();
}
return crsComponent;
}
protected abstract JComponent createCrsComponent();
public void setReferenceProduct(Product product) {
referenceProduct = product;
}
protected Product getReferenceProduct() {
return referenceProduct;
}
protected AppContext getAppContext() {
return appContext;
}
protected void fireCrsChanged() {
for (PropertyChangeListener listener : changeListeners) {
listener.propertyChange(new PropertyChangeEvent(this, "crs", null, null));
}
}
protected boolean addCrsChangeListener(PropertyChangeListener listener) {
if (!changeListeners.contains(listener)) {
return changeListeners.add(listener);
}
return false;
}
protected boolean removeCrsChangeListener(PropertyChangeListener listener) {
if (changeListeners.contains(listener)) {
return changeListeners.remove(listener);
}
return false;
}
public abstract void prepareShow();
public abstract void prepareHide();
}
| 3,325 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CrsInfoListModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/CrsInfoListModel.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.ui.crs;
import javax.swing.AbstractListModel;
import java.util.ArrayList;
import java.util.List;
/**
* @author Marco Peters
* @since BEAM 4.6
*/
class CrsInfoListModel extends AbstractListModel<CrsInfo> {
private final List<CrsInfo> crsList;
CrsInfoListModel(List<CrsInfo> crsList) {
this.crsList = new ArrayList<>(crsList);
}
@Override
public CrsInfo getElementAt(int index) {
return crsList.get(index);
}
@Override
public int getSize() {
return crsList.size();
}
}
| 1,277 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductCrsForm.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/ProductCrsForm.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.ui.crs;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.ui.AppContext;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.JComponent;
import javax.swing.JTextField;
public class ProductCrsForm extends CrsForm {
private final Product product;
public ProductCrsForm(AppContext appContext, Product product) {
super(appContext);
this.product = product;
}
@Override
protected String getLabelText() {
return "Use target CRS";
}
@Override
public CoordinateReferenceSystem getCRS(GeoPos referencePos) throws FactoryException {
return getMapCrs();
}
private CoordinateReferenceSystem getMapCrs() {
return product.getSceneGeoCoding().getMapCRS();
}
@Override
protected JComponent createCrsComponent() {
final JTextField field = new JTextField();
field.setEditable(false);
field.setText(getMapCrs().getName().getCode());
return field;
}
@Override
public void prepareShow() {
}
@Override
public void prepareHide() {
}
}
| 1,952 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CrsSelectionPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/CrsSelectionPanel.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.ui.crs;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.Product;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
/**
* @author Marco Peters
* @author Marco Zühlke
* @since BEAM 4.7
*/
public class CrsSelectionPanel extends JPanel {
private CrsChangeListener crsChangeListener;
private final CrsForm[] crsForms;
public CrsSelectionPanel(CrsForm... crsForms) {
this.crsForms = crsForms;
createUI();
crsChangeListener = new CrsChangeListener();
addPropertyChangeListener("enabled", new EnabledChangeListener());
}
public void setReferenceProduct(Product product) {
for (CrsForm crsForm : crsForms) {
crsForm.setReferenceProduct(product);
}
}
public CoordinateReferenceSystem getCrs(GeoPos referencePos) throws FactoryException {
for (CrsForm crsForm : crsForms) {
if (crsForm.getRadioButton().isSelected()) {
return crsForm.getCRS(referencePos);
}
}
return null;
}
public void prepareShow() {
for (CrsForm crsForm : crsForms) {
crsForm.prepareShow();
crsForm.addCrsChangeListener(crsChangeListener);
}
updateUIState();
}
public void prepareHide() {
for (CrsForm crsForm : crsForms) {
crsForm.prepareHide();
crsForm.removeCrsChangeListener(crsChangeListener);
}
}
private void updateUIState() {
for (CrsForm crsForm : crsForms) {
crsForm.getCrsUI().setEnabled(crsForm.getRadioButton().isSelected());
}
}
private void createUI() {
ButtonGroup buttonGroup = new ButtonGroup();
final TableLayout tableLayout = new TableLayout(2);
tableLayout.setTablePadding(4, 4);
tableLayout.setTableFill(TableLayout.Fill.BOTH);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setTableWeightX(1.0);
tableLayout.setTableWeightY(0.0);
setLayout(tableLayout);
setBorder(BorderFactory.createTitledBorder("Coordinate Reference System (CRS)"));
final UpdateStateListener updateStateListener = new UpdateStateListener();
int rowCount = 0;
for (int i = 0, crsFormsLength = crsForms.length; i < crsFormsLength; i++) {
CrsForm crsForm = crsForms[i];
JRadioButton crsRadioButton = crsForm.getRadioButton();
crsRadioButton.setSelected(i == 0);
crsRadioButton.addActionListener(updateStateListener);
JComponent crsComponent = crsForm.getCrsUI();
crsComponent.setEnabled(i == 0);
buttonGroup.add(crsRadioButton);
if (crsForm.wrapAfterButton()) {
tableLayout.setCellColspan(rowCount, 0, 2);
rowCount++;
tableLayout.setCellColspan(rowCount, 0, 2);
tableLayout.setCellPadding(rowCount, 0, new Insets(4, 24, 4, 4));
rowCount++;
} else {
tableLayout.setCellWeightX(rowCount, 0, 0.0);
rowCount++;
}
add(crsRadioButton);
add(crsComponent);
}
}
private class UpdateStateListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
updateUIState();
fireCrsChanged();
}
}
private class CrsChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
fireCrsChanged();
}
}
private void fireCrsChanged() {
firePropertyChange("crs", null, null);
}
private class EnabledChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
final Boolean enabled = (Boolean) evt.getNewValue();
for (CrsForm crsForm : crsForms) {
final JRadioButton button = crsForm.getRadioButton();
button.setEnabled(enabled);
final boolean selected = button.isSelected();
crsForm.getCrsUI().setEnabled(selected && enabled);
}
}
}
}
| 5,467 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractUTMCrsProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/projdef/AbstractUTMCrsProvider.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.ui.crs.projdef;
import org.esa.snap.core.util.math.MathUtils;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.geotools.referencing.cs.DefaultCartesianCS;
import org.geotools.referencing.cs.DefaultEllipsoidalCS;
import org.geotools.referencing.operation.projection.MapProjection;
import org.geotools.referencing.operation.projection.TransverseMercator;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CRSFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.crs.GeographicCRS;
import org.opengis.referencing.datum.GeodeticDatum;
import org.opengis.referencing.operation.Conversion;
import org.opengis.referencing.operation.CoordinateOperationFactory;
import org.opengis.referencing.operation.OperationMethod;
import java.util.HashMap;
/**
* @author Marco Peters
* @since BEAM 4.7
*/
abstract class AbstractUTMCrsProvider extends AbstractCrsProvider {
static final int MIN_UTM_ZONE = 1;
static final int MAX_UTM_ZONE = 60;
AbstractUTMCrsProvider(String name, boolean hasParameters, boolean datumChangable,
GeodeticDatum defaultDatum) {
super(name, hasParameters, datumChangable, defaultDatum);
}
static String getProjectionName(int zoneIndex, boolean south) {
return "UTM Zone " + zoneIndex + (south ? ", South" : "");
}
static int getZoneIndex(double longitude) {
final double zoneIndex = ((longitude + 180.0f) / 6.0f - 0.5f) + 1;
return (int)MathUtils.roundAndCrop(zoneIndex, MIN_UTM_ZONE, MAX_UTM_ZONE);
}
private static void setValue(ParameterValueGroup values, ParameterDescriptor<Double> descriptor, double value) {
values.parameter(descriptor.getName().getCode()).setValue(value);
}
protected static double getCentralMeridian(int zoneIndex) {
return (zoneIndex - 0.5) * 6.0 - 180.0;
}
ParameterValueGroup createTransverseMercatorParameters(int zoneIndex, boolean south,
GeodeticDatum datum) {
ParameterDescriptorGroup tmParameters = new TransverseMercator.Provider().getParameters();
ParameterValueGroup tmValues = tmParameters.createValue();
setValue(tmValues, MapProjection.AbstractProvider.SEMI_MAJOR, datum.getEllipsoid().getSemiMajorAxis());
setValue(tmValues, MapProjection.AbstractProvider.SEMI_MINOR, datum.getEllipsoid().getSemiMinorAxis());
setValue(tmValues, MapProjection.AbstractProvider.LATITUDE_OF_ORIGIN, 0.0);
setValue(tmValues, MapProjection.AbstractProvider.CENTRAL_MERIDIAN, getCentralMeridian(zoneIndex));
setValue(tmValues, MapProjection.AbstractProvider.SCALE_FACTOR, 0.9996);
setValue(tmValues, MapProjection.AbstractProvider.FALSE_EASTING, 500000.0);
setValue(tmValues, MapProjection.AbstractProvider.FALSE_NORTHING, south ? 10000000.0 : 0.0);
return tmValues;
}
CoordinateReferenceSystem createCrs(String crsName, OperationMethod method,
ParameterValueGroup parameters,
GeodeticDatum datum) throws FactoryException {
final CRSFactory crsFactory = ReferencingFactoryFinder.getCRSFactory(null);
final CoordinateOperationFactory coFactory = ReferencingFactoryFinder.getCoordinateOperationFactory(null);
final HashMap<String, Object> projProperties = new HashMap<String, Object>();
projProperties.put("name", crsName + " / " + datum.getName().getCode());
final Conversion conversion = coFactory.createDefiningConversion(projProperties,
method,
parameters);
final HashMap<String, Object> baseCrsProperties = new HashMap<String, Object>();
baseCrsProperties.put("name", datum.getName().getCode());
final GeographicCRS baseCrs = crsFactory.createGeographicCRS(baseCrsProperties, datum,
DefaultEllipsoidalCS.GEODETIC_2D);
return crsFactory.createProjectedCRS(projProperties, baseCrs, conversion, DefaultCartesianCS.PROJECTED);
}
}
| 5,255 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UTMZonesCrsProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/projdef/UTMZonesCrsProvider.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.ui.crs.projdef;
import org.esa.snap.core.datamodel.GeoPos;
import org.geotools.metadata.iso.citation.Citations;
import org.geotools.parameter.DefaultParameterDescriptor;
import org.geotools.parameter.DefaultParameterDescriptorGroup;
import org.geotools.referencing.operation.projection.TransverseMercator;
import org.opengis.metadata.citation.Citation;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterDescriptorGroup;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.GeodeticDatum;
import tec.uom.se.AbstractUnit;
class UTMZonesCrsProvider extends AbstractUTMCrsProvider {
private static final String NAME = "UTM Zone";
private static final Citation BEAM = Citations.fromName("BEAM");
private static final String NORTH_HEMISPHERE = "North";
private static final String SOUTH_HEMISPHERE = "South";
private static final String ZONE_NAME = "zone";
private static final String HEMISPHERE_NAME = "hemisphere";
private static final ParameterDescriptor[] DESCRIPTORS = new ParameterDescriptor[]{
new DefaultParameterDescriptor<Integer>(BEAM, ZONE_NAME, Integer.class, null, 1,
MIN_UTM_ZONE, MAX_UTM_ZONE, AbstractUnit.ONE, true),
new DefaultParameterDescriptor<String>(HEMISPHERE_NAME, String.class,
new String[]{NORTH_HEMISPHERE, SOUTH_HEMISPHERE},
NORTH_HEMISPHERE)
};
private static final ParameterDescriptorGroup UTM_PARAMETERS = new DefaultParameterDescriptorGroup(NAME,
DESCRIPTORS);
UTMZonesCrsProvider(GeodeticDatum wgs84Datum) {
super(NAME, true, true, wgs84Datum);
}
@Override
public ParameterValueGroup getParameter() {
return UTM_PARAMETERS.createValue();
}
@Override
public CoordinateReferenceSystem getCRS(final GeoPos referencePos, ParameterValueGroup parameters,
GeodeticDatum datum) throws FactoryException {
int zoneIndex = parameters.parameter(ZONE_NAME).intValue();
String hemisphere1 = parameters.parameter(HEMISPHERE_NAME).stringValue();
boolean south = (SOUTH_HEMISPHERE.equals(hemisphere1));
ParameterValueGroup tmParameters = createTransverseMercatorParameters(zoneIndex, south, datum);
return createCrs(getProjectionName(zoneIndex, south), new TransverseMercator.Provider(), tmParameters, datum);
}
}
| 3,514 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UTMAutomaticCrsProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/projdef/UTMAutomaticCrsProvider.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.ui.crs.projdef;
import org.esa.snap.core.datamodel.GeoPos;
import org.geotools.parameter.ParameterGroup;
import org.geotools.referencing.operation.projection.TransverseMercator;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.GeodeticDatum;
class UTMAutomaticCrsProvider extends AbstractUTMCrsProvider {
private static final String NAME = "UTM / WGS 84 (Automatic)";
UTMAutomaticCrsProvider(GeodeticDatum wgs84Datum) {
super(NAME, false, false, wgs84Datum);
}
@Override
public ParameterValueGroup getParameter() {
return ParameterGroup.EMPTY;
}
@Override
public CoordinateReferenceSystem getCRS(final GeoPos referencePos, ParameterValueGroup parameters,
GeodeticDatum datum) throws FactoryException {
int zoneIndex = getZoneIndex(referencePos.getLon());
final boolean south = referencePos.getLat() < 0.0;
ParameterValueGroup tmParameters = createTransverseMercatorParameters(zoneIndex, south, datum);
final String projName = getProjectionName(zoneIndex, south);
return createCrs(projName, new TransverseMercator.Provider(), tmParameters, datum);
}
}
| 2,086 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractCrsProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/projdef/AbstractCrsProvider.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.ui.crs.projdef;
import org.esa.snap.core.datamodel.GeoPos;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.GeodeticDatum;
abstract class AbstractCrsProvider {
private final String name;
private final boolean hasParameters;
private final boolean isDatumChangable;
private final GeodeticDatum defaultDatum;
AbstractCrsProvider(String name, boolean hasParameters,
boolean datumChangable, GeodeticDatum defaultDatum) {
this.name = name;
this.hasParameters = hasParameters;
isDatumChangable = datumChangable;
this.defaultDatum = defaultDatum;
}
String getName() {
return name;
}
boolean hasParameters() {
return hasParameters;
}
boolean isDatumChangable() {
return isDatumChangable;
}
GeodeticDatum getDefaultDatum() {
return defaultDatum;
}
abstract ParameterValueGroup getParameter();
abstract CoordinateReferenceSystem getCRS(final GeoPos referencePos, ParameterValueGroup parameter,
GeodeticDatum datum) throws FactoryException;
}
| 2,023 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OperationMethodCrsProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/projdef/OperationMethodCrsProvider.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.ui.crs.projdef;
import org.esa.snap.core.datamodel.GeoPos;
import org.geotools.referencing.AbstractIdentifiedObject;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.geotools.referencing.cs.DefaultCartesianCS;
import org.geotools.referencing.cs.DefaultEllipsoidalCS;
import org.geotools.referencing.operation.DefaultOperationMethod;
import org.geotools.referencing.operation.DefiningConversion;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CRSFactory;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.crs.GeographicCRS;
import org.opengis.referencing.datum.GeodeticDatum;
import org.opengis.referencing.operation.Conversion;
import org.opengis.referencing.operation.MathTransform;
import org.opengis.referencing.operation.MathTransformFactory;
import org.opengis.referencing.operation.OperationMethod;
import java.util.HashMap;
class OperationMethodCrsProvider extends AbstractCrsProvider {
final OperationMethod delegate;
OperationMethodCrsProvider(OperationMethod method) {
super(method.getName().getCode().replace("_", " "), true, true, null);
this.delegate = method;
}
@Override
public ParameterValueGroup getParameter() {
return delegate.getParameters().createValue();
}
@Override
public CoordinateReferenceSystem getCRS(final GeoPos referencePos, ParameterValueGroup parameters,
GeodeticDatum datum) throws FactoryException {
final CRSFactory crsFactory = ReferencingFactoryFinder.getCRSFactory(null);
// in some cases, depending on the parameters set, the effective transformation can be different
// from the transformation given by the OperationMethod.
// So we create a new one
final MathTransformFactory mtFactory = ReferencingFactoryFinder.getMathTransformFactory(null);
final MathTransform transform = mtFactory.createParameterizedTransform(parameters);
final DefaultOperationMethod operationMethod = new DefaultOperationMethod(transform);
final Conversion conversion = new DefiningConversion(AbstractIdentifiedObject.getProperties(operationMethod),
operationMethod, transform);
final HashMap<String, Object> baseCrsProperties = new HashMap<String, Object>();
baseCrsProperties.put("name", datum.getName().getCode());
GeographicCRS baseCrs = crsFactory.createGeographicCRS(baseCrsProperties,
datum,
DefaultEllipsoidalCS.GEODETIC_2D);
final HashMap<String, Object> projProperties = new HashMap<String, Object>();
projProperties.put("name", conversion.getName().getCode() + " / " + datum.getName().getCode());
return crsFactory.createProjectedCRS(projProperties, baseCrs, conversion, DefaultCartesianCS.PROJECTED);
}
}
| 3,839 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WGS84CrsProvider.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/projdef/WGS84CrsProvider.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.ui.crs.projdef;
import org.esa.snap.core.datamodel.GeoPos;
import org.geotools.parameter.ParameterGroup;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.GeodeticDatum;
class WGS84CrsProvider extends AbstractCrsProvider {
private static final String NAME = "Geographic Lat/Lon (WGS 84)";
WGS84CrsProvider(GeodeticDatum wgs84Datum) {
super(NAME, false, false, wgs84Datum);
}
@Override
public ParameterValueGroup getParameter() {
return ParameterGroup.EMPTY;
}
@Override
public CoordinateReferenceSystem getCRS(final GeoPos referencePos, ParameterValueGroup parameter,
GeodeticDatum datum) throws FactoryException {
return DefaultGeographicCRS.WGS84;
}
}
| 1,713 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomCrsPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/crs/projdef/CustomCrsPanel.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.ui.crs.projdef;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyAccessor;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.PropertyDescriptor;
import com.bc.ceres.binding.ValueRange;
import com.bc.ceres.binding.ValueSet;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.PropertyPane;
import com.jidesoft.swing.ComboBoxSearchable;
import com.jidesoft.swing.SearchableUtils;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.ui.AbstractDialog;
import org.esa.snap.ui.ModalDialog;
import org.geotools.referencing.AbstractIdentifiedObject;
import org.geotools.referencing.ReferencingFactoryFinder;
import org.geotools.referencing.datum.DefaultGeodeticDatum;
import org.opengis.parameter.GeneralParameterDescriptor;
import org.opengis.parameter.GeneralParameterValue;
import org.opengis.parameter.ParameterDescriptor;
import org.opengis.parameter.ParameterValue;
import org.opengis.parameter.ParameterValueGroup;
import org.opengis.referencing.AuthorityFactory;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.IdentifiedObject;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.datum.DatumAuthorityFactory;
import org.opengis.referencing.datum.Ellipsoid;
import org.opengis.referencing.datum.GeodeticDatum;
import org.opengis.referencing.operation.MathTransformFactory;
import org.opengis.referencing.operation.OperationMethod;
import org.opengis.referencing.operation.Projection;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* @author Marco Peters
* @author Marco Zühlke
* @since BEAM 4.7
*/
public class CustomCrsPanel extends JPanel {
private static final String OPERATION_WRAPPER = "operationWrapper";
private static final String DATUM = "datum";
private static final String PARAMETERS = "parameters";
private final Set<GeodeticDatum> datumSet;
private final Set<AbstractCrsProvider> crsProviderSet;
private final CustomCrsPanel.Model model;
private final PropertyContainer vc;
private final Window parent;
private JComboBox<AbstractCrsProvider> projectionComboBox;
private JComboBox<GeodeticDatum> datumComboBox;
private JButton paramButton;
private static final String SEMI_MAJOR_PARAM_NAME = "semi_major";
private static final String SEMI_MINOR_PARAM_NAME = "semi_minor";
public CustomCrsPanel(Window parent, Set<GeodeticDatum> datumSet, Set<AbstractCrsProvider> crsProviderSet) {
this.parent = parent;
this.datumSet = datumSet;
this.crsProviderSet = crsProviderSet;
GeodeticDatum wgs84Datum = null;
// This is necessary because DefaultGeodeticDatum.WGS84 is
// not equal to the geodetic WGS84 datum from the database
for (GeodeticDatum geodeticDatum : datumSet) {
if (DefaultGeodeticDatum.isWGS84(geodeticDatum)) {
wgs84Datum = geodeticDatum;
break;
}
}
AbstractCrsProvider defaultMethod = new WGS84CrsProvider(wgs84Datum);
crsProviderSet.add(defaultMethod);
crsProviderSet.add(new UTMZonesCrsProvider(wgs84Datum));
crsProviderSet.add(new UTMAutomaticCrsProvider(wgs84Datum));
model = new Model();
model.operationWrapper = defaultMethod;
model.datum = wgs84Datum;
vc = PropertyContainer.createObjectBacked(model);
vc.addPropertyChangeListener(new UpdateListener());
createUI();
updateModel(OPERATION_WRAPPER);
}
public CoordinateReferenceSystem getCRS(GeoPos referencePos) throws FactoryException {
return model.operationWrapper.getCRS(referencePos, model.parameters, model.datum);
}
private void createUI() {
final TableLayout tableLayout = new TableLayout(2);
setLayout(tableLayout);
tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL);
tableLayout.setTablePadding(4, 4);
tableLayout.setTableAnchor(TableLayout.Anchor.WEST);
tableLayout.setColumnWeightX(0, 0.0);
tableLayout.setColumnWeightX(1, 1.0);
tableLayout.setCellColspan(2, 0, 2);
tableLayout.setCellAnchor(2, 0, TableLayout.Anchor.EAST);
tableLayout.setCellFill(2, 0, TableLayout.Fill.NONE);
final JLabel datumLabel = new JLabel("Geodetic datum:");
final JLabel projectionLabel = new JLabel("Projection:");
projectionComboBox = new JComboBox<>(crsProviderSet.toArray(new AbstractCrsProvider[crsProviderSet.size()]));
projectionComboBox.setEditable(false); // combobox searchable only works when combobox is not editable.
final ComboBoxSearchable methodSearchable = new CrsProviderSearchable(projectionComboBox);
methodSearchable.installListeners();
projectionComboBox.setRenderer(new CrsProviderCellRenderer());
datumComboBox = new JComboBox<>(datumSet.toArray(new GeodeticDatum[datumSet.size()]));
datumComboBox.setEditable(false); // combobox searchable only works when combobox is not editable.
SearchableUtils.installSearchable(datumComboBox);
datumComboBox.setRenderer(new IdentifiedObjectCellRenderer());
final ComboBoxSearchable datumSearchable = new IdentifiedObjectSearchable(datumComboBox);
datumSearchable.installListeners();
paramButton = new JButton("Projection Parameters...");
paramButton.addActionListener(new ParameterButtonListener());
add(datumLabel);
add(datumComboBox);
add(projectionLabel);
add(projectionComboBox);
add(paramButton);
addPropertyChangeListener("enabled", evt -> updateEnableState((Boolean) evt.getNewValue()));
final BindingContext context = new BindingContext(vc);
context.bind(OPERATION_WRAPPER, projectionComboBox);
context.bind(DATUM, datumComboBox);
}
private void updateEnableState(boolean componentEnabled) {
projectionComboBox.setEnabled(componentEnabled);
datumComboBox.setEnabled(model.operationWrapper.isDatumChangable() && componentEnabled);
paramButton.setEnabled(model.operationWrapper.hasParameters() && componentEnabled);
}
private void updateModel(String propertyName) {
if (OPERATION_WRAPPER.equals(propertyName)) {
GeodeticDatum defaultDatum = model.operationWrapper.getDefaultDatum();
if (defaultDatum != null) {
vc.setValue(DATUM, defaultDatum);
}
Object oldParameterGroup;
if (model.operationWrapper.hasParameters()) {
oldParameterGroup = vc.getValue(PARAMETERS);
ParameterValueGroup newParameters = model.operationWrapper.getParameter();
if (oldParameterGroup instanceof ParameterValueGroup) {
ParameterValueGroup oldParameters = (ParameterValueGroup) oldParameterGroup;
List<GeneralParameterDescriptor> generalParameterDescriptors = newParameters.getDescriptor().descriptors();
List<GeneralParameterValue> oldValues = oldParameters.values();
for (GeneralParameterDescriptor newDescriptor : generalParameterDescriptors) {
String parameterName = newDescriptor.getName().getCode();
for (GeneralParameterValue oldParameterValue : oldValues) {
if (AbstractIdentifiedObject.nameMatches(oldParameterValue.getDescriptor(), newDescriptor)) {
Object old = ((ParameterValue)oldParameterValue).getValue();
newParameters.parameter(parameterName).setValue(old);
}
}
}
}
if (hasParameter(newParameters, SEMI_MAJOR_PARAM_NAME) && hasParameter(newParameters, SEMI_MINOR_PARAM_NAME)) {
Ellipsoid ellipsoid = model.datum.getEllipsoid();
ParameterValue<?> semiMajorParam = newParameters.parameter(SEMI_MAJOR_PARAM_NAME);
if (semiMajorParam.getValue() == null) {
semiMajorParam.setValue(ellipsoid.getSemiMajorAxis());
}
ParameterValue<?> semiMinorParam = newParameters.parameter(SEMI_MINOR_PARAM_NAME);
if (semiMinorParam.getValue() == null) {
semiMinorParam.setValue(ellipsoid.getSemiMinorAxis());
}
}
vc.setValue(PARAMETERS, newParameters);
}
}
if (DATUM.equals(propertyName)) {
if (model.datum != null && model.parameters != null && hasParameter(model.parameters, SEMI_MAJOR_PARAM_NAME) && hasParameter(model.parameters, SEMI_MINOR_PARAM_NAME)) {
Ellipsoid ellipsoid = model.datum.getEllipsoid();
model.parameters.parameter(SEMI_MAJOR_PARAM_NAME).setValue(ellipsoid.getSemiMajorAxis());
model.parameters.parameter(SEMI_MINOR_PARAM_NAME).setValue(ellipsoid.getSemiMinorAxis());
}
}
updateEnableState(true);
firePropertyChange("crs", null, null);
}
private static boolean hasParameter(ParameterValueGroup parameterValueGroup, String name) {
List<GeneralParameterDescriptor> generalParameterDescriptors = parameterValueGroup.getDescriptor().descriptors();
for (GeneralParameterDescriptor descriptor : generalParameterDescriptors) {
if (AbstractIdentifiedObject.nameMatches(descriptor, name)) {
return true;
}
}
return false;
}
public void setCustom(GeodeticDatum geodeticDatum, OperationMethod operationMethod, ParameterValueGroup parameterValues) {
String geodeticDatumName = geodeticDatum.getName().getCode();
for (GeodeticDatum datum : datumSet) {
if (datum.getName().getCode().equals(geodeticDatumName)) {
vc.setValue(DATUM, datum);
break;
}
}
for (AbstractCrsProvider abstractCrsProvider : crsProviderSet) {
if (abstractCrsProvider instanceof OperationMethodCrsProvider) {
OperationMethodCrsProvider operationMethodCrsProvider = (OperationMethodCrsProvider) abstractCrsProvider;
String operationMethodName = operationMethod.getName().getCode();
if (operationMethodCrsProvider.delegate.getName().getCode().equals(operationMethodName)) {
vc.setValue(OPERATION_WRAPPER, abstractCrsProvider);
break;
}
}
}
vc.setValue(PARAMETERS, parameterValues);
}
private class UpdateListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateModel(evt.getPropertyName());
}
}
public static void main(String[] args) {
final JFrame frame = new JFrame("Projection Method Form Test");
final CustomCrsPanel customCrsForm = new CustomCrsPanel(frame, CustomCrsPanel.createDatumSet(), CustomCrsPanel.createCrsProviderSet());
frame.setContentPane(customCrsForm);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
SwingUtilities.invokeLater(() -> {
frame.pack();
frame.setVisible(true);
});
}
public static Set<AbstractCrsProvider> createCrsProviderSet() {
MathTransformFactory factory = ReferencingFactoryFinder.getMathTransformFactory(null);
Set<OperationMethod> methods = factory.getAvailableMethods(Projection.class);
TreeSet<AbstractCrsProvider> crsProviderSet = new TreeSet<>(new CrsProviderComparator());
for (OperationMethod method : methods) {
crsProviderSet.add(new OperationMethodCrsProvider(method));
}
return crsProviderSet;
}
public static Set<GeodeticDatum> createDatumSet() {
DatumAuthorityFactory factory = ReferencingFactoryFinder.getDatumAuthorityFactory("EPSG", null);
List<String> datumCodes = retrieveCodes(GeodeticDatum.class, factory);
Set<GeodeticDatum> datumSet = new TreeSet<>(AbstractIdentifiedObject.NAME_COMPARATOR);
for (String datumCode : datumCodes) {
try {
DefaultGeodeticDatum geodeticDatum = (DefaultGeodeticDatum) factory.createGeodeticDatum(datumCode);
if (geodeticDatum.getBursaWolfParameters().length != 0 ||
DefaultGeodeticDatum.isWGS84(geodeticDatum)) {
datumSet.add(geodeticDatum);
}
} catch (FactoryException ignored) {
}
}
return datumSet;
}
private static List<String> retrieveCodes(Class<? extends GeodeticDatum> crsType, AuthorityFactory factory) {
try {
Set<String> localCodes = factory.getAuthorityCodes(crsType);
return new ArrayList<>(localCodes);
} catch (FactoryException ignore) {
return Collections.emptyList();
}
}
private static PropertyContainer createValueContainer(ParameterValueGroup valueGroup) {
final PropertyContainer vc = new PropertyContainer();
List<GeneralParameterDescriptor> descriptors = valueGroup.getDescriptor().descriptors();
for (GeneralParameterDescriptor descriptor : descriptors) {
final Class valueType;
Set validValues = null;
Comparable minValue = null;
Comparable maxValue = null;
if (descriptor instanceof ParameterDescriptor) {
ParameterDescriptor parameterDescriptor = (ParameterDescriptor) descriptor;
valueType = parameterDescriptor.getValueClass();
validValues = parameterDescriptor.getValidValues();
minValue = parameterDescriptor.getMinimumValue();
maxValue = parameterDescriptor.getMaximumValue();
} else {
valueType = Double.TYPE;
}
final String paramName = descriptor.getName().getCode();
final PropertyDescriptor vd = new PropertyDescriptor(paramName, valueType);
final ParameterValue<?> parameterValue = valueGroup.parameter(paramName);
if (parameterValue.getUnit() != null) {
vd.setUnit(String.valueOf(parameterValue.getUnit()));
}
if (validValues != null) {
vd.setValueSet(new ValueSet(validValues.toArray()));
}
if ( minValue instanceof Double && maxValue instanceof Double) {
Double min = (Double) minValue;
Double max = (Double) maxValue;
vd.setValueRange(new ValueRange(min, max));
if(parameterValue.getValue() == null) {
parameterValue.setValue((min + max) / 2);
}
}
vd.setDefaultConverter();
final Property property = new Property(vd, new PropertyAccessor() {
@Override
public Object getValue() {
return parameterValue.getValue();
}
@Override
public void setValue(Object value) {
parameterValue.setValue(value);
}
});
vc.addProperty(property);
}
return vc;
}
private static class Model {
private AbstractCrsProvider operationWrapper;
private GeodeticDatum datum;
@SuppressWarnings("UnusedDeclaration")
private ParameterValueGroup parameters;
}
private class ParameterButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
final String operationName = model.operationWrapper.getName();
final ModalDialog modalDialog = new ModalDialog(parent, operationName + " - Parameters",
ModalDialog.ID_OK_CANCEL, null);
final ParameterValueGroup workCopy = model.parameters.clone();
final PropertyContainer propertyContainer = createValueContainer(workCopy);
modalDialog.setContent(new PropertyPane(propertyContainer).createPanel());
if (modalDialog.show() == AbstractDialog.ID_OK) {
vc.setValue(PARAMETERS, workCopy);
}
}
}
private static class CrsProviderComparator implements Comparator<AbstractCrsProvider> {
@Override
public int compare(AbstractCrsProvider o1, AbstractCrsProvider o2) {
final String name1 = o1.getName();
final String name2 = o2.getName();
return name1.compareTo(name2);
}
}
private static class IdentifiedObjectSearchable extends ComboBoxSearchable {
private IdentifiedObjectSearchable(JComboBox<GeodeticDatum> operationComboBox) {
super(operationComboBox);
}
@Override
protected String convertElementToString(Object o) {
if (o instanceof IdentifiedObject) {
IdentifiedObject identifiedObject = (IdentifiedObject) o;
return identifiedObject.getName().getCode();
} else {
return super.convertElementToString(o);
}
}
}
private static class CrsProviderSearchable extends ComboBoxSearchable {
private CrsProviderSearchable(JComboBox<AbstractCrsProvider> operationComboBox) {
super(operationComboBox);
}
@Override
protected String convertElementToString(Object o) {
if (o instanceof AbstractCrsProvider) {
AbstractCrsProvider wrapper = (AbstractCrsProvider) o;
return wrapper.getName();
} else {
return super.convertElementToString(o);
}
}
}
private static class CrsProviderCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
final Component component = super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
JLabel label = (JLabel) component;
if (value != null) {
AbstractCrsProvider wrapper = (AbstractCrsProvider) value;
label.setText(wrapper.getName());
}
return label;
}
}
private static class IdentifiedObjectCellRenderer extends DefaultListCellRenderer {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus) {
final Component component = super.getListCellRendererComponent(list, value, index,
isSelected, cellHasFocus);
JLabel label = (JLabel) component;
if (value != null) {
IdentifiedObject identifiedObject = (IdentifiedObject) value;
label.setText(identifiedObject.getName().getCode());
}
return label;
}
}
}
| 21,006 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LabelListCellRenderer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/LabelListCellRenderer.java | package org.esa.snap.ui.loading;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
/**
* Created by jcoravu on 19/12/2018.
*/
public class LabelListCellRenderer<ItemType> extends JLabel implements ListCellRenderer<ItemType> {
private final ItemRenderer<ItemType> itemRenderer;
public LabelListCellRenderer(Insets margins) {
this(margins, null);
}
public LabelListCellRenderer(Insets margins, ItemRenderer<ItemType> itemRenderer) {
this.itemRenderer = itemRenderer;
setOpaque(true);
setBorder(new EmptyBorder(margins));
}
public LabelListCellRenderer(int itemHeight) {
this(itemHeight, null);
}
public LabelListCellRenderer(int itemHeight, ItemRenderer<ItemType> itemRenderer) {
this.itemRenderer = itemRenderer;
setOpaque(true);
Dimension rendererSize = getPreferredSize();
rendererSize.height = itemHeight;
setPreferredSize(rendererSize);
}
@Override
public JLabel getListCellRendererComponent(JList<? extends ItemType> list, ItemType value, int index, boolean isSelected, boolean cellHasFocus) {
Color backgroundColor;
Color foregroundColor;
if (isSelected) {
backgroundColor = list.getSelectionBackground();
foregroundColor = list.getSelectionForeground();
} else {
backgroundColor = list.getBackground();
foregroundColor = list.getForeground();
}
setBackground(backgroundColor);
setForeground(foregroundColor);
String itemDisplayName = getItemDisplayText(value);
setText(itemDisplayName);
setEnabled(list.isEnabled());
setFont(list.getFont());
return this;
}
protected String getItemDisplayText(ItemType item) {
if (this.itemRenderer == null) {
return (item == null) ? null : item.toString();
}
return this.itemRenderer.getItemDisplayText(item);
}
}
| 2,016 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/AbstractTimerRunnable.java | package org.esa.snap.ui.loading;
import javax.swing.SwingUtilities;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Created by jcoravu on 31/12/2018.
*/
public abstract class AbstractTimerRunnable<OutputType> implements Runnable {
private static final Logger logger = Logger.getLogger(AbstractTimerRunnable.class.getName());
private final Timer timer;
private final int timerDelayInMilliseconds;
private final int threadId;
private final LoadingIndicator loadingIndicator;
protected AbstractTimerRunnable(LoadingIndicator loadingIndicator, int threadId, int timerDelayInMilliseconds) {
this.loadingIndicator = loadingIndicator;
this.threadId = threadId;
this.timerDelayInMilliseconds = timerDelayInMilliseconds;
this.timer = (this.timerDelayInMilliseconds > 0) ? new Timer() : null;
}
protected abstract OutputType execute() throws Exception;
protected abstract String getExceptionLoggingMessage();
@Override
public final void run() {
try {
OutputType result = execute();
GenericRunnable<OutputType> runnable = new GenericRunnable<OutputType>(result) {
@Override
protected void execute(OutputType item) {
if (loadingIndicator.onHide(threadId)) {
onSuccessfullyFinish(item);
}
}
};
SwingUtilities.invokeLater(runnable);
} catch (Exception exception) {
logger.log(Level.SEVERE, getExceptionLoggingMessage(), exception);
GenericRunnable<Exception> runnable = new GenericRunnable<Exception>(exception) {
@Override
protected void execute(Exception threadException) {
if (loadingIndicator.onHide(threadId)) {
onFailed(threadException);
}
}
};
SwingUtilities.invokeLater(runnable);
} finally {
stopTimer();
}
}
protected void onFailed(Exception exception) {
}
protected void onSuccessfullyFinish(OutputType result) {
}
public final void executeAsync() {
startTimerIfDefined();
Thread thread = new Thread(this);
thread.start(); // start the thread
}
private void startTimerIfDefined() {
if (this.timerDelayInMilliseconds > 0) {
TimerTask timerTask = new TimerTask() {
@Override
public void run() {
if (isRunning()) {
timerWakeUp();
}
}
};
this.timer.schedule(timerTask, this.timerDelayInMilliseconds);
}
}
protected void onTimerWakeUp(String messageToDisplay) {
onDisplayLoadingIndicatorMessage(messageToDisplay);
}
protected final boolean onDisplayLoadingIndicatorMessage(String messageToDisplay) {
return this.loadingIndicator.onDisplay(this.threadId, messageToDisplay);
}
protected final boolean isRunning() {
return this.loadingIndicator.isRunning(this.threadId);
}
private void stopTimer() {
if (this.timer != null) {
this.timer.cancel();
}
}
private void timerWakeUp() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
onTimerWakeUp(null);
}
});
}
}
| 3,595 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ItemRenderer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/ItemRenderer.java | package org.esa.snap.ui.loading;
/**
* Created by jcoravu on 7/2/2020.
*/
public interface ItemRenderer<ItemType> {
public String getItemDisplayText(ItemType item);
}
| 175 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MessageDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/MessageDialog.java | package org.esa.snap.ui.loading;
/**
* Created by jcoravu on 7/1/2019.
*/
public interface MessageDialog {
public void close();
public void showErrorDialog(String errorMessage);
public void showErrorDialog(String message, String title);
public void showInformationDialog(String infoMessage);
public void showInformationDialog(String infoMessage, String title);
}
| 391 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CircularProgressPainter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/CircularProgressPainter.java | package org.esa.snap.ui.loading;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
/**
* Created by jcoravu on 28/12/2018.
*/
public class CircularProgressPainter {
private final Color baseColor;
private final Color highlightColor;
private final int trailLength;
private final int points;
private final float barWidth;
private final float barLength;
private final float centerDistance;
private int frame;
public CircularProgressPainter(Color baseColor, Color highlightColor) {
this.baseColor = baseColor;
this.highlightColor = highlightColor;
this.frame = -1;
this.points = 8;
this.barWidth = 4;
this.barLength = 10;
this.centerDistance = 7;
this.trailLength = 3;
}
protected void doPaint(Graphics2D graphics, int width, int height) {
RoundRectangle2D rect = new RoundRectangle2D.Float(this.centerDistance, -this.barWidth / 2, this.barLength, this.barWidth, this.barWidth, this.barWidth);
graphics.setColor(Color.GRAY);
graphics.translate(width / 2, height / 2);
for (int i = 0; i < this.points; i++) {
graphics.setColor(computeFrameColor(i));
graphics.fill(rect);
graphics.rotate(Math.PI * 2.0 / (double) this.points); // rotate clockwise direction
}
}
public int getPoints() {
return points;
}
public Dimension getPreferredSize() {
int size = (int) (2 * (this.centerDistance + this.barLength)) + 5;
return new Dimension(size, size);
}
public void setFrame(int frame) {
this.frame = frame;
}
private Color computeFrameColor(int index) {
if (this.frame == -1) {
return this.baseColor;
}
for (int i = 0; i < this.trailLength; i++) {
if (index == (this.frame - i + this.points) % this.points) {
float terp = 1.0f - ((float) (this.trailLength - i)) / (float) this.trailLength;
return interpolate(this.baseColor, this.highlightColor, terp);
}
}
return this.baseColor;
}
private static Color interpolate(Color color1, Color color2, float factor) {
float[] componentsClolor1 = color1.getRGBComponents(null);
float[] componentsClolor2 = color2.getRGBComponents(null);
float[] componentsNewColor = new float[4];
for (int i = 0; i < 4; i++) {
componentsNewColor[i] = componentsClolor2[i] + (componentsClolor1[i] - componentsClolor2[i]) * factor;
}
return new Color(componentsNewColor[0], componentsNewColor[1], componentsNewColor[2], componentsNewColor[3]);
}
} | 2,703 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CustomSplitPane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/loading/CustomSplitPane.java | package org.esa.snap.ui.loading;
import javax.swing.BorderFactory;
import javax.swing.JSplitPane;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.plaf.basic.BasicSplitPaneDivider;
import javax.swing.plaf.basic.BasicSplitPaneUI;
import java.awt.Color;
import java.awt.Graphics;
/**
* Created by jcoravu on 20/8/2019.
*/
public class CustomSplitPane extends JSplitPane {
private final int visibleDividerSize;
private final int dividerMargins;
private final Color dividerColor;
private float initialDividerLocationPercent;
public CustomSplitPane(int newOrientation, int visibleDividerSize, int dividerMargins, float initialDividerLocationPercent) {
this(newOrientation, visibleDividerSize, dividerMargins, initialDividerLocationPercent, UIManager.getColor("controlShadow"));
}
public CustomSplitPane(int newOrientation, int visibleDividerSize, int dividerMargins, float initialDividerLocationPercent, Color dividerColor) {
super(newOrientation);
if (visibleDividerSize < 0) {
throw new IllegalArgumentException("The visible divider size " + visibleDividerSize + " must be >= 0.");
}
if (dividerMargins < 0) {
throw new IllegalArgumentException("The divider margins " + dividerMargins + " must be >= 0.");
}
if (initialDividerLocationPercent < 0.0f || initialDividerLocationPercent > 1.0f) {
throw new IllegalArgumentException("The initial divider location percent " + initialDividerLocationPercent + " must be between 0.0 and 1.0.");
}
this.visibleDividerSize = visibleDividerSize;
this.dividerMargins = dividerMargins;
this.dividerColor = dividerColor;
this.initialDividerLocationPercent = initialDividerLocationPercent;
super.setDividerSize((2*this.dividerMargins) + this.visibleDividerSize);
setContinuousLayout(true);
setBorder(BorderFactory.createEmptyBorder());
}
@Override
public void setDividerSize(int newSize) {
// do nothing
}
@Override
public void updateUI() {
setUI(new CustomSplitPaneDividerUI());
revalidate();
}
@Override
public void doLayout() {
super.doLayout();
int availableWidth = getSize().width;
if (availableWidth > 0 && this.initialDividerLocationPercent > 0.0f) {
int dividerLocation = (int)(this.initialDividerLocationPercent * availableWidth);
setDividerLocation(dividerLocation);
this.initialDividerLocationPercent = 0.0f; // reset the divider
}
}
private class CustomSplitPaneDividerUI extends BasicSplitPaneUI {
private CustomSplitPaneDividerUI() {
}
@Override
public BasicSplitPaneDivider createDefaultDivider() {
return new CustomSplitPaneDivider(this);
}
}
private class CustomSplitPaneDivider extends BasicSplitPaneDivider {
private CustomSplitPaneDivider(BasicSplitPaneUI ui) {
super(ui);
super.setBorder(BorderFactory.createEmptyBorder());
setBackground(CustomSplitPane.this.dividerColor);
}
@Override
public void setBorder(Border border) {
// do nothing
}
@Override
public void paint(Graphics graphics) {
graphics.setColor(getBackground());
if (this.orientation == HORIZONTAL_SPLIT) {
graphics.fillRect(CustomSplitPane.this.dividerMargins, 0, CustomSplitPane.this.visibleDividerSize, getHeight());
} else {
graphics.fillRect(0, CustomSplitPane.this.dividerMargins, getWidth(), CustomSplitPane.this.visibleDividerSize);
}
}
}
}
| 3,796 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.