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 |
---|---|---|---|---|---|---|---|---|---|---|---|
ScanLocalRepositoryOptionsDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/ScanLocalRepositoryOptionsDialog.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.ui.loading.AbstractModalDialog;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* The dialog window to allow the user to select the options for scanning a local repository.
*
* Created by jcoravu on 20/7/2020.
*/
public class ScanLocalRepositoryOptionsDialog extends AbstractModalDialog {
private JCheckBox scanFolderRecursivelyCheckBox;
private JCheckBox generateQuickLookImagesCheckBox;
private JCheckBox testZipFilesForErrorsCheckBox;
public ScanLocalRepositoryOptionsDialog(Window parent) {
super(parent, "Scan folder options", true, null);
}
@Override
protected void onAboutToShow() {
JDialog dialog = getJDialog();
Dimension dialogSize = dialog.getSize();
dialogSize.width = (int)(1.5f * dialogSize.width);
dialog.setSize(dialogSize);
}
@Override
protected JPanel buildContentPanel(int gapBetweenColumns, int gapBetweenRows) {
this.scanFolderRecursivelyCheckBox = new JCheckBox("Search folder recursively");
this.generateQuickLookImagesCheckBox = new JCheckBox("Generate quick look images");
this.testZipFilesForErrorsCheckBox = new JCheckBox("Test zip files for errors");
JPanel contentPanel = new JPanel(new GridBagLayout());
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, 0);
contentPanel.add(this.scanFolderRecursivelyCheckBox, c);
c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
contentPanel.add(this.generateQuickLookImagesCheckBox, c);
c = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
contentPanel.add(this.testZipFilesForErrorsCheckBox, c);
c = SwingUtils.buildConstraints(0, 3, GridBagConstraints.BOTH, GridBagConstraints.WEST, 1, 1, 0, 0);
contentPanel.add(new JLabel(), c);
return contentPanel;
}
@Override
protected JPanel buildButtonsPanel(ActionListener cancelActionListener) {
ActionListener okActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
okButtonPressed(scanFolderRecursivelyCheckBox.isSelected(), generateQuickLookImagesCheckBox.isSelected(), testZipFilesForErrorsCheckBox.isSelected());
}
};
return buildButtonsPanel("Ok", okActionListener, "Cancel", cancelActionListener);
}
protected void okButtonPressed(boolean scanRecursively, boolean generateQuickLookImages, boolean testZipFileForErrors) {
getJDialog().dispose();
}
}
| 2,905 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
OpenLocalProductsRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/OpenLocalProductsRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.core.dataio.ProductIO;
import org.esa.snap.core.dataio.ProductReader;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryProduct;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.AppContext;
import org.esa.snap.ui.loading.PairRunnable;
import javax.swing.*;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to open in the application a list with local products.
*
* Created by jcoravu on 27/9/2019.
*/
public class OpenLocalProductsRunnable extends AbstractProcessLocalProductsRunnable {
private static final Logger logger = Logger.getLogger(OpenLocalProductsRunnable.class.getName());
private final AppContext appContext;
public OpenLocalProductsRunnable(ProgressBarHelper progressPanel, int threadId, RepositoryOutputProductListPanel repositoryProductListPanel,
AppContext appContext, List<RepositoryProduct> productsToOpen) {
super(progressPanel, threadId, repositoryProductListPanel, productsToOpen);
this.appContext = appContext;
}
@Override
protected boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp("Open local products...");
}
@Override
protected Void execute() throws Exception {
for (int i = 0; i<this.productsToProcess.size(); i++) {
LocalRepositoryProduct repositoryProduct = (LocalRepositoryProduct)this.productsToProcess.get(i);
try {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.OPENING);
// check if the local product exists on the disk
if (Files.exists(repositoryProduct.getPath())) {
// the product exists on the local disk
//TODO Jean temporary method until the Landsat8 product reader will be changed to read the product from a folder
Path productPath = RemoteProductsRepositoryProvider.prepareProductPathToOpen(repositoryProduct.getPath(), repositoryProduct);
File productFile = productPath.toFile();
//TODO Jean old code to get the product path to open
//File productFile = repositoryProduct.getPath().toFile();
ProductReader productReader = ProductIO.getProductReaderForInput(productFile);
if (productReader == null) {
// no product reader found in the application
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_OPENED_MISSING_PRODUCT_READER);
} else {
// there is a product reader in the application
Product product = productReader.readProductNodes(productFile, null);
if (product == null) {
// the product has not been read
throw new NullPointerException("The product '" + repositoryProduct.getName()+"' has not been read from '" + productFile.getAbsolutePath()+"'.");
} else {
// open the product in the application
Runnable runnable = new PairRunnable<LocalRepositoryProduct, Product>(repositoryProduct, product) {
@Override
protected void execute(LocalRepositoryProduct localRepositoryProduct, Product productToOpen) {
appContext.getProductManager().addProduct(productToOpen); // open the product in the application
updateProductProgressStatusLater(localRepositoryProduct, LocalProgressStatus.OPENED);
}
};
SwingUtilities.invokeLater(runnable);
}
}
} else {
// the product does not exist into the local repository folder
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.MISSING_PRODUCT_FROM_REPOSITORY);
}
} catch (Exception exception) {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_OPENED);
logger.log(Level.SEVERE, "Failed to open the local product '" + repositoryProduct.getURL() + "'.", exception);
}
}
return null;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to open the local products.";
}
}
| 5,113 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LoadProductListTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/LoadProductListTimerRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.download.DownloadProductListTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ThreadListener;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryFolder;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to search the products in the local repository.
*
* Created by jcoravu on 5/9/2019.
*/
public class LoadProductListTimerRunnable extends AbstractProgressTimerRunnable<List<RepositoryProduct>> {
private static final Logger logger = Logger.getLogger(LoadProductListTimerRunnable.class.getName());
private final ThreadListener threadListener;
private final LocalRepositoryFolder localRepositoryFolder;
private final RepositoryOutputProductListPanel repositoryProductListPanel;
private final String remoteMissionName;
private final Map<String, Object> parameterValues;
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
public LoadProductListTimerRunnable(ProgressBarHelper progressPanel, int threadId, ThreadListener threadListener, LocalRepositoryFolder localRepositoryFolder,
String remoteMissionName, Map<String, Object> parameterValues, RepositoryOutputProductListPanel repositoryProductListPanel,
AllLocalFolderProductsRepository allLocalFolderProductsRepository) {
super(progressPanel, threadId, 500);
this.threadListener = threadListener;
this.localRepositoryFolder = localRepositoryFolder;
this.repositoryProductListPanel = repositoryProductListPanel;
this.remoteMissionName = remoteMissionName;
this.parameterValues = parameterValues;
this.allLocalFolderProductsRepository = allLocalFolderProductsRepository;
}
@Override
public void cancelRunning() {
if (logger.isLoggable(Level.FINE)) {
logger.log(Level.FINE, "Cancel searching the product list on the local repository.");
}
super.cancelRunning();
}
@Override
protected List<RepositoryProduct> execute() throws Exception {
return this.allLocalFolderProductsRepository.loadProductList(this.localRepositoryFolder, this.remoteMissionName, this.parameterValues);
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to read the product list from the database.";
}
@Override
protected void onFinishRunning() {
this.threadListener.onStopExecuting(this);
}
@Override
protected void onSuccessfullyFinish(List<RepositoryProduct> results) {
this.repositoryProductListPanel.setProducts(results);
}
@Override
protected void onFailed(Exception exception) {
onShowErrorMessageDialog(this.repositoryProductListPanel, "Failed to read the product list from the database.", "Error");
}
}
| 3,441 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
CopyLocalProductsRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/CopyLocalProductsRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.engine_utilities.util.FileIOUtils;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryProduct;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.ui.AppContext;
import java.nio.file.Path;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The thread to copy local products from one local repository to other local repository.
*
* Created by jcoravu on 27/9/2019.
*/
public class CopyLocalProductsRunnable extends AbstractProcessLocalProductsRunnable {
private static final Logger logger = Logger.getLogger(CopyLocalProductsRunnable.class.getName());
private final Path localTargetFolder;
public CopyLocalProductsRunnable(ProgressBarHelper progressPanel, int threadId, RepositoryOutputProductListPanel repositoryProductListPanel, Path localTargetFolder, List<RepositoryProduct> productsToCopy) {
super(progressPanel, threadId, repositoryProductListPanel, productsToCopy);
this.localTargetFolder = localTargetFolder;
}
@Override
protected boolean onTimerWakeUp(String message) {
return super.onTimerWakeUp("Copy local products...");
}
@Override
protected Void execute() throws Exception {
for (int i = 0; i<this.productsToProcess.size(); i++) {
LocalRepositoryProduct repositoryProduct = (LocalRepositoryProduct)this.productsToProcess.get(i);
try {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.COPYING);
FileIOUtils.copyFolderNew(repositoryProduct.getPath(), this.localTargetFolder);
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.COPIED);
} catch (Exception exception) {
updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_COPIED);
logger.log(Level.SEVERE, "Failed to copy the local product '" + repositoryProduct.getPath() + "'.", exception);
}
}
return null;
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to copy the local products.";
}
}
| 2,437 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AllLocalProductsRepositoryPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/AllLocalProductsRepositoryPanel.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.apache.commons.lang3.StringUtils;
import org.esa.snap.product.library.ui.v2.ComponentDimension;
import org.esa.snap.product.library.ui.v2.RepositoryProductPanelBackground;
import org.esa.snap.product.library.ui.v2.repository.AbstractProductsRepositoryPanel;
import org.esa.snap.product.library.ui.v2.repository.AbstractRepositoryProductPanel;
import org.esa.snap.product.library.ui.v2.repository.input.AbstractParameterComponent;
import org.esa.snap.product.library.ui.v2.repository.input.ParametersPanel;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.repository.remote.RemoteRepositoriesSemaphore;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.product.library.ui.v2.thread.ThreadListener;
import org.esa.snap.worldwind.productlibrary.WorldMapPanelWrapper;
import org.esa.snap.product.library.v2.database.AllLocalFolderProductsRepository;
import org.esa.snap.product.library.v2.database.AttributeFilter;
import org.esa.snap.product.library.v2.database.LocalRepositoryParameterValues;
import org.esa.snap.product.library.v2.database.model.LocalRepositoryFolder;
import org.esa.snap.remote.products.repository.Attribute;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import org.esa.snap.remote.products.repository.RepositoryQueryParameter;
import org.esa.snap.ui.loading.CustomComboBox;
import org.esa.snap.ui.loading.ItemRenderer;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.ComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
/**
* The panel containing the query parameters of a local repository.
* Created by jcoravu on 5/8/2019.
*/
public class AllLocalProductsRepositoryPanel extends AbstractProductsRepositoryPanel {
private final AllLocalFolderProductsRepository allLocalFolderProductsRepository;
private final JComboBox<LocalRepositoryFolder> foldersComboBox;
private final JComboBox<String> remoteMissionsComboBox;
private final JComboBox<String> attributesComboBox;
private final JComboBox<String> attributeValuesEditableComboBox;
private final JButton scanFoldersButton;
private final JButton addFolderButton;
private final JButton removeFoldersButton;
private LocalInputParameterValues localInputParameterValues;
public AllLocalProductsRepositoryPanel(ComponentDimension componentDimension, WorldMapPanelWrapper worlWindPanel) {
super(worlWindPanel, componentDimension, new BorderLayout(0, componentDimension.getGapBetweenRows()));
this.allLocalFolderProductsRepository = new AllLocalFolderProductsRepository();
Dimension buttonSize = new Dimension(componentDimension.getTextFieldPreferredHeight(), componentDimension.getTextFieldPreferredHeight());
ItemRenderer<LocalRepositoryFolder> foldersItemRenderer = item -> (item == null) ? " " : item.getPath().toString();
this.foldersComboBox = new CustomComboBox(foldersItemRenderer, componentDimension.getTextFieldPreferredHeight(), false, componentDimension.getTextFieldBackgroundColor());
ItemRenderer<String> missionsItemRenderer = item -> (item == null) ? " " : item;
this.remoteMissionsComboBox = new CustomComboBox(missionsItemRenderer, componentDimension.getTextFieldPreferredHeight(), false, componentDimension.getTextFieldBackgroundColor());
this.attributesComboBox = SwingUtils.buildComboBox(null, null, componentDimension.getTextFieldPreferredHeight(), false);
this.attributesComboBox.setBackground(componentDimension.getTextFieldBackgroundColor());
this.addFolderButton = SwingUtils.buildButton("/org/esa/snap/resources/images/icons/Add16.png", null, buttonSize, 1);
this.addFolderButton.setToolTipText("Add new local folder");
this.scanFoldersButton = SwingUtils.buildButton("/org/esa/snap/product/library/ui/v2/icons/refresh24.png", null, buttonSize, 1);
this.scanFoldersButton.setToolTipText("Scan all local folders");
this.removeFoldersButton = SwingUtils.buildButton("/org/esa/snap/resources/images/icons/Remove16.png", null, buttonSize, 1);
this.removeFoldersButton.setToolTipText("Remove local folder(s)");
ItemRenderer<String> attributeValuesItemRenderer = item -> (item == null) ? " " : item;
this.attributeValuesEditableComboBox = new CustomComboBox(attributeValuesItemRenderer, componentDimension.getTextFieldPreferredHeight(), true, componentDimension.getTextFieldBackgroundColor());
this.attributeValuesEditableComboBox.addItem(null);
}
@Override
public String getRepositoryName() {
return "All Local Folders";
}
private static Comparator<String> buildAttributeNamesComparator() {
return String::compareToIgnoreCase;
}
@Override
protected ParametersPanel getInputParameterComponentsPanel() {
ParametersPanel panel = new ParametersPanel();
int gapBetweenColumns = this.componentDimension.getGapBetweenColumns();
int gapBetweenRows = this.componentDimension.getGapBetweenRows();
GridBagConstraints c = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, 0, 0);
panel.add(new JLabel("Folder"), c);
c = SwingUtils.buildConstraints(1, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, 0, gapBetweenColumns);
panel.add(this.foldersComboBox, c);
c = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0);
panel.add(new JLabel("Mission"), c);
c = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
panel.add(this.remoteMissionsComboBox, c);
Class<?> areaOfInterestClass = Rectangle2D.class;
Class<?> attributesClass = Attribute.class;
Class<?>[] classesToIgnore = new Class<?>[]{areaOfInterestClass, attributesClass};
List<RepositoryQueryParameter> parameters = this.allLocalFolderProductsRepository.getParameters();
int startRowIndex = 2;
this.parameterComponents = panel.addParameterComponents(parameters, startRowIndex, gapBetweenRows, this.componentDimension, classesToIgnore);
RepositoryQueryParameter attributesParameter = null;
for (RepositoryQueryParameter param : parameters) {
if (param.getType() == attributesClass) {
attributesParameter = param;
}
}
this.attributesComboBox.setSelectedItem(null); // reset the selected attribute name when refreshing the parent panel
this.attributeValuesEditableComboBox.setSelectedItem(null); // reset the selected attribute value when refreshing the parent panel
if (attributesParameter != null) {
int nextRowIndex = startRowIndex + this.parameterComponents.size() + 1;
AttributesParameterComponent attributesParameterComponent = new AttributesParameterComponent(this.attributesComboBox, this.attributeValuesEditableComboBox,
attributesParameter.getName(), attributesParameter.getLabel(),
attributesParameter.isRequired(), this.componentDimension);
this.parameterComponents.add(attributesParameterComponent);
int difference = this.componentDimension.getTextFieldPreferredHeight() - attributesParameterComponent.getLabel().getPreferredSize().height;
c = SwingUtils.buildConstraints(0, nextRowIndex, GridBagConstraints.NONE, GridBagConstraints.NORTHWEST, 1, 1, gapBetweenRows + (difference / 2), 0);
panel.add(attributesParameterComponent.getLabel(), c);
c = SwingUtils.buildConstraints(1, nextRowIndex, GridBagConstraints.BOTH, GridBagConstraints.WEST, 1, 1, gapBetweenRows, gapBetweenColumns);
panel.add(attributesParameterComponent.getComponent(), c);
}
return panel;
}
@Override
public AbstractProgressTimerRunnable<List<RepositoryProduct>> buildSearchProductListThread(ProgressBarHelper progressPanel, int threadId, ThreadListener threadListener,
RemoteRepositoriesSemaphore remoteRepositoriesSemaphore, RepositoryOutputProductListPanel repositoryProductListPanel) {
Map<String, Object> parameterValues = getParameterValues();
if (parameterValues != null) {
LocalRepositoryFolder localRepositoryFolder = (LocalRepositoryFolder)this.foldersComboBox.getSelectedItem();
String selectedMissionName = (String) this.remoteMissionsComboBox.getSelectedItem(); // the selected mission may be null
this.localInputParameterValues = new LocalInputParameterValues(parameterValues, selectedMissionName, localRepositoryFolder);
return new LoadProductListTimerRunnable(progressPanel, threadId, threadListener, localRepositoryFolder, selectedMissionName,
parameterValues, repositoryProductListPanel, this.allLocalFolderProductsRepository);
}
return null;
}
@Override
public AbstractRepositoryProductPanel buildProductProductPanel(RepositoryProductPanelBackground repositoryProductPanelBackground,
ComponentDimension componentDimension) {
return new LocalRepositoryProductPanel(repositoryProductPanelBackground, componentDimension);
}
@Override
public JButton[] getTopBarButton() {
return new JButton[]{this.scanFoldersButton, this.addFolderButton, this.removeFoldersButton};
}
@Override
public void resetInputParameterValues() {
this.localInputParameterValues = null;
}
@Override
public void clearInputParameterComponentValues() {
this.foldersComboBox.setSelectedItem(null);
this.remoteMissionsComboBox.setSelectedItem(null);
super.clearInputParameterComponentValues();
}
@Override
protected RepositoryQueryParameter getAreaOfInterestParameter(){
Class<?> areaOfInterestClass = Rectangle2D.class;
List<RepositoryQueryParameter> parameters = this.allLocalFolderProductsRepository.getParameters();
RepositoryQueryParameter areaOfInterestParameter = null;
for (RepositoryQueryParameter param : parameters) {
if (param.getType() == areaOfInterestClass) {
areaOfInterestParameter = param;
}
}
return areaOfInterestParameter;
}
public void updateInputParameterValues(Path localRepositoryFolderPath, LocalDateTime startDate, LocalDateTime endDate, Rectangle2D.Double areaOfInterestToSelect, List<AttributeFilter> attributes) {
LocalRepositoryFolder localRepositoryFolderToSelect = null;
int size = this.foldersComboBox.getModel().getSize();
for (int i=0; i<size && localRepositoryFolderToSelect == null; i++) {
LocalRepositoryFolder localRepositoryFolder = this.foldersComboBox.getModel().getElementAt(i);
if (localRepositoryFolder != null && localRepositoryFolder.getPath().equals(localRepositoryFolderPath)) {
localRepositoryFolderToSelect = localRepositoryFolder;
}
}
updateInputParameterValues(localRepositoryFolderToSelect, null, startDate, endDate, areaOfInterestToSelect, attributes);
}
@Override
public boolean refreshInputParameterComponentValues() {
if (this.localInputParameterValues != null) {
this.foldersComboBox.setSelectedItem(this.localInputParameterValues.getLocalRepositoryFolder());
this.remoteMissionsComboBox.setSelectedItem(this.localInputParameterValues.getMissionName());
for (AbstractParameterComponent<?> inputParameterComponent : this.parameterComponents) {
Object parameterValue = this.localInputParameterValues.getParameterValue(inputParameterComponent.getParameterName());
inputParameterComponent.setParameterValue(parameterValue);
}
return true;
}
return false;
}
public AllLocalFolderProductsRepository getAllLocalFolderProductsRepository() {
return allLocalFolderProductsRepository;
}
public void deleteLocalRepositoryFolder(LocalRepositoryFolder localRepositoryFolderToRemove) {
ComboBoxModel<LocalRepositoryFolder> foldersModel = this.foldersComboBox.getModel();
for (int i = 0; i < foldersModel.getSize(); i++) {
LocalRepositoryFolder existingFolder = foldersModel.getElementAt(i);
if (existingFolder != null && existingFolder.getId() == localRepositoryFolderToRemove.getId()) {
this.foldersComboBox.removeItemAt(i);
break;
}
}
if (foldersModel.getSize() == 1 && foldersModel.getElementAt(0) == null) {
this.foldersComboBox.removeItemAt(0);
}
}
public void setTopBarButtonListeners(ActionListener scanRepositoryFoldersListener, ActionListener addRepositoryFoldersListener, ActionListener deleteRepositoryFoldersListener) {
this.scanFoldersButton.addActionListener(scanRepositoryFoldersListener);
this.addFolderButton.addActionListener(addRepositoryFoldersListener);
this.removeFoldersButton.addActionListener(deleteRepositoryFoldersListener);
}
public void addMissionIfMissing(String mission) {
ComboBoxModel<String> missionsModel = this.remoteMissionsComboBox.getModel();
boolean foundMission = false;
for (int i = 0; i < missionsModel.getSize() && !foundMission; i++) {
String existingMission = missionsModel.getElementAt(i);
if (existingMission != null && existingMission.equalsIgnoreCase(mission)) {
foundMission = true;
}
}
if (!foundMission) {
if (missionsModel.getSize() == 0) {
this.remoteMissionsComboBox.addItem(null);
}
this.remoteMissionsComboBox.addItem(mission);
}
}
public void addLocalRepositoryFolderIfMissing(LocalRepositoryFolder localRepositoryFolder) {
ComboBoxModel<LocalRepositoryFolder> foldersModel = this.foldersComboBox.getModel();
boolean foundFolder = false;
for (int i = 0; i < foldersModel.getSize() && !foundFolder; i++) {
LocalRepositoryFolder existingFolder = foldersModel.getElementAt(i);
if (existingFolder != null && existingFolder.getId() == localRepositoryFolder.getId()) {
foundFolder = true;
}
}
if (!foundFolder) {
if (foldersModel.getSize() == 0) {
this.foldersComboBox.addItem(null);
}
this.foldersComboBox.addItem(localRepositoryFolder);
}
}
public List<LocalRepositoryFolder> getLocalRepositoryFolders() {
ComboBoxModel<LocalRepositoryFolder> foldersModel = this.foldersComboBox.getModel();
List<LocalRepositoryFolder> result = new ArrayList<>(foldersModel.getSize());
for (int i = 0; i < foldersModel.getSize(); i++) {
LocalRepositoryFolder existingFolder = foldersModel.getElementAt(i);
if (existingFolder != null) {
result.add(existingFolder);
}
}
return result;
}
public LocalRepositoryFolder getSelectedFolder() {
return (LocalRepositoryFolder) this.foldersComboBox.getSelectedItem();
}
public void updateInputParameterValues(LocalRepositoryFolder localRepositoryFolder, String remoteMission, LocalDateTime startDate, LocalDateTime endDate,
Rectangle2D.Double areaOfInterestToSelect, List<AttributeFilter> attributes) {
this.foldersComboBox.setSelectedItem(localRepositoryFolder);
this.remoteMissionsComboBox.setSelectedItem(remoteMission);
for (AbstractParameterComponent<?> inputParameterComponent : this.parameterComponents) {
switch (inputParameterComponent.getParameterName()) {
case AllLocalFolderProductsRepository.FOOT_PRINT_PARAMETER:
inputParameterComponent.setParameterValue(areaOfInterestToSelect);
break;
case AllLocalFolderProductsRepository.START_DATE_PARAMETER:
inputParameterComponent.setParameterValue(startDate);
break;
case AllLocalFolderProductsRepository.END_DATE_PARAMETER:
inputParameterComponent.setParameterValue(endDate);
break;
case AllLocalFolderProductsRepository.ATTRIBUTES_PARAMETER:
inputParameterComponent.setParameterValue(attributes);
break;
default:
inputParameterComponent.setParameterValue(null); // clear the value
break;
}
}
}
private void setAttributes(SortedSet<String> uniqueAttributeNames) {
this.attributesComboBox.removeAllItems();
// add an empty attribute on the first position
this.attributesComboBox.addItem(null);
for (String attributeName : uniqueAttributeNames) {
this.attributesComboBox.addItem(attributeName);
}
}
public void setLocalParameterValues(LocalRepositoryParameterValues localRepositoryParameterValues) {
List<LocalRepositoryFolder> localRepositoryFolders = null;
List<String> remoteMissionNames = null;
Map<Short, Set<String>> attributeNamesPerMission = null;
Set<String> localAttributeNames = null;
if (localRepositoryParameterValues != null) {
localRepositoryFolders = localRepositoryParameterValues.getLocalRepositoryFolders();
remoteMissionNames = localRepositoryParameterValues.getRemoteMissionNames();
attributeNamesPerMission = localRepositoryParameterValues.getRemoteAttributeNamesPerMission();
localAttributeNames = localRepositoryParameterValues.getLocalAttributeNames();
}
this.foldersComboBox.removeAllItems();
if (localRepositoryFolders != null && localRepositoryFolders.size() > 0) {
this.foldersComboBox.addItem(null);
for (LocalRepositoryFolder localRepositoryFolder : localRepositoryFolders) {
this.foldersComboBox.addItem(localRepositoryFolder);
}
this.foldersComboBox.setSelectedItem(null);
}
this.remoteMissionsComboBox.removeAllItems();
if (remoteMissionNames != null && remoteMissionNames.size() > 0) {
this.remoteMissionsComboBox.addItem(null);
for (String remoteMissionName : remoteMissionNames) {
this.remoteMissionsComboBox.addItem(remoteMissionName);
}
this.remoteMissionsComboBox.setSelectedItem(null);
}
Comparator<String> comparator = buildAttributeNamesComparator();
SortedSet<String> uniqueAttributeNames = new TreeSet<>(comparator);
if (attributeNamesPerMission != null && attributeNamesPerMission.size() > 0) {
for (Map.Entry<Short, Set<String>> entry : attributeNamesPerMission.entrySet()) {
uniqueAttributeNames.addAll(entry.getValue());
}
}
if (localAttributeNames != null && localAttributeNames.size() > 0) {
uniqueAttributeNames.addAll(localAttributeNames);
}
if (uniqueAttributeNames.size() > 0) {
setAttributes(uniqueAttributeNames);
this.attributesComboBox.setSelectedItem(null);
} else {
this.attributesComboBox.removeAllItems();
}
}
public void addAttributesIfMissing(RepositoryProduct repositoryProduct) {
Comparator<String> comparator = buildAttributeNamesComparator();
SortedSet<String> uniqueAttributes = new TreeSet<>(comparator);
ComboBoxModel<String> attributesModel = this.attributesComboBox.getModel();
for (int i = 0; i < attributesModel.getSize(); i++) {
String existingAtributeName = attributesModel.getElementAt(i);
if (!StringUtils.isBlank(existingAtributeName)) {
uniqueAttributes.add(existingAtributeName);
}
}
boolean newAttribute = false;
List<Attribute> remoteAttributes = repositoryProduct.getRemoteAttributes();
if (remoteAttributes != null) {
for (Attribute attribute : remoteAttributes) {
if (uniqueAttributes.add(attribute.getName())) {
newAttribute = true;
}
}
}
List<Attribute> localAttributes = repositoryProduct.getLocalAttributes();
if (localAttributes != null) {
for (Attribute attribute : localAttributes) {
if (uniqueAttributes.add(attribute.getName())) {
newAttribute = true;
}
}
}
if (newAttribute) {
int oldSize = attributesModel.getSize();
setAttributes(uniqueAttributes);
if (oldSize == 0) {
// reset the first selected attribute name
this.attributesComboBox.setSelectedItem(null);
}
}
}
}
| 22,236 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractProcessLocalProductsRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/AbstractProcessLocalProductsRunnable.java | package org.esa.snap.product.library.ui.v2.repository.local;
import org.esa.snap.product.library.ui.v2.repository.output.OutputProductListModel;
import org.esa.snap.product.library.ui.v2.repository.output.RepositoryOutputProductListPanel;
import org.esa.snap.product.library.ui.v2.thread.AbstractProgressTimerRunnable;
import org.esa.snap.product.library.ui.v2.thread.ProgressBarHelper;
import org.esa.snap.remote.products.repository.RepositoryProduct;
import javax.swing.*;
import java.util.List;
/**
* The base thread to process the local products.
*
* Created by jcoravu on 27/9/2019.
*/
public abstract class AbstractProcessLocalProductsRunnable extends AbstractProgressTimerRunnable<Void> {
protected final List<RepositoryProduct> productsToProcess;
protected final RepositoryOutputProductListPanel repositoryProductListPanel;
protected AbstractProcessLocalProductsRunnable(ProgressBarHelper progressPanel, int threadId, RepositoryOutputProductListPanel repositoryProductListPanel,
List<RepositoryProduct> productsToProcess) {
super(progressPanel, threadId, 500);
this.repositoryProductListPanel = repositoryProductListPanel;
this.productsToProcess = productsToProcess;
}
protected final void updateProductProgressStatusLater(RepositoryProduct repositoryProduct, byte localStatus) {
UpdateLocalProgressStatusRunnable runnable = new UpdateLocalProgressStatusRunnable(repositoryProduct, localStatus, this.repositoryProductListPanel);
SwingUtilities.invokeLater(runnable);
}
private static class UpdateLocalProgressStatusRunnable implements Runnable {
private final RepositoryProduct repositoryProduct;
private final byte localStatus;
private final RepositoryOutputProductListPanel repositoryProductListPanel;
private UpdateLocalProgressStatusRunnable(RepositoryProduct repositoryProduct, byte localStatus, RepositoryOutputProductListPanel repositoryProductListPanel) {
this.repositoryProduct = repositoryProduct;
this.localStatus = localStatus;
this.repositoryProductListPanel = repositoryProductListPanel;
}
@Override
public void run() {
OutputProductListModel productListModel = this.repositoryProductListPanel.getProductListPanel().getProductListModel();
productListModel.setLocalProductStatus(this.repositoryProduct, this.localStatus);
}
}
}
| 2,512 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
LocalProgressStatus.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/repository/local/LocalProgressStatus.java | package org.esa.snap.product.library.ui.v2.repository.local;
/**
* The status of a local repository product.
*
* Created by jcoravu on 27/9/2019.
*/
public class LocalProgressStatus {
public static final byte PENDING_OPEN = 1;
public static final byte OPENING = 2;
public static final byte OPENED = 3;
public static final byte FAIL_OPENED = 4;
public static final byte PENDING_DELETE = 5;
public static final byte DELETING = 6;
public static final byte DELETED = 7;
public static final byte FAIL_DELETED = 8;
public static final byte FAIL_OPENED_MISSING_PRODUCT_READER = 9;
public static final byte PENDING_COPY = 10;
public static final byte COPYING = 11;
public static final byte FAIL_COPIED = 12;
public static final byte COPIED = 13;
public static final byte PENDING_MOVE = 14;
public static final byte MOVING = 15;
public static final byte FAIL_MOVED = 16;
public static final byte MOVED = 17;
public static final byte MISSING_PRODUCT_FROM_REPOSITORY = 18;
private byte status;
public LocalProgressStatus(byte status) {
this.status = status;
}
public boolean isPendingOpen() {
return (this.status == PENDING_OPEN);
}
public boolean isOpened() {
return (this.status == OPENED);
}
public boolean isOpening() {
return (this.status == OPENING);
}
public boolean isFailOpened() {
return (this.status == FAIL_OPENED);
}
public boolean isFailOpenedBecauseNoProductReader() {
return (this.status == FAIL_OPENED_MISSING_PRODUCT_READER);
}
public byte getStatus() {
return status;
}
public void setStatus(byte status) {
this.status = status;
}
public boolean isPendingDelete() {
return (this.status == PENDING_DELETE);
}
public boolean isDeleting() {
return (this.status == DELETING);
}
public boolean isDeleted() {
return (this.status == DELETED);
}
public boolean isFailDeleted() {
return (this.status == FAIL_DELETED);
}
}
| 2,111 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositoriesCredentialsControllerUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/preferences/RepositoriesCredentialsControllerUI.java | package org.esa.snap.product.library.ui.v2.preferences;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.swing.binding.BindingContext;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsController;
import org.esa.snap.product.library.v2.preferences.RepositoriesCredentialsPersistence;
import org.esa.snap.product.library.v2.preferences.model.RemoteRepositoryCredentials;
import org.esa.snap.product.library.v2.preferences.model.RepositoriesCredentialsConfigurations;
import org.esa.snap.product.library.ui.v2.preferences.model.RepositoriesCredentialsTableModel;
import org.esa.snap.product.library.ui.v2.preferences.model.RepositoriesTableModel;
import org.esa.snap.rcp.SnapApp;
import org.esa.snap.rcp.preferences.DefaultConfigController;
import org.esa.snap.rcp.preferences.Preference;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import org.esa.snap.ui.AppContext;
import org.netbeans.spi.options.OptionsPanelController;
import org.openide.util.HelpCtx;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellEditor;
import java.awt.*;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A controller UI for Product Library Remote Repositories Credentials.
* Used for provide a UI to the strategy with storing Remote Repositories credentials data.
*
* @author Adrian Draghici
*/
@OptionsPanelController.SubRegistration(location = "GeneralPreferences",
displayName = "#Options_DisplayName_PLOptions",
keywords = "#Options_Keywords_PLOptions",
keywordsCategory = "Remote Data Sources",
id = "PL",
position = 12)
@org.openide.util.NbBundle.Messages({
"Options_DisplayName_PLOptions=Product Library",
"Options_Keywords_PLOptions=product library, remote, data, sources, credentials"
})
public class RepositoriesCredentialsControllerUI extends DefaultConfigController {
public static final String REMOTE_PRODUCTS_REPOSITORY_CREDENTIALS = "remoteProductsRepositoryCredentials";
private static Logger logger = Logger.getLogger(RepositoriesCredentialsControllerUI.class.getName());
private static ImageIcon addButtonIcon;
private static ImageIcon removeButtonIcon;
private static ImageIcon passwordSeeIcon;
static {
try {
addButtonIcon = loadImageIcon("/tango/16x16/actions/list-add.png");
removeButtonIcon = loadImageIcon("/tango/16x16/actions/list-remove.png");
passwordSeeIcon = loadImageIcon("/org/esa/snap/rcp/icons/quicklook16.png");
} catch (Exception ex) {
logger.log(Level.WARNING, "Unable to load image resource. Details: " + ex.getMessage());
}
}
private final JTable repositoriesListTable;
private final JTable credentialsListTable;
private final List<RemoteProductsRepositoryProvider> remoteRepositories = new ArrayList<>();
private JPanel credentialsListPanel;
private JRadioButton autoUncompressEnabled;
private JRadioButton downloadAllPagesEnabled;
private JComboBox<Integer> recordsOnPageCb;
private RepositoriesCredentialsBean repositoriesCredentialsBean = new RepositoriesCredentialsBean();
private List<RemoteRepositoryCredentials> repositoriesCredentials;
private boolean autoUncompress;
private boolean downloadAllPages;
private int nrRecordsOnPage;
private boolean isInitialized = false;
private int currentSelectedRow = -1;
public RepositoriesCredentialsControllerUI() {
RepositoriesCredentialsController repositoriesCredentialsController = RepositoriesCredentialsController.getInstance();
this.repositoriesCredentials = createCopy(repositoriesCredentialsController.getRepositoriesCredentials());
this.autoUncompress = repositoriesCredentialsController.isAutoUncompress();
this.downloadAllPages = repositoriesCredentialsController.downloadsAllPages();
this.nrRecordsOnPage = repositoriesCredentialsController.getNrRecordsOnPage();
loadRemoteRepositories();
repositoriesListTable = buildRepositoriesListTable();
credentialsListTable = buildCredentialsListTable();
}
public static ImageIcon getPasswordSeeIcon() {
return passwordSeeIcon;
}
private static ImageIcon loadImageIcon(String imagePath) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL imageURL = classLoader.getResource(imagePath);
return (imageURL == null) ? null : new ImageIcon(imageURL);
}
private static List<RemoteRepositoryCredentials> createCopy(List<RemoteRepositoryCredentials> repositoriesCredentialsSource) {
List<RemoteRepositoryCredentials> repositoriesCredentialsCopy = new ArrayList<>();
for (RemoteRepositoryCredentials repositoryCredentialsSource : repositoriesCredentialsSource) {
List<Credentials> credentialsCopy = new ArrayList<>();
for (Credentials credentialsSource : repositoryCredentialsSource.getCredentialsList()) {
UsernamePasswordCredentials repositoryCredential = new UsernamePasswordCredentials(credentialsSource.getUserPrincipal().getName(), credentialsSource.getPassword());
credentialsCopy.add(repositoryCredential);
}
repositoriesCredentialsCopy.add(new RemoteRepositoryCredentials(repositoryCredentialsSource.getRepositoryName(), credentialsCopy));
}
return repositoriesCredentialsCopy;
}
private static boolean isRepositoriesChanged(List<RemoteRepositoryCredentials> savedRepositoriesCredentials, List<RemoteRepositoryCredentials> repositoriesCredentials) {
if (repositoriesCredentials.size() != savedRepositoriesCredentials.size()) {
return true;
}
for (RemoteRepositoryCredentials repositoryCredentials : repositoriesCredentials) {
for (RemoteRepositoryCredentials savedRepositoryCredentials : savedRepositoriesCredentials) {
if (repositoryCredentials.getRepositoryName().contentEquals(savedRepositoryCredentials.getRepositoryName()) && isRepositoryChanged(savedRepositoryCredentials, repositoryCredentials)) {
return true;
}
}
}
return false;
}
private static boolean isRepositoryChanged(RemoteRepositoryCredentials savedRepositoryCredentials, RemoteRepositoryCredentials repositoryCredentials) {
List<Credentials> credentials = repositoryCredentials.getCredentialsList();
if (credentials.size() != savedRepositoryCredentials.getCredentialsList().size()) {
// some credentials deleted or added = changed
return true;
}
for (Credentials credential : credentials) {
if (!savedRepositoryCredentials.credentialExists(credential)) {
return true; // the credential was not found = changed
}
}
return false;
}
private void loadRemoteRepositories() {
RemoteProductsRepositoryProvider[] remoteRepositoryProductProviders = RemoteProductsRepositoryProvider.getRemoteProductsRepositoryProviders();
for (RemoteProductsRepositoryProvider remoteRepositoryProductProvider : remoteRepositoryProductProviders) {
if (remoteRepositoryProductProvider.requiresAuthentication()) {
this.remoteRepositories.add(remoteRepositoryProductProvider);
}
}
}
private List<RemoteRepositoryCredentials> getChangedRemoteRepositories() {
List<RemoteRepositoryCredentials> changedRepositoriesCredentials = new ArrayList<>();
RepositoriesTableModel repositoriesTableModel = (RepositoriesTableModel) this.repositoriesListTable.getModel();
RepositoriesCredentialsTableModel repositoriesCredentialsTableModel = (RepositoriesCredentialsTableModel) this.credentialsListTable.getModel();
String selectedRemoteRepositoryName = repositoriesTableModel.get(this.currentSelectedRow).getRepositoryName();
List<Credentials> selectedRepositoryCredentials = repositoriesCredentialsTableModel.fetchData();
RemoteRepositoryCredentials repositoryCredentialsFromTable = new RemoteRepositoryCredentials(selectedRemoteRepositoryName, selectedRepositoryCredentials);
for (RemoteRepositoryCredentials repositoryCredentials : this.repositoriesCredentials) {
if (!repositoryCredentials.getRepositoryName().contentEquals(repositoryCredentialsFromTable.getRepositoryName())) {
changedRepositoriesCredentials.add(repositoryCredentials);
}
}
if (!repositoryCredentialsFromTable.getCredentialsList().isEmpty()) {
changedRepositoriesCredentials.add(repositoryCredentialsFromTable);
}
return changedRepositoriesCredentials;
}
private boolean getChangedAutoUncompress() {
return autoUncompressEnabled.isSelected();
}
private boolean getChangedDownloadAllPagesEnabled() {
return downloadAllPagesEnabled.isSelected();
}
private int getChangedNrRecordsOnPage() {
return recordsOnPageCb.getItemAt(recordsOnPageCb.getSelectedIndex());
}
private List<Credentials> getRemoteRepositoryCredentials(String remoteRepositoryId) {
for (RemoteRepositoryCredentials repositoryCredentials : repositoriesCredentials) {
if (repositoryCredentials.getRepositoryName().contentEquals(remoteRepositoryId)) {
return repositoryCredentials.getCredentialsList();
}
}
return new ArrayList<>();
}
private void cleanupRemoteRepositories() {
for (RemoteRepositoryCredentials repositoryCredentials : repositoriesCredentials) {
if (repositoryCredentials.getCredentialsList().isEmpty()) {
repositoriesCredentials.remove(repositoryCredentials);
break;
}
}
}
/**
* Create a {@link PropertySet} object instance that holds all parameters.
* Clients that want to maintain properties need to overwrite this method.
*
* @return An instance of {@link PropertySet}, holding all configuration parameters.
* @see #createPropertySet(Object)
*/
@Override
protected PropertySet createPropertySet() {
return createPropertySet(repositoriesCredentialsBean);
}
/**
* Create a panel that allows the user to set the parameters in the given {@link BindingContext}. Clients that want to create their own panel representation on the given properties need to overwrite this method.
*
* @param context The {@link BindingContext} for the panel.
* @return A JPanel instance for the given {@link BindingContext}, never {@code null}.
*/
@Override
protected JPanel createPanel(BindingContext context) {
JPanel remoteFileRepositoriesTabUI = buildRemoteRepositoriesTabUI();
SwingUtilities.invokeLater(() -> repositoriesListTable.changeSelection(0, RepositoriesTableModel.REPO_NAME_COLUMN, false, false));
isInitialized = true;
return remoteFileRepositoriesTabUI;
}
/**
* Updates the UI.
*/
@Override
public void update() {
if (isInitialized) {
if (repositoriesListTable.getSelectedRow() < 0) {
SwingUtilities.invokeLater(() -> repositoriesListTable.changeSelection(0, RepositoriesTableModel.REPO_NAME_COLUMN, false, false));
} else {
refreshCredentialsTable();
refreshSearchResultsConfigurations();
}
}
}
/**
* Saves the changes.
*/
@Override
public void applyChanges() {
final TableCellEditor tableCellEditor = this.credentialsListTable.getCellEditor();
if (tableCellEditor != null) {
tableCellEditor.stopCellEditing();
}
if (isChanged()) {
try {
RepositoriesCredentialsController repositoriesCredentialsController = RepositoriesCredentialsController.getInstance();
List<RemoteRepositoryCredentials> changedRepositoriesCredentials = getChangedRemoteRepositories();
boolean changedAutoUncompress = getChangedAutoUncompress();
boolean changedDownloadAllPagesEnabled = getChangedDownloadAllPagesEnabled();
int changedNrRecordsOnPage = getChangedNrRecordsOnPage();
repositoriesCredentialsController.saveConfigurations(new RepositoriesCredentialsConfigurations(createCopy(changedRepositoriesCredentials), repositoriesCredentialsController.getRepositoriesCollectionsCredentials(), changedAutoUncompress, changedDownloadAllPagesEnabled, changedNrRecordsOnPage));
this.autoUncompress = changedAutoUncompress;
this.downloadAllPages = changedDownloadAllPagesEnabled;
this.nrRecordsOnPage = changedNrRecordsOnPage;
AppContext appContext = SnapApp.getDefault().getAppContext();
SwingUtilities.invokeLater(() -> appContext.getApplicationWindow().firePropertyChange(REMOTE_PRODUCTS_REPOSITORY_CREDENTIALS, 1, 2));
} catch (Exception ex) {
String title = "Error saving remote repositories credentials";
String msg = "Unable to save Remote Repositories Credentials to SNAP configuration file." + " Details: " + ex.getMessage();
logger.log(Level.SEVERE, msg, ex);
SwingUtilities.invokeLater(() -> JOptionPane.showMessageDialog(credentialsListPanel, msg, title, JOptionPane.ERROR_MESSAGE));
}
}
}
/**
* Cancels the changes.
*/
@Override
public void cancel() {
RepositoriesCredentialsController repositoriesCredentialsController = RepositoriesCredentialsController.getInstance();
this.repositoriesCredentials = createCopy(repositoriesCredentialsController.getRepositoriesCredentials());
this.currentSelectedRow = -1;
this.autoUncompress = repositoriesCredentialsController.isAutoUncompress();
this.downloadAllPages = repositoriesCredentialsController.downloadsAllPages();
this.nrRecordsOnPage = repositoriesCredentialsController.getNrRecordsOnPage();
}
/**
* Check whether options changes.
*
* @return {@code true} if options is changed
*/
@Override
public boolean isChanged() {
boolean changed = false;
RepositoriesCredentialsController repositoriesCredentialsController = RepositoriesCredentialsController.getInstance();
if (repositoriesListTable.getSelectedRow() >= 0) {
List<RemoteRepositoryCredentials> savedRepositoriesCredentials = repositoriesCredentialsController.getRepositoriesCredentials();
List<RemoteRepositoryCredentials> changedRepositoriesCredentials = getChangedRemoteRepositories();
if (RepositoriesCredentialsPersistence.validCredentials(changedRepositoriesCredentials)) {
changed = isRepositoriesChanged(savedRepositoriesCredentials, changedRepositoriesCredentials);
}
}
boolean savedAutoUncompress = repositoriesCredentialsController.isAutoUncompress();
boolean savedDownloadAllPages = repositoriesCredentialsController.downloadsAllPages();
int savedRecordsOnPage = repositoriesCredentialsController.getNrRecordsOnPage();
return changed || savedAutoUncompress != getChangedAutoUncompress() || savedDownloadAllPages != getChangedDownloadAllPagesEnabled() || savedRecordsOnPage != getChangedNrRecordsOnPage();
}
/**
* Gets the Help Context for this Options Controller
*
* @return The Help Context
*/
@Override
public HelpCtx getHelpCtx() {
return new HelpCtx("productLibraryToolV2");
}
/**
* Creates and gets the remote repositories table.
*
* @return The remote repositories table
*/
private JTable buildRepositoriesListTable() {
JTable newRepositoriesListTable = new JTable();
RepositoriesTableModel repositoriesTableModel = new RepositoriesTableModel(this.remoteRepositories);
newRepositoriesListTable.setModel(repositoriesTableModel);
newRepositoriesListTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
newRepositoriesListTable.getSelectionModel().addListSelectionListener(event -> refreshCredentialsTable());
newRepositoriesListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return newRepositoriesListTable;
}
/**
* Creates and gets the panel with remote repositories table.
*
* @return The panel with add and remove buttons panel and remote file repositories table
*/
private JScrollPane buildRepositoriesListPanel() {
JScrollPane remoteRepositoriesListSP = new JScrollPane();
remoteRepositoriesListSP.setViewportView(repositoriesListTable);
remoteRepositoriesListSP.setBorder(BorderFactory.createTitledBorder("Remote Repositories (Data Sources) List"));
remoteRepositoriesListSP.setLayout(new ScrollPaneLayout());
remoteRepositoriesListSP.setAutoscrolls(false);
return remoteRepositoriesListSP;
}
/**
* Runs the event associated with button for adding remote repository credential.
*/
private void runAddCredentialEvent() {
RepositoriesCredentialsTableModel repositoriesCredentialsTableModel = (RepositoriesCredentialsTableModel) credentialsListTable.getModel();
Credentials newCredential = new UsernamePasswordCredentials("", "");
repositoriesCredentialsTableModel.add(newCredential);
}
/**
* Creates and gets the button for adding remote repository credential.
*
* @return The button for adding remote repository credential
*/
private JButton buildAddCredentialButton() {
JButton addCredentialButton = new JButton(addButtonIcon);
addCredentialButton.setPreferredSize(new Dimension(20, 20));
addCredentialButton.addActionListener(e -> runAddCredentialEvent());
return addCredentialButton;
}
/**
* Runs the event associated with button for removing remote repository credential.
*/
private void runRemoveCredentialEvent() {
int selectedRowIndex = credentialsListTable.getSelectedRow();
if (selectedRowIndex >= 0) {
final TableCellEditor tableCellEditor = credentialsListTable.getDefaultEditor(JTextField.class);
if (tableCellEditor != null) {
tableCellEditor.stopCellEditing();
}
RepositoriesCredentialsTableModel repositoriesCredentialsTableModel = (RepositoriesCredentialsTableModel) credentialsListTable.getModel();
repositoriesCredentialsTableModel.remove(selectedRowIndex);
} else {
String title = "Delete repository credential";
String msg = "Please select a repository credential from list.";
JOptionPane.showMessageDialog(credentialsListTable, msg, title, JOptionPane.WARNING_MESSAGE);
}
}
/**
* Creates and gets the button for removing remote repository credential.
*
* @return The button for removing remote repository credential
*/
private JButton buildRemoveCredentialButton() {
JButton removeCredentialButton = new JButton(removeButtonIcon);
removeCredentialButton.setPreferredSize(new Dimension(20, 20));
removeCredentialButton.addActionListener(e -> runRemoveCredentialEvent());
return removeCredentialButton;
}
private DefaultTableCellRenderer buildButtonCellRenderer() {
return new DefaultTableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) {
return (JButton) value;
}
};
}
private DefaultCellEditor buildTextCellEditor(RepositoriesCredentialsTableModel repositoriesCredentialsTableModel) {
DefaultCellEditor textCellEditor = new DefaultCellEditor(new JTextField()) {
private JTextField textField;
private int row;
private int column;
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
Credentials credentials = repositoriesCredentialsTableModel.get(row);
if (column < 1) {
textField = new JTextField(credentials.getUserPrincipal().getName());
} else {
textField = new JPasswordField(credentials.getPassword());
((JPasswordField) textField).setEchoChar('\u25cf');
}
this.row = row;
this.column = column;
return textField;
}
@Override
public boolean stopCellEditing() {
repositoriesCredentialsTableModel.updateCellData(this.row, this.column, this.textField.getText());
fireEditingStopped();
return true;
}
};
textCellEditor.setClickCountToStart(1);
return textCellEditor;
}
private DefaultCellEditor buildButtonCellEditor() {
DefaultCellEditor buttonCellEditor = new DefaultCellEditor(new JTextField()) {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return (JButton) value;
}
@Override
public boolean stopCellEditing() {
fireEditingStopped();
return true;
}
};
buttonCellEditor.setClickCountToStart(1);
return buttonCellEditor;
}
/**
* Creates and gets the remote repository credentials table.
*
* @return The remote repository credentials table
*/
private JTable buildCredentialsListTable() {
JTable newCredentialsListTable = new JTable();
RepositoriesCredentialsTableModel repositoriesCredentialsTableModel = new RepositoriesCredentialsTableModel();
newCredentialsListTable.setModel(repositoriesCredentialsTableModel);
newCredentialsListTable.setDefaultRenderer(JButton.class, buildButtonCellRenderer());
newCredentialsListTable.setDefaultEditor(JTextField.class, buildTextCellEditor(repositoriesCredentialsTableModel));
newCredentialsListTable.setDefaultEditor(JPasswordField.class, buildTextCellEditor(repositoriesCredentialsTableModel));
newCredentialsListTable.setDefaultEditor(JButton.class, buildButtonCellEditor());
newCredentialsListTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_ALL_COLUMNS);
newCredentialsListTable.getColumnModel().getColumn(RepositoriesCredentialsTableModel.REPO_CRED_PASS_SEE_COLUMN).setMaxWidth(20);
newCredentialsListTable.setRowHeight(new JTextField().getPreferredSize().height);
newCredentialsListTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
return newCredentialsListTable;
}
/**
* Creates and gets the panel with add and remove buttons for remote repository credentials table.
*
* @return The panel with add and remove buttons
*/
private JPanel buildCredentialsListActionsPanel() {
JPanel credentialsListActionsPanel = new JPanel();
credentialsListActionsPanel.setLayout(new BoxLayout(credentialsListActionsPanel, BoxLayout.PAGE_AXIS));
credentialsListActionsPanel.add(buildAddCredentialButton());
credentialsListActionsPanel.add(buildRemoveCredentialButton());
credentialsListActionsPanel.add(Box.createVerticalGlue());
return credentialsListActionsPanel;
}
/**
* Creates and gets the panel with add and remove buttons panel and remote repository credentials table.
*
* @return The panel with add and remove buttons panel and remote repository credentials table
*/
private JPanel buildCredentialsListPanel() {
JScrollPane credentialsListPanelSP = new JScrollPane();
credentialsListPanelSP.setViewportView(credentialsListTable);
credentialsListPanel = new JPanel();
credentialsListPanel.setBorder(BorderFactory.createTitledBorder("Credentials List"));
credentialsListPanel.setLayout(new BoxLayout(credentialsListPanel, BoxLayout.LINE_AXIS));
credentialsListPanel.add(credentialsListPanelSP);
credentialsListPanel.add(buildCredentialsListActionsPanel());
return credentialsListPanel;
}
/**
* Creates and gets the panel with remote repositories table and remote repository credentials table.
*
* @return The panel with remote repositories table and remote repository credentials table
*/
private JSplitPane buildRemoteRepositoriesPanel() {
JSplitPane remoteRepositoriesPanel = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
remoteRepositoriesPanel.setOneTouchExpandable(false);
remoteRepositoriesPanel.setContinuousLayout(true);
remoteRepositoriesPanel.setDividerSize(5);
remoteRepositoriesPanel.setDividerLocation(0.5);
JScrollPane remoteRepositoriesListPane = buildRepositoriesListPanel();
JPanel remoteRepositoryCredentialsListPane = buildCredentialsListPanel();
Dimension minimumSize = new Dimension(350, 350);
remoteRepositoriesListPane.setPreferredSize(minimumSize);
remoteRepositoryCredentialsListPane.setPreferredSize(minimumSize);
remoteRepositoryCredentialsListPane.addComponentListener(new ComponentListener() {
@Override
public void componentResized(ComponentEvent e) {
//nothing
}
@Override
public void componentMoved(ComponentEvent e) {
//nothing
}
@Override
public void componentShown(ComponentEvent e) {
remoteRepositoriesPanel.setDividerLocation(0.5);
}
@Override
public void componentHidden(ComponentEvent e) {
//nothing
}
});
remoteRepositoriesPanel.setLeftComponent(remoteRepositoriesListPane);
remoteRepositoriesPanel.setRightComponent(remoteRepositoryCredentialsListPane);
return remoteRepositoriesPanel;
}
private JPanel buildAutoUncompressPanel() {
JPanel autoUncompressPanel = new JPanel();
autoUncompressPanel.setLayout(new BoxLayout(autoUncompressPanel, BoxLayout.LINE_AXIS));
autoUncompressEnabled = new JRadioButton("Yes");
JRadioButton autoUncompressDisabled = new JRadioButton("No", true);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(autoUncompressEnabled);
buttonGroup.add(autoUncompressDisabled);
autoUncompressEnabled.setSelected(this.autoUncompress);
JPanel autoUncompressRBsPanel = new JPanel();
autoUncompressRBsPanel.setLayout(new BoxLayout(autoUncompressRBsPanel, BoxLayout.LINE_AXIS));
autoUncompressRBsPanel.add(autoUncompressEnabled);
autoUncompressRBsPanel.add(autoUncompressDisabled);
autoUncompressPanel.add(new JLabel("Auto uncompress downloaded archive products:", SwingConstants.LEFT));
autoUncompressPanel.add(autoUncompressRBsPanel);
autoUncompressPanel.add(Box.createHorizontalGlue());
return autoUncompressPanel;
}
private JPanel buildDownloadAllPagesPanel() {
JPanel downloadAllPagesPanel = new JPanel();
downloadAllPagesPanel.setLayout(new BoxLayout(downloadAllPagesPanel, BoxLayout.LINE_AXIS));
downloadAllPagesEnabled = new JRadioButton("Yes");
JRadioButton downloadAllPagesDisabled = new JRadioButton("No", true);
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(downloadAllPagesEnabled);
buttonGroup.add(downloadAllPagesDisabled);
downloadAllPagesEnabled.setSelected(this.downloadAllPages);
JPanel downloadAllPagesRBsPanel = new JPanel();
downloadAllPagesRBsPanel.setLayout(new BoxLayout(downloadAllPagesRBsPanel, BoxLayout.LINE_AXIS));
downloadAllPagesRBsPanel.add(downloadAllPagesEnabled);
downloadAllPagesRBsPanel.add(downloadAllPagesDisabled);
downloadAllPagesPanel.add(new JLabel("Download all pages of result search:", SwingConstants.LEFT));
downloadAllPagesPanel.add(downloadAllPagesRBsPanel);
downloadAllPagesPanel.add(Box.createHorizontalGlue());
return downloadAllPagesPanel;
}
private JPanel buildRecordsOnPagePanel() {
JPanel recordsOnPagePanel = new JPanel();
recordsOnPagePanel.setLayout(new BoxLayout(recordsOnPagePanel, BoxLayout.LINE_AXIS));
recordsOnPageCb = new JComboBox<>(new Integer[]{10, 20, 30, 40, 50});
recordsOnPageCb.setMaximumSize(new Dimension(20, 50));
recordsOnPageCb.setSelectedItem(this.nrRecordsOnPage);
recordsOnPagePanel.add(new JLabel("Number of records on search result page:", SwingConstants.LEFT));
recordsOnPagePanel.add(recordsOnPageCb);
recordsOnPagePanel.add(Box.createHorizontalGlue());
return recordsOnPagePanel;
}
private JPanel buildExtraConfigurationsPanel() {
JPanel extraConfigurationsPanel = new JPanel();
extraConfigurationsPanel.setBorder(BorderFactory.createTitledBorder("Other options"));
extraConfigurationsPanel.setLayout(new BoxLayout(extraConfigurationsPanel, BoxLayout.PAGE_AXIS));
extraConfigurationsPanel.add(buildAutoUncompressPanel());
extraConfigurationsPanel.add(Box.createHorizontalGlue());
extraConfigurationsPanel.add(buildDownloadAllPagesPanel());
extraConfigurationsPanel.add(Box.createHorizontalGlue());
extraConfigurationsPanel.add(buildRecordsOnPagePanel());
extraConfigurationsPanel.add(Box.createHorizontalGlue());
return extraConfigurationsPanel;
}
/**
* Creates and gets the root panel for remote repositories tab ui.
*
* @return The root panel for remote repositories tab ui
*/
private JPanel buildRemoteRepositoriesTabUI() {
JPanel remoteRepositoriesTabUI = new JPanel(new BorderLayout());
remoteRepositoriesTabUI.add(buildRemoteRepositoriesPanel(), BorderLayout.CENTER);
remoteRepositoriesTabUI.add(buildExtraConfigurationsPanel(), BorderLayout.PAGE_END);
return remoteRepositoriesTabUI;
}
/**
* Loads the remote repository credentials usernames and passwords from/on remote repository credentials table
*/
private void refreshCredentialsTable() {
RepositoriesTableModel repositoriesTableModel = (RepositoriesTableModel) repositoriesListTable.getModel();
RepositoriesCredentialsTableModel repositoriesCredentialsTableModel = (RepositoriesCredentialsTableModel) credentialsListTable.getModel();
if (credentialsListTable.getSelectedColumn() >= 0) {
credentialsListTable.getDefaultEditor(credentialsListTable.getColumnClass(credentialsListTable.getSelectedColumn())).stopCellEditing();
}
String remoteRepositoryName;
List<Credentials> repositoryCredentials;
List<Credentials> repositoryCredentialsFromTable;
if (this.currentSelectedRow >= 0) {
remoteRepositoryName = repositoriesTableModel.get(this.currentSelectedRow).getRepositoryName();
repositoryCredentials = getRemoteRepositoryCredentials(remoteRepositoryName);
repositoryCredentialsFromTable = repositoriesCredentialsTableModel.fetchData();
if (!repositoryCredentials.isEmpty()) {
repositoryCredentials.clear();
repositoryCredentials.addAll(repositoryCredentialsFromTable);
cleanupRemoteRepositories();
} else {
if (!repositoryCredentialsFromTable.isEmpty()) {
this.repositoriesCredentials.add(new RemoteRepositoryCredentials(remoteRepositoryName, repositoryCredentialsFromTable));
}
}
}
int selectedRow = repositoriesListTable.getSelectedRow();
if (selectedRow >= 0) {
remoteRepositoryName = repositoriesTableModel.get(selectedRow).getRepositoryName();
repositoryCredentials = getRemoteRepositoryCredentials(remoteRepositoryName);
repositoriesCredentialsTableModel.setData(repositoryCredentials);
this.currentSelectedRow = selectedRow;
}
}
private void refreshSearchResultsConfigurations() {
this.autoUncompressEnabled.setSelected(this.autoUncompress);
this.downloadAllPagesEnabled.setSelected(this.downloadAllPages);
this.recordsOnPageCb.setSelectedItem(this.nrRecordsOnPage);
}
/**
* The bean with fields annoted with {@link Preference} for Product Library Remote Repositories Credentials Options.
*/
static class RepositoriesCredentialsBean {
@Preference(label = "S", key = "s")
String s;
}
}
| 33,588 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositoriesCredentialsTableModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/preferences/model/RepositoriesCredentialsTableModel.java | package org.esa.snap.product.library.ui.v2.preferences.model;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.esa.snap.product.library.ui.v2.preferences.RepositoriesCredentialsControllerUI;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;
/**
* The model of the table containing the user accounts for a remote repository.
*/
public class RepositoriesCredentialsTableModel extends AbstractTableModel {
/**
* The column index for remote repository credential password in remote file repository properties table.
*/
public static final int REPO_CRED_PASS_SEE_COLUMN = 2;
/**
* The column index for remote repository credential username in remote file repository properties table.
*/
private static final int REPO_CRED_USER_COLUMN = 0;
/**
* The column index for remote repository credential password in remote file repository properties table.
*/
private static final int REPO_CRED_PASS_COLUMN = 1;
private final List<CredentialsTableRow> credentialsTableData;
private final String[] columnsNames;
private final Class[] columnsClass;
public RepositoriesCredentialsTableModel() {
credentialsTableData = new ArrayList<>();
columnsNames = new String[]{
"Username", "Password", ""
};
columnsClass = new Class[]{
JTextField.class, JPasswordField.class, JButton.class
};
}
/**
* Returns the number of rows in the model. A
* <code>JTable</code> uses this method to determine how many rows it
* should display. This method should be quick, as it
* is called frequently during rendering.
*
* @return the number of rows in the model
* @see #getColumnCount
*/
@Override
public int getRowCount() {
return credentialsTableData.size();
}
/**
* Returns the number of columns in the model. A
* <code>JTable</code> uses this method to determine how many columns it
* should create and display by default.
*
* @return the number of columns in the model
* @see #getRowCount
*/
@Override
public int getColumnCount() {
return columnsNames.length;
}
/**
* Returns the name of the column at <code>columnIndex</code>. This is used
* to initialize the table's column header name. Note: this name does
* not need to be unique; two columns in a table can have the same name.
*
* @param columnIndex the index of the column
* @return the name of the column
*/
@Override
public String getColumnName(int columnIndex) {
return columnsNames[columnIndex];
}
/**
* Returns the most specific superclass for all the cell values
* in the column. This is used by the <code>JTable</code> to set up a
* default renderer and editor for the column.
*
* @param columnIndex the index of the column
* @return the common ancestor class of the object values in the model.
*/
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnsClass[columnIndex];
}
/**
* Returns true if the cell at <code>rowIndex</code> and
* <code>columnIndex</code>
* is editable. Otherwise, <code>setValueAt</code> on the cell will not
* change the value of that cell.
*
* @param rowIndex the row whose value to be queried
* @param columnIndex the column whose value to be queried
* @return true if the cell is editable
* @see #setValueAt
*/
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
}
/**
* Returns the value for the cell at <code>columnIndex</code> and
* <code>rowIndex</code>.
*
* @param rowIndex the row whose value is to be queried
* @param columnIndex the column whose value is to be queried
* @return the value Object at the specified cell
*/
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case REPO_CRED_USER_COLUMN:
return credentialsTableData.get(rowIndex).getUserCellData();
case REPO_CRED_PASS_COLUMN:
return credentialsTableData.get(rowIndex).getPasswordCellData();
case REPO_CRED_PASS_SEE_COLUMN:
return credentialsTableData.get(rowIndex).getButton();
default:
return null;
}
}
public Credentials get(int row) {
return credentialsTableData.get(row).getCredentials();
}
public boolean add(Credentials credential) {
boolean exists = false;
for (CredentialsTableRow credentialData : credentialsTableData) {
UsernamePasswordCredentials savedCredential = (UsernamePasswordCredentials) credentialData.getCredentials();
String savedUsername = savedCredential.getUserPrincipal().getName();
String username = credential.getUserPrincipal().getName();
String savedPassword = savedCredential.getPassword();
String password = credential.getPassword();
if (savedUsername.contentEquals(username) && savedPassword.contentEquals(password)) {
exists = true;
break;
}
}
if (!exists) {
CredentialsTableRow credentialsTableRow = new CredentialsTableRow(credential, credentialsTableData.size());
credentialsTableData.add(credentialsTableRow);
int row = credentialsTableData.indexOf(credentialsTableRow);
fireTableRowsInserted(row, row);
return true;
}
return false;
}
public void remove(int row) {
credentialsTableData.remove(row);
fireTableRowsDeleted(row, row);
}
public void setData(List<Credentials> credentialsList) {
int rowsDeleted = this.credentialsTableData.size();
if (rowsDeleted > 0) {
this.credentialsTableData.clear();
fireTableRowsDeleted(0, rowsDeleted - 1);
}
if (credentialsList != null) {
for (Credentials credential : credentialsList) {
CredentialsTableRow credentialsTableRow = new CredentialsTableRow(credential, this.credentialsTableData.size());
this.credentialsTableData.add(credentialsTableRow);
}
}
fireTableDataChanged();
}
public void updateCellData(int row, int column, String data) {
if (credentialsTableData.size() > row) {
switch (column) {
case REPO_CRED_USER_COLUMN:
credentialsTableData.get(row).setUserCellData(data);
break;
case REPO_CRED_PASS_COLUMN:
credentialsTableData.get(row).setPasswordCellData(data);
break;
default:
break;
}
}
}
public List<Credentials> fetchData() {
List<Credentials> credentialsList = new ArrayList<>();
for (CredentialsTableRow credentialsTableRow : this.credentialsTableData) {
credentialsList.add(credentialsTableRow.getCredentials());
}
return credentialsList;
}
private class CredentialsTableRow {
private String userCellData;
private String passwordCellData;
private JButton button;
private boolean hidden = true;
CredentialsTableRow(Credentials credential, int rowIndex) {
this.userCellData = credential.getUserPrincipal().getName();
this.passwordCellData = credential.getPassword();
this.button = new JButton(RepositoriesCredentialsControllerUI.getPasswordSeeIcon());
this.button.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
hidden = false;
RepositoriesCredentialsTableModel.this.fireTableCellUpdated(rowIndex, REPO_CRED_PASS_COLUMN);
}
@Override
public void mouseReleased(MouseEvent e) {
hidden = true;
RepositoriesCredentialsTableModel.this.fireTableCellUpdated(rowIndex, REPO_CRED_PASS_COLUMN);
}
});
}
String getUserCellData() {
return userCellData;
}
void setUserCellData(String userCellData) {
this.userCellData = userCellData;
}
String getPasswordCellData() {
if (hidden) {
return passwordCellData.replaceAll(".+?", "\u25cf");
}
return passwordCellData;
}
void setPasswordCellData(String passwordCellData) {
this.passwordCellData = passwordCellData;
}
JButton getButton() {
return button;
}
Credentials getCredentials() {
String username = this.userCellData;
String password = this.passwordCellData;
return new UsernamePasswordCredentials(username, password);
}
}
}
| 9,374 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RepositoriesTableModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/preferences/model/RepositoriesTableModel.java | package org.esa.snap.product.library.ui.v2.preferences.model;
import org.esa.snap.remote.products.repository.RemoteProductsRepositoryProvider;
import javax.swing.table.AbstractTableModel;
import java.util.List;
/**
* The model of the table containing the available remote repositories.
*/
public class RepositoriesTableModel extends AbstractTableModel {
/**
* The column index for remote repository name in remote repositories table.
*/
public static final int REPO_NAME_COLUMN = 0;
private List<RemoteProductsRepositoryProvider> repositoriesNamesList;
private String[] columnsNames;
private Class[] columnsClass;
public RepositoriesTableModel(List<RemoteProductsRepositoryProvider> repositoriesNamesList) {
columnsNames = new String[]{
"Name"
};
columnsClass = new Class[]{
String.class
};
this.repositoriesNamesList = repositoriesNamesList;
}
/**
* Returns the number of rows in the model. A
* <code>JTable</code> uses this method to determine how many rows it
* should display. This method should be quick, as it
* is called frequently during rendering.
*
* @return the number of rows in the model
* @see #getColumnCount
*/
@Override
public int getRowCount() {
return repositoriesNamesList.size();
}
/**
* Returns the number of columns in the model. A
* <code>JTable</code> uses this method to determine how many columns it
* should create and display by default.
*
* @return the number of columns in the model
* @see #getRowCount
*/
@Override
public int getColumnCount() {
return columnsNames.length;
}
/**
* Returns the name of the column at <code>columnIndex</code>. This is used
* to initialize the table's column header name. Note: this name does
* not need to be unique; two columns in a table can have the same name.
*
* @param columnIndex the index of the column
* @return the name of the column
*/
@Override
public String getColumnName(int columnIndex) {
return columnsNames[columnIndex];
}
/**
* Returns the most specific superclass for all the cell values
* in the column. This is used by the <code>JTable</code> to set up a
* default renderer and editor for the column.
*
* @param columnIndex the index of the column
* @return the common ancestor class of the object values in the model.
*/
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnsClass[columnIndex];
}
/**
* Returns true if the cell at <code>rowIndex</code> and
* <code>columnIndex</code>
* is editable. Otherwise, <code>setValueAt</code> on the cell will not
* change the value of that cell.
*
* @param rowIndex the row whose value to be queried
* @param columnIndex the column whose value to be queried
* @return true if the cell is editable
* @see #setValueAt
*/
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
/**
* Returns the value for the cell at <code>columnIndex</code> and
* <code>rowIndex</code>.
*
* @param rowIndex the row whose value is to be queried
* @param columnIndex the column whose value is to be queried
* @return the value Object at the specified cell
*/
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
if (columnIndex == REPO_NAME_COLUMN) {
return repositoriesNamesList.get(rowIndex).getRepositoryName();
}
return null;
}
public RemoteProductsRepositoryProvider get(int row) {
return repositoriesNamesList.get(row);
}
public void add(RemoteProductsRepositoryProvider repositoryName) {
repositoriesNamesList.add(repositoryName);
int row = repositoriesNamesList.size() - 1;
fireTableRowsInserted(row, row);
}
public void remove(int row) {
repositoriesNamesList.remove(row);
fireTableRowsDeleted(row, row);
}
}
| 4,206 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 1678)
package org.esa.snap.product.library.ui.v2.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 170 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractProgressTimerRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/thread/AbstractProgressTimerRunnable.java | package org.esa.snap.product.library.ui.v2.thread;
import com.bc.ceres.core.ProgressMonitor;
import org.esa.snap.ui.loading.GenericRunnable;
import org.esa.snap.ui.loading.PairRunnable;
import javax.swing.*;
import java.awt.EventQueue;
/**
* The <code>AbstractProgressTimerRunnable</code> class should be extended by any
* class whose instances are intended to be executed by a thread. The class contains a timer
* started when the thread is started to show after a predefinesd period the progress bar panel.
*
* Created by jcoravu on 23/8/2019.
*/
public abstract class AbstractProgressTimerRunnable<OutputType> extends AbstractRunnable<OutputType> implements ProgressMonitor {
private final ProgressBarHelper progressPanel;
private final java.util.Timer timer;
private final int timerDelayInMilliseconds;
private final int threadId;
protected AbstractProgressTimerRunnable(ProgressBarHelper progressPanel, int threadId, int timerDelayInMilliseconds) {
super();
this.progressPanel = progressPanel;
this.threadId = threadId;
this.timerDelayInMilliseconds = timerDelayInMilliseconds;
this.timer = (this.timerDelayInMilliseconds > 0) ? new java.util.Timer() : null;
}
@Override
protected final void failedExecuting(Exception exception) {
GenericRunnable<Exception> runnable = new GenericRunnable<Exception>(exception) {
@Override
protected void execute(Exception threadException) {
if (onHideProgressPanelLater()) {
onFailed(threadException);
}
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
protected final void successfullyExecuting(OutputType result) {
GenericRunnable<OutputType> runnable = new GenericRunnable<OutputType>(result) {
@Override
protected void execute(OutputType item) {
if (onHideProgressPanelLater()) {
onSuccessfullyFinish(item);
}
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
protected final void finishRunning() {
super.finishRunning();
stopTimer();
Runnable runnable = new Runnable() {
@Override
public void run() {
onFinishRunning();
}
};
SwingUtilities.invokeLater(runnable);
}
public void cancelRunning() {
setRunning(false);
stopTimer();
}
@Override
public final void executeAsync() {
startTimerIfDefined();
super.executeAsync();
}
@Override
public final void beginTask(String taskName, int totalWork) {
PairRunnable<String, Integer> runnable = new PairRunnable<String, Integer>(taskName, totalWork) {
@Override
protected void execute(String message, Integer maximumValue) {
progressPanel.beginProgressBarTask(threadId, message, maximumValue.intValue());
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public final void worked(int valueToAdd) {
GenericRunnable<Integer> runnable = new GenericRunnable<Integer>(valueToAdd) {
@Override
protected void execute(Integer value) {
progressPanel.updateProgressBarValue(threadId, value.intValue());
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
public final void setTaskName(String taskName) {
updateProgressBarTextLater(taskName);
}
@Override
public final void setSubTaskName(String subTaskName) {
updateProgressBarTextLater(subTaskName);
}
@Override
public final void done() {
// do nothing
}
@Override
public final void internalWorked(double work) {
// do nothing
}
@Override
public final boolean isCanceled() {
return isFinished();
}
@Override
public final void setCanceled(boolean canceled) {
// do nothing
}
protected boolean onHideProgressPanelLater() {
return this.progressPanel.hideProgressPanel(this.threadId);
}
protected void onFinishRunning() {
}
protected void onFailed(Exception exception) {
}
protected void onSuccessfullyFinish(OutputType result) {
}
protected boolean onTimerWakeUp(String message) {
return this.progressPanel.showProgressPanel(this.threadId, message);
}
protected final boolean onUpdateProgressBarText(String message) {
return this.progressPanel.updateProgressBarText(this.threadId, message);
}
protected final boolean isCurrentProgressPanelThread() {
if (EventQueue.isDispatchThread()) {
return this.progressPanel.isCurrentThread(this.threadId);
} else {
throw new IllegalStateException("The method must be invoked from the current AWT thread.");
}
}
protected final void onShowErrorMessageDialog(JComponent parentDialogComponent, String message, String title) {
JOptionPane.showMessageDialog(parentDialogComponent, message, title, JOptionPane.ERROR_MESSAGE);
}
protected final void updateProgressBarTextLater(String text) {
GenericRunnable<String> runnable = new GenericRunnable<String>(text) {
@Override
protected void execute(String message) {
onUpdateProgressBarText(message);
}
};
SwingUtilities.invokeLater(runnable);
}
private void startTimerIfDefined() {
if (this.timerDelayInMilliseconds > 0) {
java.util.TimerTask timerTask = new java.util.TimerTask() {
@Override
public void run() {
if (!isFinished()) {
notifyTimerWakeUpLater();
}
}
};
this.timer.schedule(timerTask, this.timerDelayInMilliseconds);
}
}
private void stopTimer() {
if (this.timer != null) {
this.timer.cancel();
}
}
private void notifyTimerWakeUpLater() {
Runnable runnable = new Runnable() {
@Override
public void run() {
if (!isFinished()) {
onTimerWakeUp(""); // set empty string for progress bar message
}
}
};
SwingUtilities.invokeLater(runnable);
}
}
| 6,532 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ThreadListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/thread/ThreadListener.java | package org.esa.snap.product.library.ui.v2.thread;
/**
* The listener interface for receiving the event when a thread has stopped.
*
* Created by jcoravu on 28/8/2019.
*/
public interface ThreadListener {
public void onStopExecuting(Runnable invokerThread);
}
| 270 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractRunnable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/thread/AbstractRunnable.java | package org.esa.snap.product.library.ui.v2.thread;
import org.esa.snap.remote.products.repository.ThreadStatus;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The <code>AbstractRunnable</code> class should be extended by any
* class whose instances are intended to be executed by a thread.
*
* Created by jcoravu on 23/8/2019.
*/
public abstract class AbstractRunnable<OutputType> implements Runnable, ThreadStatus {
private static final Logger logger = Logger.getLogger(AbstractRunnable.class.getName());
private Boolean isRunning;
protected AbstractRunnable() {
}
protected abstract OutputType execute() throws Exception;
protected abstract String getExceptionLoggingMessage();
@Override
public final boolean isFinished() {
synchronized (this) {
return (this.isRunning != null && !this.isRunning.booleanValue());
}
}
@Override
public final void run() {
try {
startRunning();
OutputType result = execute();
if (!isFinished()) {
successfullyExecuting(result);
}
} catch (Exception exception) {
logger.log(Level.SEVERE, getExceptionLoggingMessage(), exception);
if (!isFinished()) {
failedExecuting(exception);
}
} finally {
finishRunning();
}
}
protected void failedExecuting(Exception exception) {
}
protected void successfullyExecuting(OutputType result) {
}
public void executeAsync() {
Thread thread = new Thread(this);
thread.start(); // start the thread
}
protected void finishRunning() {
setRunning(false);
}
private void startRunning() {
setRunning(true);
}
protected final void setRunning(boolean isRunning) {
synchronized (this) {
this.isRunning = isRunning;
}
}
}
| 1,967 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProgressBarHelperImpl.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/thread/ProgressBarHelperImpl.java | package org.esa.snap.product.library.ui.v2.thread;
import org.esa.snap.ui.loading.SwingUtils;
import javax.swing.*;
import java.awt.*;
import java.beans.PropertyChangeListener;
/**
* The class implementation to manage the progress bar panel visible when running long time operations.
*
* Created by jcoravu on 12/9/2019.
*/
public abstract class ProgressBarHelperImpl implements ProgressBarHelper {
public static final String VISIBLE_PROGRESS_BAR = "visibleProgressBar";
private final JButton stopButton;
private final JProgressBar progressBar;
private final JLabel messageLabel;
private int currentThreadId;
public ProgressBarHelperImpl(int progressBarWidth, int progressBarHeight) {
this.messageLabel = new JLabel("", JLabel.CENTER);
Dimension progressBarSize = new Dimension(progressBarWidth, progressBarHeight);
this.progressBar = new JProgressBar(JProgressBar.HORIZONTAL);
this.progressBar.setLayout(new BorderLayout());
this.progressBar.add(this.messageLabel, BorderLayout.CENTER);
this.progressBar.setIndeterminate(true);
this.progressBar.setPreferredSize(progressBarSize);
this.progressBar.setMinimumSize(progressBarSize);
this.progressBar.setMaximumSize(progressBarSize);
Dimension buttonSize = new Dimension(progressBarHeight, progressBarHeight);
this.stopButton = SwingUtils.buildButton("/org/esa/snap/product/library/ui/v2/icons/stop20.gif", null, buttonSize, 1);
this.stopButton.setToolTipText("Stop");
this.currentThreadId = 0;
setProgressPanelVisible(false);
}
protected abstract void setParametersEnabledWhileDownloading(boolean enabled);
@Override
public boolean isCurrentThread(int threadId) {
if (EventQueue.isDispatchThread()) {
return (this.currentThreadId == threadId);
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
@Override
public boolean hideProgressPanel(int threadId) {
if (EventQueue.isDispatchThread()) {
if (this.currentThreadId == threadId) {
// this.currentThreadId++;
this.messageLabel.setText(""); // reset the message text
boolean oldVisible = this.progressBar.isVisible();
// hide the progress bar
setProgressPanelVisible(false);
this.progressBar.setIndeterminate(true);
if (oldVisible) {
// the progress bar was visible
setParametersEnabledWhileDownloading(true);
}
return true;
}
return false;
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
@Override
public boolean showProgressPanel(int threadId, String message) {
if (EventQueue.isDispatchThread()) {
if (this.currentThreadId == threadId) {
if (message != null) {
this.messageLabel.setText(message); // the message may be null or empty
}
boolean oldVisible = this.progressBar.isVisible();
// show the progress bar
setProgressPanelVisible(true);
if (!oldVisible) {
// the progress bar was hidden
setParametersEnabledWhileDownloading(false);
}
return true;
}
return false;
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
/**
* Update the visible text from the progress bar. The progress bar is not displayed if it is hidden.
* @param threadId
* @param message
* @return
*/
@Override
public boolean updateProgressBarText(int threadId, String message) {
if (EventQueue.isDispatchThread()) {
if (this.currentThreadId == threadId) {
this.messageLabel.setText(message);
return true;
}
return false;
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
@Override
public boolean beginProgressBarTask(int threadId, String message, int totalWork) {
if (EventQueue.isDispatchThread()) {
if (this.currentThreadId == threadId) {
if (totalWork < 0) {
throw new IllegalArgumentException("The total work " + totalWork +" is negative.");
}
this.progressBar.setIndeterminate(false);
this.progressBar.setValue(0);
this.progressBar.setMinimum(0);
this.progressBar.setMaximum(totalWork);
this.messageLabel.setText(message);
return true;
}
return false;
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
@Override
public boolean updateProgressBarValue(int threadId, int valueToAdd) {
if (EventQueue.isDispatchThread()) {
if (this.currentThreadId == threadId) {
if (valueToAdd < 0) {
throw new IllegalArgumentException("The value to add " + valueToAdd +" is negative.");
}
int newValue = progressBar.getValue() + valueToAdd;
if (newValue > this.progressBar.getMaximum()) {
throw new IllegalArgumentException("The new value " + newValue + " is greater than the maximum " + this.progressBar.getMaximum() + ".");
}
this.progressBar.setValue(newValue);
return true;
}
return false;
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
public JButton getStopButton() {
return stopButton;
}
public JProgressBar getProgressBar() {
return progressBar;
}
public void hideProgressPanel() {
if (EventQueue.isDispatchThread()) {
this.currentThreadId++;
setProgressPanelVisible(false);
this.progressBar.setIndeterminate(true);
setParametersEnabledWhileDownloading(true);
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
public final int incrementAndGetCurrentThreadId() {
if (EventQueue.isDispatchThread()) {
return ++this.currentThreadId;
} else {
throw new IllegalStateException("The method must be invoked from the AWT dispatch thread.");
}
}
public void addVisiblePropertyChangeListener(PropertyChangeListener changeListener) {
this.progressBar.addPropertyChangeListener(VISIBLE_PROGRESS_BAR, changeListener);
}
private void setProgressPanelVisible(boolean visible) {
boolean oldVisible = this.progressBar.isVisible();
this.progressBar.setVisible(visible);
this.stopButton.setVisible(visible);
if (oldVisible != visible) {
this.progressBar.firePropertyChange(VISIBLE_PROGRESS_BAR, oldVisible, visible);
}
}
}
| 7,503 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ThreadCallback.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/thread/ThreadCallback.java | package org.esa.snap.product.library.ui.v2.thread;
/**
* The listener interface for receiving events when a thread has finished.
*
* Created by jcoravu on 28/8/2019.
*/
public interface ThreadCallback<OutputType> {
public void onFailed(Exception exception);
public void onSuccessfullyFinish(OutputType productEntries);
}
| 336 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProgressBarHelper.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/thread/ProgressBarHelper.java | package org.esa.snap.product.library.ui.v2.thread;
/**
* The interface to manage the progress bar panel visible when running long time operations.
*
* Created by jcoravu on 23/8/2019.
*/
public interface ProgressBarHelper {
public boolean hideProgressPanel(int threadId);
public boolean showProgressPanel(int threadId, String message);
public boolean isCurrentThread(int threadId);
public boolean updateProgressBarText(int threadId, String message);
public boolean beginProgressBarTask(int threadId, String message, int totalWork);
public boolean updateProgressBarValue(int threadId, int valueToAdd);
}
| 638 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMapPanelWrapperImpl.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-product-library-ui-v2/src/main/java/org/esa/snap/product/library/ui/v2/worldwind/WorldMapPanelWrapperImpl.java | package org.esa.snap.product.library.ui.v2.worldwind;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.product.library.ui.v2.thread.AbstractRunnable;
import org.esa.snap.ui.loading.GenericRunnable;
import org.esa.snap.worldwind.productlibrary.PolygonMouseListener;
import org.esa.snap.worldwind.productlibrary.PolygonsLayerModel;
import org.esa.snap.worldwind.productlibrary.WorldMap3DPanel;
import org.esa.snap.worldwind.productlibrary.WorldMapPanelWrapper;
import javax.swing.*;
import java.awt.*;
public class WorldMapPanelWrapperImpl extends WorldMapPanelWrapper {
public WorldMapPanelWrapperImpl(PolygonMouseListener mouseListener, Color backgroundColor, PropertyMap persistencePreferences) {
super(mouseListener, backgroundColor, persistencePreferences);
}
@Override
public void addWorldMapPanelAsync(boolean flat3DEarth, boolean removeExtraLayers) {
InitWorldMap3DPanelRunnable thread = new InitWorldMap3DPanelRunnable(this, flat3DEarth, removeExtraLayers, this.polygonsLayerModel);
thread.executeAsync(); // start the thread
}
private static class InitWorldMap3DPanelRunnable extends AbstractRunnable<WorldMap3DPanel> {
private final WorldMapPanelWrapper worldWindowPanel;
private final boolean flatEarth;
private final boolean removeExtraLayers;
private final PolygonsLayerModel polygonsLayerModel;
public InitWorldMap3DPanelRunnable(WorldMapPanelWrapper worldWindowPanel, boolean flatEarth, boolean removeExtraLayers, PolygonsLayerModel polygonsLayerModel) {
this.polygonsLayerModel = polygonsLayerModel;
this.worldWindowPanel = worldWindowPanel;
this.flatEarth = flatEarth;
this.removeExtraLayers = removeExtraLayers;
}
@Override
protected WorldMap3DPanel execute() throws Exception {
return new WorldMap3DPanel(this.flatEarth, this.removeExtraLayers, this.polygonsLayerModel);
}
@Override
protected String getExceptionLoggingMessage() {
return "Failed to create the world window panel.";
}
@Override
protected final void successfullyExecuting(WorldMap3DPanel result) {
GenericRunnable<WorldMap3DPanel> runnable = new GenericRunnable<WorldMap3DPanel>(result) {
@Override
protected void execute(WorldMap3DPanel item) {
worldWindowPanel.addWorldWindowPanel(item);
}
};
SwingUtilities.invokeLater(runnable);
}
@Override
protected void failedExecuting(Exception exception) {
GenericRunnable<Exception> runnable = new GenericRunnable<Exception>(exception) {
@Override
protected void execute(Exception item) {
worldWindowPanel.addWorldWindowPanel(null);
}
};
SwingUtilities.invokeLater(runnable);
}
}
}
| 3,009 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-change-detection-ui/src/main/java/org/esa/snap/change/detection/docs/package-info.java | @HelpSetRegistration(helpSet = "help.hs", position = 6020)
package org.esa.snap.change.detection.docs;
import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration; | 165 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DummyPreferences.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/DummyPreferences.java | package org.esa.snap.ui;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.prefs.BackingStoreException;
import java.util.prefs.NodeChangeListener;
import java.util.prefs.PreferenceChangeListener;
import java.util.prefs.Preferences;
/**
* @author Tonio Fincke
*/
public class DummyPreferences extends Preferences {
Map<String, Object> propertyMap;
DummyPreferences() {
propertyMap = new HashMap<String, Object>();
}
@Override
public void put(String key, String value) {
propertyMap.put(key, value);
}
@Override
public String get(String key, String def) {
final Object value = propertyMap.get(key);
if(value != null && !value.equals("")) {
return value.toString();
}
return def;
}
@Override
public void remove(String key) {
}
@Override
public void clear() throws BackingStoreException {
}
@Override
public void putInt(String key, int value) {
propertyMap.put(key, value);
}
@Override
public int getInt(String key, int def) {
final Object value = propertyMap.get(key);
if(value != null) {
return Integer.parseInt(value.toString());
}
return def;
}
@Override
public void putLong(String key, long value) {
}
@Override
public long getLong(String key, long def) {
return 0;
}
@Override
public void putBoolean(String key, boolean value) {
}
@Override
public boolean getBoolean(String key, boolean def) {
return false;
}
@Override
public void putFloat(String key, float value) {
}
@Override
public float getFloat(String key, float def) {
return 0;
}
@Override
public void putDouble(String key, double value) {
}
@Override
public double getDouble(String key, double def) {
return 0;
}
@Override
public void putByteArray(String key, byte[] value) {
}
@Override
public byte[] getByteArray(String key, byte[] def) {
return new byte[0];
}
@Override
public String[] keys() throws BackingStoreException {
return new String[0];
}
@Override
public String[] childrenNames() throws BackingStoreException {
return new String[0];
}
@Override
public Preferences parent() {
return null;
}
@Override
public Preferences node(String pathName) {
return null;
}
@Override
public boolean nodeExists(String pathName) throws BackingStoreException {
return false;
}
@Override
public void removeNode() throws BackingStoreException {
}
@Override
public String name() {
return null;
}
@Override
public String absolutePath() {
return null;
}
@Override
public boolean isUserNode() {
return false;
}
@Override
public String toString() {
return null;
}
@Override
public void flush() throws BackingStoreException {
}
@Override
public void sync() throws BackingStoreException {
}
@Override
public void addPreferenceChangeListener(PreferenceChangeListener pcl) {
}
@Override
public void removePreferenceChangeListener(PreferenceChangeListener pcl) {
}
@Override
public void addNodeChangeListener(NodeChangeListener ncl) {
}
@Override
public void removeNodeChangeListener(NodeChangeListener ncl) {
}
@Override
public void exportNode(OutputStream os) throws IOException, BackingStoreException {
}
@Override
public void exportSubtree(OutputStream os) throws IOException, BackingStoreException {
}
}
| 3,826 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UIUtilsTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/UIUtilsTest.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;
import org.esa.snap.core.param.ParamProperties;
import org.esa.snap.core.param.Parameter;
import org.junit.Test;
import javax.swing.JInternalFrame;
import javax.swing.JSpinner;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.HeadlessException;
import java.awt.Panel;
import java.awt.Rectangle;
import static org.junit.Assert.*;
public class UIUtilsTest {
@Test
public void testCenterComponent() {
try {
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
Component comp = new Panel();
Component alignComp = new Panel();
comp.setBounds(0, 0, 100, 100);
UIUtils.centerComponent(comp);
assertEquals(comp.getBounds(), new Rectangle(screenSize.width / 2 - 50, screenSize.height / 2 - 50, 100, 100));
comp.setBounds(0, 0, 100, 100);
alignComp.setBounds(100, 100, 200, 200);
UIUtils.centerComponent(comp, alignComp);
assertEquals(comp.getBounds(), new Rectangle(150, 150, 100, 100));
} catch (HeadlessException e) {
warnHeadless();
}
}
@Test
public void testGetScreenSize() {
try {
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
assertNotNull(UIUtils.getScreenSize());
assertEquals(UIUtils.getScreenSize(), screenSize);
} catch (HeadlessException e) {
warnHeadless();
}
}
@Test
public void testGetScreenWidth() {
try {
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
assertEquals(UIUtils.getScreenWidth(), screenSize.width);
} catch (HeadlessException e) {
warnHeadless();
}
}
@Test
public void testGetScreenHeight() {
try {
Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
assertEquals(UIUtils.getScreenHeight(), screenSize.height);
} catch (HeadlessException e) {
warnHeadless();
}
}
@Test
public void testGetUniqueFrameTitle() {
String title;
title = UIUtils.getUniqueFrameTitle(
new JInternalFrame[]{
new JInternalFrame("Image1"),
new JInternalFrame("Image2"),
new JInternalFrame("Image3"),
}, "Image");
assertEquals("Image", title);
title = UIUtils.getUniqueFrameTitle(
new JInternalFrame[]{
new JInternalFrame("Image"),
new JInternalFrame("Data"),
new JInternalFrame("Raw"),
}, "Image");
assertEquals("Image (2)", title);
title = UIUtils.getUniqueFrameTitle(
new JInternalFrame[]{
new JInternalFrame("Image (3)"),
new JInternalFrame("Data"),
new JInternalFrame("Raw"),
}, "Image");
assertEquals("Image", title);
title = UIUtils.getUniqueFrameTitle(
new JInternalFrame[]{
new JInternalFrame("Image"),
new JInternalFrame("Image (2)"),
new JInternalFrame("Image (3)"),
}, "Image");
assertEquals("Image (4)", title);
title = UIUtils.getUniqueFrameTitle(
new JInternalFrame[]{
new JInternalFrame("Image"),
new JInternalFrame("Image (2)"),
new JInternalFrame("Image (4)"),
}, "Image");
assertEquals("Image (3)", title);
title = UIUtils.getUniqueFrameTitle(
new JInternalFrame[]{
new JInternalFrame("Image"),
new JInternalFrame("Image (1)"),
new JInternalFrame("Image (2)"),
new JInternalFrame("Image (3)"),
}, "Image");
assertEquals("Image (4)", title);
}
@Test
public void testCreateSpinner_WithParameter() {
final String labelname = "paramLabel";
final ParamProperties properties = new ParamProperties(Integer.class, Integer.valueOf(3));
properties.setLabel(labelname);
final Parameter parameter = new Parameter("paramName", properties);
final JSpinner spinner = UIUtils.createSpinner(parameter, Integer.valueOf(10), "#0");
assertEquals(labelname, spinner.getName());
}
private void warnHeadless() {
System.out.println("A " + UIUtilsTest.class + " test has not been performed: HeadlessException");
}
}
| 5,536 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UserInputHistoryTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/UserInputHistoryTest.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;
import org.junit.Test;
import java.util.prefs.Preferences;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class UserInputHistoryTest {
@Test
public void testFail() {
final String propertyKey = "test.prop";
final Preferences preferences = new DummyPreferences();
preferences.putInt(propertyKey + ".length", 4);
preferences.put(propertyKey + ".0", "0");
preferences.put(propertyKey + ".1", "1");
preferences.put(propertyKey + ".2", "2");
preferences.put(propertyKey + ".3", "3");
preferences.put(propertyKey + ".4", "4");
final UserInputHistory history = new UserInputHistory(9, propertyKey);
assertEquals(9, history.getMaxNumEntries());
assertEquals(0, history.getNumEntries());
assertNull(history.getEntries());
history.initBy(preferences);
assertEquals(4, history.getMaxNumEntries());
assertEquals(4, history.getNumEntries());
String[] entries = history.getEntries();
assertEquals(4, entries.length);
assertEquals("0", entries[0]);
assertEquals("1", entries[1]);
assertEquals("2", entries[2]);
assertEquals("3", entries[3]);
history.push("4");
assertEquals(4, history.getMaxNumEntries());
assertEquals(4, history.getNumEntries());
entries = history.getEntries();
assertEquals(4, entries.length);
assertEquals("4", entries[0]);
assertEquals("0", entries[1]);
assertEquals("1", entries[2]);
assertEquals("2", entries[3]);
history.setMaxNumEntries(2);
assertEquals(2, history.getMaxNumEntries());
assertEquals(2, history.getNumEntries());
entries = history.getEntries();
assertEquals(2, entries.length);
assertEquals("4", entries[0]);
assertEquals("0", entries[1]);
history.copyInto(preferences);
assertEquals("4", preferences.get(propertyKey + ".0", null));
assertEquals("0", preferences.get(propertyKey + ".1", null));
assertNull(preferences.get(propertyKey + ".2", null));
assertNull(preferences.get(propertyKey + ".3", null));
assertNull(preferences.get(propertyKey + ".4", null));
}
}
| 3,054 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RegionSelectableWorldMapPane_BindingContextValidationTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/RegionSelectableWorldMapPane_BindingContextValidationTest.java | package org.esa.snap.ui;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.swing.binding.BindingContext;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class RegionSelectableWorldMapPane_BindingContextValidationTest {
private final static String NORTH_BOUND = RegionSelectableWorldMapPane.NORTH_BOUND;
private final static String SOUTH_BOUND = RegionSelectableWorldMapPane.SOUTH_BOUND;
private final static String WEST_BOUND = RegionSelectableWorldMapPane.WEST_BOUND;
private final static String EAST_BOUND = RegionSelectableWorldMapPane.EAST_BOUND;
private PropertiesObject propertiesObject;
private BindingContext bindingContext;
@Before
public void setUp() throws Exception {
propertiesObject = new PropertiesObject();
bindingContext = new BindingContext(PropertyContainer.createObjectBacked(propertiesObject));
}
@Test
public void testThatBindingContextMustBeNotNull() {
try {
RegionSelectableWorldMapPane.ensureValidBindingContext(null);
fail("should not come here");
} catch (IllegalArgumentException expected) {
assertEquals("bindingContext must be not null", expected.getMessage());
} catch (Exception notExpected) {
fail("Exception '" + notExpected.getClass().getName() + "' is not expected");
}
}
@Test
public void testThatPropertiesObjectAreFilledWithDefaultValuesIfAllPropertyValuesAreNull() {
//preparation
propertiesObject.northBound = null;
propertiesObject.eastBound = null;
propertiesObject.southBound = null;
propertiesObject.westBound = null;
//execution
RegionSelectableWorldMapPane.ensureValidBindingContext(bindingContext);
//verification
assertEquals(Double.valueOf(75.0), propertiesObject.northBound);
assertEquals(Double.valueOf(30.0), propertiesObject.eastBound);
assertEquals(Double.valueOf(35.0), propertiesObject.southBound);
assertEquals(Double.valueOf(-15.0), propertiesObject.westBound);
}
@Test
public void testValidValuesAreNotChanged() {
//preparation
propertiesObject.northBound = 15.0;
propertiesObject.eastBound = 15.0;
propertiesObject.southBound = -15.0;
propertiesObject.westBound = -15.0;
final PropertyContainer objectBacked = PropertyContainer.createObjectBacked(propertiesObject);
//execution
RegionSelectableWorldMapPane.ensureValidBindingContext(new BindingContext(objectBacked));
//verification
assertEquals(Double.valueOf(15.0), propertiesObject.northBound);
assertEquals(Double.valueOf(15.0), propertiesObject.eastBound);
assertEquals(Double.valueOf(-15.0), propertiesObject.southBound);
assertEquals(Double.valueOf(-15.0), propertiesObject.westBound);
}
@Test
public void testThatBindingContextWithoutNorthBoundPropertyThrowsIllegalArgumentException() {
assertIllegalArgumentExceptionIfPropertyIsMissing(NORTH_BOUND);
}
@Test
public void testThatBindingContextWithoutSouthBoundPropertyThrowsIllegalArgumentException() {
assertIllegalArgumentExceptionIfPropertyIsMissing(SOUTH_BOUND);
}
@Test
public void testThatBindingContextWithoutEastBoundPropertyThrowsIllegalArgumentException() {
assertIllegalArgumentExceptionIfPropertyIsMissing(EAST_BOUND);
}
@Test
public void testThatBindingContextWithoutWestBoundPropertyThrowsIllegalArgumentException() {
assertIllegalArgumentExceptionIfPropertyIsMissing(WEST_BOUND);
}
@Test
/**
* It suffices to test one invalid property value, since the implementation responsible for testing whether
* the property values are valid is well tested in {@link RegionSelectableWorldMapPane_BoundingValuesValidation}
*/
public void testThatIllegalArgumentExceptionIsThrownIfAnyPropertyValueIsInvalid() {
//preparation
bindingContext.getPropertySet().setValue(NORTH_BOUND, null);
try {
//execution
RegionSelectableWorldMapPane.ensureValidBindingContext(bindingContext);
} catch (IllegalArgumentException expected) {
//verification
assertEquals("Given geo-bounds (" + null + ", " + EAST_BOUND + ", " + SOUTH_BOUND + ", " + WEST_BOUND +
" are invalid.", expected.getMessage());
} catch (Exception notExpected) {
fail("Exception '" + notExpected.getClass().getName() + "' not expected");
}
}
private void assertIllegalArgumentExceptionIfPropertyIsMissing(String propertyName) {
//preparation
bindingContext.getPropertySet().removeProperty(bindingContext.getPropertySet().getProperty(propertyName));
//execution
try {
RegionSelectableWorldMapPane.ensureValidBindingContext(bindingContext);
fail("should not come here");
} catch (IllegalArgumentException expected) {
//verification
assertEquals("bindingContext must contain a property named " + propertyName, expected.getMessage());
} catch (Exception notExpected) {
fail("Exception '" + notExpected.getClass().getName() + "' not expected");
}
}
private static class PropertiesObject {
private Double northBound;
private Double eastBound;
private Double southBound;
private Double westBound;
}
}
| 5,581 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RegionSelectableWorldMapPane_BoundingValuesValidation.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/RegionSelectableWorldMapPane_BoundingValuesValidation.java | package org.esa.snap.ui;
import org.junit.Test;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import static org.junit.Assert.*;
public class RegionSelectableWorldMapPane_BoundingValuesValidation {
private final double validNorthBound = 75.0;
private final double validEastBound = 30.0;
private final double validSouthBound = 20.0;
private final double validWestBound = 10.0;
@Test
public void testValidBounds() {
assertTrue(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, validEastBound, validSouthBound, validWestBound));
}
@Test
public void testThatReturnValueIsFalseIfAllBoundingValuesAreNull() {
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(null, null, null, null));
}
@Test
public void testThatEachValueMustBeNotNull() {
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(null, validEastBound, validSouthBound, validWestBound));
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, null, validSouthBound, validWestBound));
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, validEastBound, null, validWestBound));
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, validEastBound, validSouthBound, null));
}
@Test
public void testThatNorthValueMustBeBiggerThanSouthValue() {
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(10.0, validEastBound, 10.0, validWestBound));
}
@Test
public void testThatEastValueMustBeBiggerThanWestValue() {
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, 10.0, validSouthBound, 10.0));
}
@Test
public void testThatValuesAreInsideValidBounds() {
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(91.0, validEastBound, validSouthBound, validWestBound));
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, 181.0, validSouthBound, validWestBound));
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, validEastBound, -91.0, validWestBound));
assertFalse(RegionSelectableWorldMapPane.geoBoundsAreValid(validNorthBound, validEastBound, validSouthBound, -181.0));
}
@Test
public void testCorrectBoundsIfNecessary_noCorrection() {
final Rectangle2D.Double toCorrect = new Rectangle2D.Double(-175.0, -85.0, 140.0, 110.0);
RegionSelectableWorldMapPane.correctBoundsIfNecessary(toCorrect);
assertEquals(-175.0, toCorrect.getMinX(), 1e-8);
assertEquals(-85.0, toCorrect.getMinY(), 1e-8);
assertEquals(-175.0 + 140.0, toCorrect.getMaxX(), 1e-8);
assertEquals(-85.0 + 110.0, toCorrect.getMaxY(), 1e-8);
}
@Test
public void testCorrectBoundsIfNecessary_correction_positive_x() {
final Rectangle2D.Double toCorrect = new Rectangle2D.Double(-175.499991, -90.0, 360.0, 180.0);
RegionSelectableWorldMapPane.correctBoundsIfNecessary(toCorrect);
assertEquals(-175.499991, toCorrect.getMinX(), 1e-8);
assertEquals(180.0, toCorrect.getMaxX(), 1e-8);
assertEquals(-90.0, toCorrect.getMinY(), 1e-8);
assertEquals(90.0, toCorrect.getMaxY(), 1e-8);
assertTrue(toCorrect.getMinX() + toCorrect.getWidth() <= 180.0);
assertTrue(toCorrect.getMinY() + toCorrect.getHeight() <= 90.0);
}
@Test
public void testCorrectBoundsIfNecessary_correction_negative_x() {
final Rectangle2D.Double toCorrect = new Rectangle2D.Double(-185.499991, -90.0, 360.0, 180.0);
RegionSelectableWorldMapPane.correctBoundsIfNecessary(toCorrect);
assertEquals(-180.0, toCorrect.getMinX(), 1e-8);
assertEquals(174.50000899999895, toCorrect.getMaxX(), 1e-8);
assertEquals(-90.0, toCorrect.getMinY(), 1e-8);
assertEquals(90.0, toCorrect.getMaxY(), 1e-8);
assertTrue(toCorrect.getMinX() + toCorrect.getWidth() <= 180.0);
assertTrue(toCorrect.getMinY() + toCorrect.getHeight() <= 90.0);
}
}
| 4,096 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FileHistoryTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/FileHistoryTest.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;
import org.esa.snap.GlobalTestConfig;
import org.esa.snap.GlobalTestTools;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.prefs.Preferences;
import static org.esa.snap.core.util.Guardian.assertTrue;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
/**
* <code>FileHistory</code> is a fixed-size array for the pathes of files opened/saved by a user. If a new file is added
* and the file history is full, the list of registered files is shifted so that the oldest file path is beeing
* skipped..
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class FileHistoryTest {
private File _a;
private File _b;
private File _c;
private File _d;
private File _e;
@Before
public void setUp() {
GlobalTestTools.deleteTestDataOutputDirectory();
_a = new File(GlobalTestConfig.getSnapTestDataOutputDirectory(), "A.dim");
_b = new File(GlobalTestConfig.getSnapTestDataOutputDirectory(), "B.dim");
_c = new File(GlobalTestConfig.getSnapTestDataOutputDirectory(), "C.dim");
_d = new File(GlobalTestConfig.getSnapTestDataOutputDirectory(), "D.dim");
_e = new File(GlobalTestConfig.getSnapTestDataOutputDirectory(), "E.dim");
try {
_a.getParentFile().mkdirs();
_a.createNewFile();
_b.createNewFile();
//_c.createNewFile(); should not be created
_d.createNewFile();
_e.createNewFile();
} catch (IOException e) {
}
}
@After
public void tearDown() {
GlobalTestTools.deleteTestDataOutputDirectory();
}
@Test
public void testFileHistory() {
assertTrue(_a.getAbsolutePath() + " does not exist", _a.exists());
assertTrue(_b.getAbsolutePath() + " does not exist", _b.exists());
assertTrue(_c.getAbsolutePath() + " does exist", !_c.exists()); // should not exist
assertTrue(_d.getAbsolutePath() + " deos not exist", _d.exists());
assertTrue(_e.getAbsolutePath() + " deos not exist", _e.exists());
final String propertyKey = "recent.files.";
final Preferences preferences = new DummyPreferences();
preferences.putInt(propertyKey + ".length", 3);
preferences.put(propertyKey + ".0", _a.getAbsolutePath());
preferences.put(propertyKey + ".1", _b.getAbsolutePath());
preferences.put(propertyKey + ".2", _c.getAbsolutePath());
preferences.put(propertyKey + ".3", _d.getAbsolutePath());
preferences.put(propertyKey + ".4", _e.getAbsolutePath());
//create and init new FileHistory
final FileHistory history = new FileHistory(9, propertyKey);
assertEquals(9, history.getMaxNumEntries());
assertEquals(0, history.getNumEntries());
assertNull(history.getEntries());
//init by Properties
history.initBy(preferences);
assertEquals(3, history.getMaxNumEntries());
assertEquals(2, history.getNumEntries());
String[] files = history.getEntries();
assertEquals(2, files.length);
assertEquals(_a.getAbsolutePath(), files[0]);
assertEquals(_b.getAbsolutePath(), files[1]);
//Add new File to existin two files
history.push(_d.getAbsolutePath());
assertEquals(3, history.getNumEntries());
files = history.getEntries();
assertEquals(3, files.length);
assertEquals(_d.getAbsolutePath(), files[0]);
assertEquals(_a.getAbsolutePath(), files[1]);
assertEquals(_b.getAbsolutePath(), files[2]);
//Add new File to existing three files
history.push(_e.getAbsolutePath());
assertEquals(3, history.getNumEntries());
files = history.getEntries();
assertEquals(3, files.length);
assertEquals(_e.getAbsolutePath(), files[0]);
assertEquals(_d.getAbsolutePath(), files[1]);
assertEquals(_a.getAbsolutePath(), files[2]);
//decreace num max files
history.setMaxNumEntries(2);
assertEquals(2, history.getNumEntries());
files = history.getEntries();
assertEquals(2, files.length);
assertEquals(_e.getAbsolutePath(), files[0]);
assertEquals(_d.getAbsolutePath(), files[1]);
//copy values to properties
history.copyInto(preferences);
assertEquals(2, preferences.getInt(propertyKey + ".length", -1));
assertEquals(_e.getAbsolutePath(), preferences.get(propertyKey + ".0", null));
assertEquals(_d.getAbsolutePath(), preferences.get(propertyKey + ".1", null));
assertNull(preferences.get(propertyKey + ".2", null));
assertNull(preferences.get(propertyKey + ".3", null));
assertNull(preferences.get(propertyKey + ".4", null));
}
}
| 5,643 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GUIElementFactoryTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/GUIElementFactoryTest.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;
import org.junit.Test;
import javax.swing.*;
import java.awt.*;
import static org.junit.Assert.*;
public class GUIElementFactoryTest {
@Test
public void testAddComponentsToBorderPanel() {
BorderLayout bl = new BorderLayout();
JPanel panel = new JPanel(bl);
JTextArea centerComp = new JTextArea("textArea");
JLabel westComp = new JLabel("text");
String place = BorderLayout.WEST;
BorderLayoutUtils.addToPanel(panel, centerComp, westComp, place);
assertEquals(2, panel.getComponentCount());
assertTrue(panel.isAncestorOf(centerComp));
assertTrue(panel.isAncestorOf(westComp));
}
@Test
public void testGridBagPanel_fourParams() {
GridBagLayout gbl = new GridBagLayout();
JPanel panel = new JPanel(gbl);
JLabel comp = new JLabel("text");
final GridBagConstraints gbconstr = GridBagUtils.createDefaultConstraints();
GridBagUtils.setAttributes(gbconstr, "gridx=2, gridy=4");
GridBagUtils.addToPanel(panel, comp, gbconstr);
GridBagConstraints gbc = gbl.getConstraints(comp);
assertEquals(GridBagConstraints.WEST, gbc.anchor);
assertEquals(0, gbc.insets.top);
assertEquals(3, gbc.insets.left);
assertEquals(0, gbc.insets.bottom);
assertEquals(3, gbc.insets.right);
assertEquals(2, gbc.gridx);
assertEquals(4, gbc.gridy);
assertEquals(0, gbc.weightx, 0.01);
assertEquals(0, gbc.weighty, 0.01);
assertEquals(0, gbc.ipadx);
assertEquals(0, gbc.ipady);
assertEquals(1, gbc.gridheight);
assertEquals(1, gbc.gridwidth);
}
@Test
public void testGridBagPanel_sevenParams() {
GridBagLayout gbl = new GridBagLayout();
JPanel panel = new JPanel(gbl);
JLabel comp = new JLabel("text");
final GridBagConstraints gbconstraints = GridBagUtils.createDefaultConstraints();
GridBagUtils.setAttributes(gbconstraints, "gridx=2, gridy=4, anchor=SOUTHEAST, weighty=1.3, insets.top=5");
GridBagUtils.addToPanel(panel, comp, gbconstraints);
GridBagConstraints gbc = gbl.getConstraints(comp);
assertEquals(GridBagConstraints.SOUTHEAST, gbc.anchor);
assertEquals(5, gbc.insets.top);
assertEquals(3, gbc.insets.left);
assertEquals(0, gbc.insets.bottom);
assertEquals(3, gbc.insets.right);
assertEquals(2, gbc.gridx);
assertEquals(4, gbc.gridy);
assertEquals(0, gbc.weightx, 0.01);
assertEquals(1.3, gbc.weighty, 0.01);
assertEquals(0, gbc.ipadx);
assertEquals(0, gbc.ipady);
assertEquals(1, gbc.gridheight);
assertEquals(1, gbc.gridwidth);
}
@Test
public void testGridBagPanel_eightParams() {
GridBagLayout gbl = new GridBagLayout();
JPanel panel = new JPanel(gbl);
JLabel comp = new JLabel("text");
final GridBagConstraints gbconstraints = GridBagUtils.createDefaultConstraints();
GridBagUtils.setAttributes(gbconstraints,
"gridx=2, gridy=4, anchor=SOUTHEAST, weighty=1.3, insets.top=5, gridwidth=3");
GridBagUtils.addToPanel(panel, comp, gbconstraints);
GridBagConstraints gbc = gbl.getConstraints(comp);
assertEquals(GridBagConstraints.SOUTHEAST, gbc.anchor);
assertEquals(5, gbc.insets.top);
assertEquals(3, gbc.insets.left);
assertEquals(0, gbc.insets.bottom);
assertEquals(3, gbc.insets.right);
assertEquals(2, gbc.gridx);
assertEquals(4, gbc.gridy);
assertEquals(0, gbc.weightx, 0.01);
assertEquals(1.3, gbc.weighty, 0.01);
assertEquals(0, gbc.ipadx);
assertEquals(0, gbc.ipady);
assertEquals(1, gbc.gridheight);
assertEquals(3, gbc.gridwidth);
}
@Test
public void testSetAttributes() {
GridBagConstraints gbc = new GridBagConstraints();
gbc = GridBagUtils.setAttributes(gbc, "gridx=RELATIVE,gridy=RELATIVE");
assertEquals(GridBagConstraints.RELATIVE, gbc.gridx);
assertEquals(GridBagConstraints.RELATIVE, gbc.gridy);
gbc = GridBagUtils.setAttributes(gbc, "gridx=12, gridy=34");
assertEquals(12, gbc.gridx);
assertEquals(34, gbc.gridy);
gbc = GridBagUtils.setAttributes(gbc, "gridwidth=REMAINDER,gridheight=REMAINDER");
assertEquals(GridBagConstraints.REMAINDER, gbc.gridwidth);
assertEquals(GridBagConstraints.REMAINDER, gbc.gridheight);
gbc = GridBagUtils.setAttributes(gbc, "gridwidth=RELATIVE,gridheight=RELATIVE");
assertEquals(GridBagConstraints.RELATIVE, gbc.gridwidth);
assertEquals(GridBagConstraints.RELATIVE, gbc.gridheight);
gbc = GridBagUtils.setAttributes(gbc, "gridwidth=56, gridheight=78");
assertEquals(56, gbc.gridwidth);
assertEquals(78, gbc.gridheight);
gbc = GridBagUtils.setAttributes(gbc, "weightx=0.4, weighty=0.6");
assertEquals(0.4, gbc.weightx, 1e-12);
assertEquals(0.6, gbc.weighty, 1e-12);
gbc = GridBagUtils.setAttributes(gbc, "anchor=CENTER");
assertEquals(GridBagConstraints.CENTER, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=NORTH");
assertEquals(GridBagConstraints.NORTH, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=NORTHEAST");
assertEquals(GridBagConstraints.NORTHEAST, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=EAST");
assertEquals(GridBagConstraints.EAST, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=SOUTHEAST");
assertEquals(GridBagConstraints.SOUTHEAST, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=SOUTH");
assertEquals(GridBagConstraints.SOUTH, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=SOUTHWEST");
assertEquals(GridBagConstraints.SOUTHWEST, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=WEST");
assertEquals(GridBagConstraints.WEST, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=NORTHWEST");
assertEquals(GridBagConstraints.NORTHWEST, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "anchor=10");
assertEquals(10, gbc.anchor);
gbc = GridBagUtils.setAttributes(gbc, "fill=NONE");
assertEquals(GridBagConstraints.NONE, gbc.fill);
gbc = GridBagUtils.setAttributes(gbc, "fill=HORIZONTAL");
assertEquals(GridBagConstraints.HORIZONTAL, gbc.fill);
gbc = GridBagUtils.setAttributes(gbc, "fill=VERTICAL");
assertEquals(GridBagConstraints.VERTICAL, gbc.fill);
gbc = GridBagUtils.setAttributes(gbc, "fill=BOTH");
assertEquals(GridBagConstraints.BOTH, gbc.fill);
gbc = GridBagUtils.setAttributes(gbc, "fill=1");
assertEquals(1, gbc.fill);
gbc = GridBagUtils.setAttributes(gbc, "insets.bottom=10,insets.left=11,insets.right=12,insets.top=13");
assertEquals(10, gbc.insets.bottom);
assertEquals(11, gbc.insets.left);
assertEquals(12, gbc.insets.right);
assertEquals(13, gbc.insets.top);
gbc = GridBagUtils.setAttributes(gbc, "ipadx=6,ipady=7");
assertEquals(6, gbc.ipadx);
assertEquals(7, gbc.ipady);
assertEquals(12, gbc.gridx);
assertEquals(34, gbc.gridy);
assertEquals(56, gbc.gridwidth);
assertEquals(78, gbc.gridheight);
assertEquals(0.4, gbc.weightx, 1e-12);
assertEquals(0.6, gbc.weighty, 1e-12);
assertEquals(10, gbc.anchor);
assertEquals(1, gbc.fill);
assertEquals(10, gbc.insets.bottom);
assertEquals(11, gbc.insets.left);
assertEquals(12, gbc.insets.right);
assertEquals(13, gbc.insets.top);
assertEquals(6, gbc.ipadx);
assertEquals(7, gbc.ipady);
try {
gbc = GridBagUtils.setAttributes(gbc, null);
} catch (IllegalArgumentException e) {
fail("IllegalArgumentException not expected");
}
try {
gbc = GridBagUtils.setAttributes(gbc, "");
} catch (IllegalArgumentException e) {
fail("IllegalArgumentException not expected");
}
try {
gbc = GridBagUtils.setAttributes(gbc, "ipadx");
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
}
try {
gbc = GridBagUtils.setAttributes(gbc, "ipadx=");
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
}
try {
gbc = GridBagUtils.setAttributes(gbc, "ipadx=,");
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
}
try {
gbc = GridBagUtils.setAttributes(gbc, "=9");
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
}
try {
gbc = GridBagUtils.setAttributes(gbc, "=");
fail("IllegalArgumentException expected");
} catch (IllegalArgumentException e) {
}
}
}
| 9,962 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BoundsInputPanelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/BoundsInputPanelTest.java | package org.esa.snap.ui;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Marco Peters
*/
public class BoundsInputPanelTest {
@Test
public void testDecimalFormatter() throws Exception {
DecimalFormatter formatter = BoundsInputPanel.DECIMAL_FORMATTER;
assertEquals("0.003", formatter.valueToString(0.003));
assertEquals("0.000001", formatter.valueToString(0.000001));
assertEquals("0.00000102", formatter.valueToString(0.00000102));
assertEquals("123456789.0", formatter.valueToString(123456789));
assertEquals("123456789.12345", formatter.valueToString(123456789.12345));
}
} | 665 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DemSelectorTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/DemSelectorTest.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;
import org.esa.snap.core.param.ParamChangeEvent;
import org.esa.snap.core.param.ParamChangeListener;
import org.esa.snap.core.param.ParamValidateException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Description of DemSelectorTest
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class DemSelectorTest {
private DemSelector _demSelector;
private MyParamChangeListener _paramChangeListener;
@Before
public void setUp() throws Exception {
_paramChangeListener = new MyParamChangeListener();
_demSelector = new DemSelector(_paramChangeListener);
}
@Test
public void test_UsingExternalDEM_IsDefault() {
assertTrue(_demSelector.isUsingExternalDem());
}
@Test
public void test_SetUsingExternalDem() throws ParamValidateException {
_demSelector.setUsingExternalDem(true);
assertTrue(_demSelector.isUsingExternalDem());
assertFalse(_demSelector.isUsingProductDem());
assertEquals("", _paramChangeListener.getCallString());
}
@Test
public void test_SetUsingProductDem() throws ParamValidateException {
_demSelector.setUsingProductDem(true);
assertTrue(_demSelector.isUsingProductDem());
assertFalse(_demSelector.isUsingExternalDem());
assertEquals("useProductDem|useExternalDem|", _paramChangeListener.getCallString());
}
@Test
public void test_ToggleUsingDem() throws ParamValidateException {
_demSelector.setUsingProductDem(true);
_demSelector.setUsingExternalDem(true);
assertTrue(_demSelector.isUsingExternalDem());
assertFalse(_demSelector.isUsingProductDem());
assertEquals("useProductDem|useExternalDem|useExternalDem|useProductDem|", _paramChangeListener.getCallString());
}
private static class MyParamChangeListener implements ParamChangeListener {
StringBuilder callString = new StringBuilder();
public String getCallString() {
return callString.toString();
}
public void parameterValueChanged(ParamChangeEvent event) {
callString.append(event.getParameter().getName());
callString.append("|");
}
}
}
| 3,014 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RGBImageProfilePaneTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/RGBImageProfilePaneTest.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;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.RGBImageProfile;
import org.esa.snap.core.util.math.Range;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Thomas Storm
*/
public class RGBImageProfilePaneTest {
@Test
public void testSelectProfile_1() {
RGBImageProfile[] rgbImageProfiles = new RGBImageProfile[]{
new RGBImageProfile("p1", new String[]{"", "", ""}, new String[]{"matches", "not at", "all"}),
new RGBImageProfile("p2", new String[]{"", "", ""}, new String[]{"some_different_type", "*name_*3", null}),
new RGBImageProfile("p3", new String[]{"", "", ""}, new String[]{"*me_ty*", "*name_*3", null}),
new RGBImageProfile("p4", new String[]{"", "", ""}, new String[]{"*me_ty*", "*name_*3", "*s some*"}),
};
Product product = new Product("some_name_123", "some_type_123", 1, 1);
product.setDescription("This is some description text.");
RGBImageProfile profile = RGBImageProfilePane.findProfileForProductPattern(rgbImageProfiles, product);
assertNotNull(profile);
assertSame(rgbImageProfiles[3], profile); // all patterns match
}
@Test
public void testSelectProfile_2() {
RGBImageProfile[] rgbImageProfiles = new RGBImageProfile[]{
new RGBImageProfile("p1", new String[]{"", "", ""}, new String[]{"matches", "not at", "all"}),
new RGBImageProfile("p2", new String[]{"", "", ""}, new String[]{"some_different_type", "*name_*3", null}),
new RGBImageProfile("p3", new String[]{"", "", ""}, new String[]{"*me_ty*", null, null}),
new RGBImageProfile("p4", new String[]{"", "", ""}, new String[]{null, "*name_*3", "*s some*"}),
};
Product product = new Product("some_name_123", "some_type_123", 1, 1);
product.setDescription("This is some description text.");
RGBImageProfile profile = RGBImageProfilePane.findProfileForProductPattern(rgbImageProfiles, product);
assertNotNull(profile);
assertSame(rgbImageProfiles[2], profile); // type matches
}
@Test
public void testSelectProfile_3() {
RGBImageProfile[] rgbImageProfiles = new RGBImageProfile[]{
new RGBImageProfile("p1", new String[]{"", "", ""}, new String[]{"matches", "not at", "all"}),
new RGBImageProfile("p2", new String[]{"", "", ""}, new String[]{"some_different_type", "*name_*3", null}),
new RGBImageProfile("p3", new String[]{"", "", ""}, new String[]{null, "*name_*3", null}),
new RGBImageProfile("p4", new String[]{"", "", ""}, new String[]{null, "*name_*3", "*s some*"}),
};
Product product = new Product("some_name_123", "some_type_123", 1, 1);
product.setDescription("This is some description text.");
RGBImageProfile profile = RGBImageProfilePane.findProfileForProductPattern(rgbImageProfiles, product);
assertNotNull(profile);
assertSame(rgbImageProfiles[3], profile); // name and description match
}
@Test
public void testSelectProfile_4() {
RGBImageProfile[] rgbImageProfiles = new RGBImageProfile[]{
new RGBImageProfile("p1", new String[]{"", "", ""}, new String[]{"matches", "not at", "all"}),
new RGBImageProfile("p2", new String[]{"", "", ""}, new String[]{"some_different_type", "*name_*3", null}),
new RGBImageProfile("p3", new String[]{"", "", ""}, new String[]{"strange type", "*name_*3", null}),
new RGBImageProfile("p4", new String[]{"", "", ""}, new String[]{"strange type", "*name_*3", "*s some*"}),
};
Product product = new Product("some_name_123", "some_type_123", 1, 1);
product.setDescription("This is some description text.");
RGBImageProfile profile = RGBImageProfilePane.findProfileForProductPattern(rgbImageProfiles, product);
assertNotNull(profile);
assertSame(rgbImageProfiles[3], profile); // name and description match
}
@Test
public void testSelectProfile_5() {
RGBImageProfile[] rgbImageProfiles = new RGBImageProfile[]{
new RGBImageProfile("p1", new String[]{"", "", ""}, new String[]{"matches", "not at", "all"}),
new RGBImageProfile("p2", new String[]{"", "", ""}, new String[]{"some_different_type", "*name_*3", null}),
new RGBImageProfile("p3", new String[]{"", "", ""}, new String[]{"*me_ty*", "*name_*3", null}),
new RGBImageProfile("p4", new String[]{"", "", ""}, new String[]{"*me_ty*", "*name_*3", null}),
};
Product product = new Product("some_name_123", "some_type_123", 1, 1);
product.setDescription("This is some description text.");
RGBImageProfile profile = RGBImageProfilePane.findProfileForProductPattern(rgbImageProfiles, product);
assertNotNull(profile);
assertSame(rgbImageProfiles[2], profile); // equal, so earlier profile is chosen
}
@Test
public void testSelectProfile_6() {
RGBImageProfile[] rgbImageProfiles = new RGBImageProfile[0];
Product product = new Product("some_name_123", "some_type_123", 1, 1);
product.setDescription("This is some description text.");
RGBImageProfile profile = RGBImageProfilePane.findProfileForProductPattern(rgbImageProfiles, product);
assertNull(profile);
}
// Added by nf after NPE with Landsat 5 products
@Test
public void testNoDescriptionSet() {
RGBImageProfile[] rgbImageProfiles = new RGBImageProfile[]{
new RGBImageProfile("p1", new String[]{"", "", ""}, new String[]{"matches", "not at", "all"}),
};
Product product = new Product("some_name_123", "some_type_123", 1, 1);
product.setDescription(null);
RGBImageProfile profile = RGBImageProfilePane.findProfileForProductPattern(rgbImageProfiles, product);
assertNotNull(profile);
}
@Test
public void testRangeComponents_constructor() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
assertFalse(components.fixedRangeCheckBox.isSelected());
assertFalse(components.minText.isEnabled());
assertEquals("", components.minText.getText());
assertFalse(components.minLabel.isEnabled());
assertFalse(components.maxText.isEnabled());
assertEquals("", components.maxText.getText());
assertFalse(components.maxLabel.isEnabled());
}
@Test
public void testRangeComponents_enableMinMax() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
components.enableMinMax(true);
// changing this component triggers the actio - so it should not be altered during the call tb 2021-04-28
assertFalse(components.fixedRangeCheckBox.isSelected());
assertTrue(components.minText.isEnabled());
assertEquals("", components.minText.getText());
assertTrue(components.minLabel.isEnabled());
assertTrue(components.maxText.isEnabled());
assertEquals("", components.maxText.getText());
assertTrue(components.maxLabel.isEnabled());
}
@Test
public void testRangeComponents_setRange_validRange() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
components.set(new Range(0.87, 11.3));
assertTrue(components.fixedRangeCheckBox.isSelected());
assertTrue(components.minText.isEnabled());
assertEquals("0.87", components.minText.getText());
assertTrue(components.minLabel.isEnabled());
assertTrue(components.maxText.isEnabled());
assertEquals("11.3", components.maxText.getText());
assertTrue(components.maxLabel.isEnabled());
}
@Test
public void testRangeComponents_setRange_rangePartiallyFilled() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
components.set(new Range(0.88, Double.NaN));
assertTrue(components.fixedRangeCheckBox.isSelected());
assertTrue(components.minText.isEnabled());
assertEquals("0.88", components.minText.getText());
assertTrue(components.minLabel.isEnabled());
assertTrue(components.maxText.isEnabled());
assertEquals("", components.maxText.getText());
assertTrue(components.maxLabel.isEnabled());
components.set(new Range(Double.NaN, 9.8865));
assertTrue(components.fixedRangeCheckBox.isSelected());
assertTrue(components.minText.isEnabled());
assertEquals("", components.minText.getText());
assertTrue(components.minLabel.isEnabled());
assertTrue(components.maxText.isEnabled());
assertEquals("9.8865", components.maxText.getText());
assertTrue(components.maxLabel.isEnabled());
}
@Test
public void testRangeComponents_setRange_invalidRange() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
components.set(new Range(Double.NaN, Double.NaN));
assertFalse(components.fixedRangeCheckBox.isSelected());
assertFalse(components.minText.isEnabled());
assertEquals("", components.minText.getText());
assertFalse(components.minLabel.isEnabled());
assertFalse(components.maxText.isEnabled());
assertEquals("", components.maxText.getText());
assertFalse(components.maxLabel.isEnabled());
}
@Test
public void testRangeComponents_getRange() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
components.fixedRangeCheckBox.setSelected(true);
components.minText.setText(" -1.76");
components.maxText.setText(" 2.0076 ");
final Range range = components.getRange();
assertEquals(-1.76, range.getMin(), 1e-8);
assertEquals(2.0076, range.getMax(), 1e-8);
}
@Test
public void testRangeComponents_getRange_unselected() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
components.fixedRangeCheckBox.setSelected(false);
components.minText.setText(" -1.76");
components.maxText.setText(" 2.0076 ");
final Range range = components.getRange();
assertEquals(Double.NaN, range.getMin(), 1e-8);
assertEquals(Double.NaN, range.getMax(), 1e-8);
}
@Test
public void testRangeComponents_getRange_emptyFields() {
final RGBImageProfilePane.RangeComponents components = new RGBImageProfilePane.RangeComponents();
components.fixedRangeCheckBox.setSelected(true);
components.minText.setText("");
components.maxText.setText("6.8");
Range range = components.getRange();
assertEquals(Double.NaN, range.getMin(), 1e-8);
assertEquals(6.8, range.getMax(), 1e-8);
components.minText.setText("0.004");
components.maxText.setText("");
range = components.getRange();
assertEquals(0.004, range.getMin(), 1e-8);
assertEquals(Double.NaN, range.getMax(), 1e-8);
}
}
| 12,143 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorCodesTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/color/ColorCodesTest.java | package org.esa.snap.ui.color;
import org.junit.Test;
import java.awt.Color;
import java.util.List;
import static org.junit.Assert.assertEquals;
/**
* Created by Norman on 26.03.2015.
*/
public class ColorCodesTest {
@Test
public void testNameListOrder() {
List<String> names = ColorCodes.getNames();
assertEquals(340, names.size());
assertEquals("Black", names.get(0));
assertEquals("Night", names.get(1));
assertEquals("Gunmetal", names.get(2));
// ...
assertEquals("Sea Shell", names.get(337));
assertEquals("Milk White", names.get(338));
assertEquals("White", names.get(339));
}
@Test
public void testColorMap() {
assertEquals(new Color(0, 0, 0), ColorCodes.getColor("Black"));
assertEquals(new Color(12, 9, 10), ColorCodes.getColor("Night"));
assertEquals(new Color(44, 53, 57), ColorCodes.getColor("Gunmetal"));
// ...
assertEquals(new Color(255, 245, 238), ColorCodes.getColor("Sea Shell"));
assertEquals(new Color(254, 252, 255), ColorCodes.getColor("Milk White"));
assertEquals(new Color(255, 255, 255), ColorCodes.getColor("White"));
}
}
| 1,210 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorSelectionComponentRunner.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/color/ColorSelectionComponentRunner.java | package org.esa.snap.ui.color;
import javax.swing.AbstractListModel;
import javax.swing.Icon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class ColorSelectionComponentRunner {
public static void main(String[] args) {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
DefaultTableModel dm = new DefaultTableModel(new Object[][]{
{"C1", Color.RED},
{"C2", Color.GREEN},
{"C3", Color.BLUE}},
new String[]{"Name", "Color"}) {
@Override
public Class<?> getColumnClass(int columnIndex) {
return columnIndex == 0 ? String.class : Color.class;
}
};
JTable table = new JTable(dm);
ColorTableCellEditor editor = new ColorTableCellEditor();
ColorTableCellRenderer renderer = new ColorTableCellRenderer();
table.setDefaultEditor(Color.class, editor);
table.setDefaultRenderer(Color.class, renderer);
table.getModel().addTableModelListener(e -> System.out.println("e = " + e));
ColorComboBox colorComboBox1 = new ColorComboBox(Color.YELLOW);
ColorComboBox colorComboBox2 = new ColorComboBox(Color.GREEN);
colorComboBox2.setColorChooserPanelFactory(CustomColorChooserPanel::new);
JFrame frame = new JFrame("Color Selection Test");
frame.setLocation(200, 100);
frame.add(colorComboBox1, BorderLayout.NORTH);
frame.add(new JScrollPane(table), BorderLayout.CENTER);
frame.add(colorComboBox2, BorderLayout.SOUTH);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static List<ColorItem> getColorItems() {
List<ColorItem> colors = new ArrayList<>();
List<String> names = ColorCodes.getNames();
colors.addAll(names.stream().map(name -> new ColorItem(name, ColorCodes.getColor(name))).collect(Collectors.toList()));
return colors;
}
static class ColorItem {
String name;
Color color;
public ColorItem(String name, Color color) {
this.name = name;
this.color = color;
}
}
private static class ColorItemListCellRenderer extends JLabel implements ListCellRenderer<ColorItem> {
@Override
public Component getListCellRendererComponent(JList<? extends ColorItem> list, ColorItem value, int index, boolean isSelected, boolean cellHasFocus) {
setIcon(new ColorItemIcon(value));
setText(value.name);
setBorder(isSelected ? new LineBorder(Color.ORANGE, 2) : new LineBorder(Color.WHITE, 2));
return this;
}
private static class ColorItemIcon implements Icon {
private final ColorItem value;
public ColorItemIcon(ColorItem value) {
this.value = value;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
g.setColor(value.color);
g.fillRect(0, 0, getIconWidth(), getIconHeight());
}
@Override
public int getIconWidth() {
return 32;
}
@Override
public int getIconHeight() {
return 16;
}
}
}
private static class CustomColorChooserPanel extends ColorChooserPanel {
public CustomColorChooserPanel(Color selectedColor) {
super(selectedColor);
}
@Override
protected JComponent createColorPicker() {
List<ColorItem> colors = getColorItems();
JList<ColorItem> view = new JList<>(new AbstractListModel<ColorItem>() {
@Override
public int getSize() {
return colors.size();
}
@Override
public ColorItem getElementAt(int index) {
return colors.get(index);
}
});
view.setCellRenderer(new ColorItemListCellRenderer());
view.addListSelectionListener(e -> {
setSelectedColor(view.getSelectedValue().color);
});
return new JScrollPane(view);
}
}
}
| 5,116 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultLayerSourceDescriptorTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/layer/DefaultLayerSourceDescriptorTest.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.binding.PropertySet;
import com.bc.ceres.core.ServiceRegistry;
import com.bc.ceres.core.ServiceRegistryManager;
import com.bc.ceres.glayer.CollectionLayer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.annotations.LayerTypeMetadata;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
public class DefaultLayerSourceDescriptorTest {
private static SimpleTestLayerType layerType = new SimpleTestLayerType();
@BeforeClass
public static void setUp() {
final ServiceRegistryManager serviceRegistryManager = ServiceRegistryManager.getInstance();
final ServiceRegistry<LayerType> registry = serviceRegistryManager.getServiceRegistry(LayerType.class);
registry.addService(layerType);
}
@AfterClass
public static void tearDown() {
final ServiceRegistryManager serviceRegistryManager = ServiceRegistryManager.getInstance();
final ServiceRegistry<LayerType> registry = serviceRegistryManager.getServiceRegistry(LayerType.class);
registry.removeService(layerType);
}
@Test
public void testWithLayerSource() {
final String id = "wms-layer-source";
final String name = "Image from Web Mapping Server (WMS)";
final String description = "Retrieves images from a Web Mapping Server (WMS)";
DefaultLayerSourceDescriptor descriptor = new DefaultLayerSourceDescriptor(id, name, description,
DummyLayerSource.class);
assertEquals("wms-layer-source", descriptor.getId());
assertEquals("Image from Web Mapping Server (WMS)", descriptor.getName());
assertEquals("Retrieves images from a Web Mapping Server (WMS)", descriptor.getDescription());
assertNull(descriptor.getLayerType());
final LayerSource layerSource = descriptor.createLayerSource();
assertNotNull(layerSource);
assertTrue(layerSource instanceof DummyLayerSource);
}
@Test
public void testWithLayerType() {
final String id = "type-layer-source";
final String name = "Some simple layer";
final String description = "A simple layer without configuration.";
DefaultLayerSourceDescriptor descriptor = new DefaultLayerSourceDescriptor(id, name, description,
SimpleTestLayerType.class.getName());
assertEquals("type-layer-source", descriptor.getId());
assertEquals("Some simple layer", descriptor.getName());
assertEquals("A simple layer without configuration.", descriptor.getDescription());
assertNotNull(descriptor.getLayerType());
assertNotNull(descriptor.getLayerType() instanceof SimpleTestLayerType);
final LayerSource layerSource = descriptor.createLayerSource();
assertNotNull(layerSource);
}
@LayerTypeMetadata(name = "SimpleTestLayerType")
private static class SimpleTestLayerType extends LayerType {
@Override
public boolean isValidFor(LayerContext ctx) {
return true;
}
@Override
public Layer createLayer(LayerContext ctx, PropertySet configuration) {
return new CollectionLayer();
}
@Override
public PropertySet createLayerConfig(LayerContext ctx) {
return new PropertyContainer();
}
}
private static class DummyLayerSource implements LayerSource {
public DummyLayerSource() {
}
@Override
public boolean isApplicable(LayerSourcePageContext pageContext) {
return false;
}
@Override
public boolean hasFirstPage() {
return false;
}
@Override
public AbstractLayerSourceAssistantPage getFirstPage(LayerSourcePageContext pageContext) {
return null;
}
@Override
public boolean canFinish(LayerSourcePageContext pageContext) {
return false;
}
@Override
public boolean performFinish(LayerSourcePageContext pageContext) {
return false;
}
@Override
public void cancel(LayerSourcePageContext pageContext) {
}
}
}
| 5,241 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleFeatureShapeFigureTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/SimpleFeatureShapeFigureTest.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 com.bc.ceres.swing.figure.Figure;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.geom.GeometryCollection;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.LineString;
import org.locationtech.jts.geom.LinearRing;
import org.locationtech.jts.geom.MultiLineString;
import org.locationtech.jts.geom.MultiPoint;
import org.locationtech.jts.geom.MultiPolygon;
import org.locationtech.jts.geom.Point;
import org.locationtech.jts.geom.Polygon;
import junit.framework.TestCase;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.transform.MathTransform2D;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import static org.esa.snap.core.datamodel.PlainFeatureFactory.createPlainFeature;
import static org.esa.snap.core.datamodel.PlainFeatureFactory.createPlainFeatureType;
public class SimpleFeatureShapeFigureTest {
private final GeometryFactory gf = new GeometryFactory();
private SceneTransformProvider sceneTransformProvider;
@Before
public void setUp() {
sceneTransformProvider = new SceneTransformProvider() {
@Override
public MathTransform2D getModelToSceneTransform() {
return MathTransform2D.IDENTITY;
}
@Override
public MathTransform2D getSceneToModelTransform() {
return MathTransform2D.IDENTITY;
}
};
}
@Test
public void testSpecificGeometryType() {
SimpleFeatureType sft = createPlainFeatureType("Polygon", Polygon.class, DefaultGeographicCRS.WGS84);
Polygon polygon = createPolygon();
SimpleFeature simpleFeature = createPlainFeature(sft, "_1", polygon, "");
SimpleFeatureShapeFigure shapeFigure = new SimpleFeatureShapeFigure(simpleFeature, sceneTransformProvider, new DefaultFigureStyle());
Assert.assertEquals(polygon, shapeFigure.getGeometry());
Assert.assertNotNull(shapeFigure.getShape());
Assert.assertEquals(Figure.Rank.AREA, shapeFigure.getRank());
}
@Test
public void testMixedGeometries_2() {
SimpleFeatureType sft = createPlainFeatureType("Geometry", Geometry.class, DefaultGeographicCRS.WGS84);
Geometry geometry;
SimpleFeature feature;
SimpleFeatureShapeFigure figure;
geometry = createPoint();
feature = createPlainFeature(sft, "_4", geometry, "");
figure = new SimpleFeatureShapeFigure(feature, sceneTransformProvider, new DefaultFigureStyle());
Assert.assertEquals(geometry, figure.getGeometry());
Assert.assertNotNull(figure.getShape());
Assert.assertEquals(Figure.Rank.POINT, figure.getRank());
geometry = createGeometryCollection();
feature = createPlainFeature(sft, "_5", geometry, "");
figure = new SimpleFeatureShapeFigure(feature, sceneTransformProvider, new DefaultFigureStyle());
Assert.assertEquals(geometry, figure.getGeometry());
Assert.assertNotNull(figure.getShape());
Assert.assertEquals(Figure.Rank.NOT_SPECIFIED, figure.getRank());
}
@Test
public void testMixedGeometries_1() {
SimpleFeatureType sft = createPlainFeatureType("Geometry", Geometry.class, DefaultGeographicCRS.WGS84);
Geometry geometry;
SimpleFeature feature;
SimpleFeatureShapeFigure figure;
geometry = createPolygon();
feature = createPlainFeature(sft, "_1", geometry, "");
figure = new SimpleFeatureShapeFigure(feature, sceneTransformProvider, new DefaultFigureStyle());
Assert.assertEquals(geometry, figure.getGeometry());
Assert.assertNotNull(figure.getShape());
Assert.assertEquals(Figure.Rank.AREA, figure.getRank());
geometry = createLinearRing();
feature = createPlainFeature(sft, "_2", geometry, "");
figure = new SimpleFeatureShapeFigure(feature, sceneTransformProvider, new DefaultFigureStyle());
Assert.assertEquals(geometry, figure.getGeometry());
Assert.assertNotNull(figure.getShape());
Assert.assertEquals(Figure.Rank.LINE, figure.getRank());
geometry = createLineString();
feature = createPlainFeature(sft, "_3", geometry, "");
figure = new SimpleFeatureShapeFigure(feature, sceneTransformProvider, new DefaultFigureStyle());
Assert.assertEquals(geometry, figure.getGeometry());
Assert.assertNotNull(figure.getShape());
Assert.assertEquals(Figure.Rank.LINE, figure.getRank());
}
@Test
public void testRank() {
Assert.assertEquals(Figure.Rank.POINT, SimpleFeatureShapeFigure.getRank(createPoint()));
Assert.assertEquals(Figure.Rank.POINT, SimpleFeatureShapeFigure.getRank(createMultiPoint()));
Assert.assertEquals(Figure.Rank.LINE, SimpleFeatureShapeFigure.getRank(createLineString()));
Assert.assertEquals(Figure.Rank.LINE, SimpleFeatureShapeFigure.getRank(createLinearRing()));
Assert.assertEquals(Figure.Rank.LINE, SimpleFeatureShapeFigure.getRank(createMultiLineString()));
Assert.assertEquals(Figure.Rank.AREA, SimpleFeatureShapeFigure.getRank(createPolygon()));
Assert.assertEquals(Figure.Rank.AREA, SimpleFeatureShapeFigure.getRank(createMultiPolygon()));
Assert.assertEquals(Figure.Rank.NOT_SPECIFIED, SimpleFeatureShapeFigure.getRank(createGeometryCollection()));
}
private Point createPoint() {
return gf.createPoint(new Coordinate(0, 0));
}
private LineString createLineString() {
return gf.createLineString(new Coordinate[]{
new Coordinate(0, 0),
new Coordinate(1, 0),
new Coordinate(1, 1),
new Coordinate(0, 1),
});
}
private LinearRing createLinearRing() {
return gf.createLinearRing(new Coordinate[]{
new Coordinate(0, 0),
new Coordinate(1, 0),
new Coordinate(1, 1),
new Coordinate(0, 1),
new Coordinate(0, 0),
});
}
private Polygon createPolygon() {
return gf.createPolygon(gf.createLinearRing(new Coordinate[]{
new Coordinate(0, 0),
new Coordinate(1, 0),
new Coordinate(0, 1),
new Coordinate(0, 0),
}), null);
}
private MultiPoint createMultiPoint() {
return gf.createMultiPoint(new Point[0]);
}
private MultiPolygon createMultiPolygon() {
return gf.createMultiPolygon(new Polygon[0]);
}
private MultiLineString createMultiLineString() {
return gf.createMultiLineString(new LineString[0]);
}
private GeometryCollection createGeometryCollection() {
return gf.createGeometryCollection(new Geometry[0]);
}
}
| 7,885 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataCollectionLayerTypeTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/VectorDataCollectionLayerTypeTest.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.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.junit.Test;
import static org.junit.Assert.*;
public class VectorDataCollectionLayerTypeTest {
@Test
public void registry() {
final VectorDataCollectionLayerType byClass = LayerTypeRegistry.getLayerType(
VectorDataCollectionLayerType.class);
final LayerType byName = LayerTypeRegistry.getLayerType(VectorDataCollectionLayerType.class.getName());
assertTrue(byClass != null);
assertSame(byClass, byName);
}
}
| 1,322 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
VectorDataLayerTypeTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/VectorDataLayerTypeTest.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.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.junit.Test;
import static org.junit.Assert.*;
public class VectorDataLayerTypeTest {
@Test
public void registry() {
final VectorDataLayerType byClass = LayerTypeRegistry.getLayerType(VectorDataLayerType.class);
final LayerType byName = LayerTypeRegistry.getLayerType(VectorDataLayerType.class.getName());
assertTrue(byClass != null);
assertSame(byClass, byName);
}
}
| 1,265 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProductSceneViewTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/ProductSceneViewTest.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.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.VirtualBand;
import org.esa.snap.core.util.DefaultPropertyMap;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.awt.geom.AffineTransform;
import static org.esa.snap.core.util.Debug.assertTrue;
import static org.junit.Assert.*;
public class ProductSceneViewTest {
private VirtualBand r;
private VirtualBand g;
private VirtualBand b;
@Before
public void setUp() throws Exception {
final Product product = new Product("x", "y", 2, 3);
r = new VirtualBand("r", ProductData.TYPE_FLOAT32, 2, 3, "0");
g = new VirtualBand("g", ProductData.TYPE_FLOAT32, 2, 3, "0");
b = new VirtualBand("b", ProductData.TYPE_FLOAT32, 2, 3, "0");
product.addBand(r);
product.addBand(g);
product.addBand(b);
r.ensureRasterData();
g.ensureRasterData();
b.ensureRasterData();
}
@After
public void tearDown() throws Exception {
r = null;
g = null;
b = null;
}
@Test
public void testIsRGB() {
ProductSceneView view;
view = new ProductSceneView(new ProductSceneImage(r, new DefaultPropertyMap(), ProgressMonitor.NULL));
assertFalse(view.isRGB());
view = new ProductSceneView(new ProductSceneImage("RGB", r, g, b, new DefaultPropertyMap(), ProgressMonitor.NULL));
assertTrue(view.isRGB());
}
@Test
public void testDispose() {
final ProductSceneView view = new ProductSceneView(new ProductSceneImage(r, new DefaultPropertyMap(), ProgressMonitor.NULL));
view.dispose();
assertNull(view.getSceneImage());
}
@Test
public void testAffineTransformReplacesManualCalculation() {
double modelOffsetX = 37.8;
double modelOffsetY = -54.1;
double viewScale = 2.5;
final AffineTransform transform = new AffineTransform();
transform.scale(viewScale, viewScale);
transform.translate(-modelOffsetX, -modelOffsetY);
double modelX = 10.4;
double modelY = 2.9;
double viewX = (modelX - modelOffsetX) * viewScale;
double viewY = (modelY - modelOffsetY) * viewScale;
final double[] result = new double[2];
transform.transform(new double[]{modelX, modelY}, 0, result, 0, 1);
assertEquals(viewX, result[0], 1e-10);
assertEquals(viewY, result[1], 1e-10);
}
}
| 3,331 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleFeaturePointFigureTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/SimpleFeaturePointFigureTest.java | package org.esa.snap.ui.product;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.locationtech.jts.geom.Coordinate;
import org.locationtech.jts.geom.GeometryFactory;
import org.locationtech.jts.geom.Point;
import org.esa.snap.core.datamodel.SceneTransformProvider;
import org.esa.snap.core.transform.MathTransform2D;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.feature.simple.SimpleFeatureType;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import static org.junit.Assert.assertEquals;
/**
* @author Norman
*/
public class SimpleFeaturePointFigureTest {
private SceneTransformProvider sceneTransformProvider;
@Test
public void testScaling() throws Exception {
SimpleFeatureType type = createShipTrackFeatureType();
SimpleFeature feature = createFeature(type, 1, 53.1F, 13.2F, 0.5);
sceneTransformProvider = new SceneTransformProvider() {
@Override
public MathTransform2D getModelToSceneTransform() {
return MathTransform2D.IDENTITY;
}
@Override
public MathTransform2D getSceneToModelTransform() {
return MathTransform2D.IDENTITY;
}
};
SimpleFeaturePointFigure figure = new SimpleFeaturePointFigure(feature, sceneTransformProvider, new DefaultFigureStyle());
Coordinate coordinate = figure.getGeometry().getCoordinate();
assertEquals(13.2F, coordinate.x, 1e-10);
assertEquals(53.1F, coordinate.y, 1e-10);
boolean closeTo = figure.isCloseTo(new Point2D.Double(13.2F, 53.1F), new AffineTransform());
assertEquals(true, closeTo);
}
private static SimpleFeatureType createShipTrackFeatureType() {
SimpleFeatureTypeBuilder ftb = new SimpleFeatureTypeBuilder();
DefaultGeographicCRS crs = DefaultGeographicCRS.WGS84;
ftb.setCRS(crs);
ftb.setName("ShipTrack");
ftb.add("index", Integer.class);
ftb.add("point", Point.class, crs);
ftb.add("data", Double.class);
ftb.setDefaultGeometry("point");
return ftb.buildFeatureType();
}
private static SimpleFeature createFeature(SimpleFeatureType type, int index, float lat, float lon, double data) {
SimpleFeatureBuilder fb = new SimpleFeatureBuilder(type);
GeometryFactory gf = new GeometryFactory();
fb.add(index);
fb.add(gf.createPoint(new Coordinate(lon, lat)));
fb.add(data);
return fb.buildFeature(Long.toHexString(System.nanoTime()));
}
}
| 2,801 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleFeatureFigureFactoryTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/SimpleFeatureFigureFactoryTest.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.PlainFeatureFactory;
import org.geotools.feature.simple.SimpleFeatureBuilder;
import org.geotools.feature.simple.SimpleFeatureTypeBuilder;
import org.junit.Before;
import org.junit.Test;
import org.opengis.feature.simple.SimpleFeature;
import static org.junit.Assert.*;
/**
* @author Tonio Fincke
* @author Thomas Storm
*/
public class SimpleFeatureFigureFactoryTest {
private SimpleFeature simpleFeature;
@Before
public void setUp() throws Exception {
final SimpleFeatureTypeBuilder sftb = new SimpleFeatureTypeBuilder();
sftb.setName("someName");
sftb.add(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, String.class);
SimpleFeatureBuilder sfb = new SimpleFeatureBuilder(sftb.buildFeatureType());
simpleFeature = sfb.buildFeature("someId");
}
@Test
public void testGetStyleCss_WithAdditionalStyles() throws Exception {
simpleFeature.setAttribute(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, "fill:120,120,120;stroke:0,10,0");
final String styleCss = SimpleFeatureFigureFactory.getStyleCss(simpleFeature, "symbol:pin");
assertEquals("fill:120,120,120;stroke:0,10,0;symbol:pin", styleCss);
}
@Test
public void testGetStyleCss_WithOverride() throws Exception {
simpleFeature.setAttribute(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, "symbol:cross;fill:100,100,100");
final String styleCss = SimpleFeatureFigureFactory.getStyleCss(simpleFeature, "symbol:pin;fill:0,0,0");
assertEquals("symbol:cross;fill:100,100,100", styleCss);
}
@Test
public void testGetStyleCss_WithOverrideAndDefaultValue() throws Exception {
simpleFeature.setAttribute(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, "fill:120,120,120;stroke:0,10,0");
final String styleCss = SimpleFeatureFigureFactory.getStyleCss(simpleFeature, "symbol:pin;fill:0,0,0");
assertEquals("fill:120,120,120;stroke:0,10,0;symbol:pin", styleCss);
}
@Test
public void testGetStyleCss_KeepDefault() throws Exception {
simpleFeature.setAttribute(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, "");
final String styleCss = SimpleFeatureFigureFactory.getStyleCss(simpleFeature, "symbol:pin;fill:0,0,0");
assertEquals("symbol:pin;fill:0,0,0", styleCss);
}
@Test
public void testGetStyleCss_EmptyDefault() throws Exception {
simpleFeature.setAttribute(PlainFeatureFactory.ATTRIB_NAME_STYLE_CSS, "symbol:cross;fill:100,100,100");
final String styleCss = SimpleFeatureFigureFactory.getStyleCss(simpleFeature, "");
assertEquals("symbol:cross;fill:100,100,100", styleCss);
}
}
| 3,442 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
InputFilesListModelTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/InputFilesListModelTest.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.ValidationException;
import org.esa.snap.core.datamodel.Product;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static org.junit.Assert.*;
/**
* @author Thomas Storm
*/
public class InputFilesListModelTest {
private InputListModel listModel;
private Property property;
@Before
public void setUp() {
property = Property.create("property", String[].class);
property.setContainer(new PropertyContainer());
listModel = new InputListModel();
listModel.setProperty(property);
}
@Test
public void testAddAndRemove() throws ValidationException {
listModel.addElements(new File("."));
listModel.addElements(new File("."));
assertEquals(1, listModel.getSize());
listModel.removeElementsAt(new int[]{0});
assertEquals(0, listModel.getSize());
List<File> files = new ArrayList<>();
files.add(new File("abc"));
files.add(new File("def"));
files.add(new File("ghi"));
listModel.addElements(files.toArray());
assertEquals(3, listModel.getSize());
assertEquals(3, ((String[]) property.getValue()).length);
List<Product> products = new ArrayList<>();
products.add(new Product("abc", "meris", 10, 120));
products.add(new Product("def", "meris", 10, 120));
products.add(new Product("ghi", "meris", 10, 120));
listModel.addElements(products.toArray());
assertEquals(6, listModel.getSize());
assertEquals(3, listModel.getSourceProducts().length);
listModel.removeElementsAt(new int[]{0, 5});
assertEquals(4, listModel.getSize());
assertEquals(2, ((String[]) property.getValue()).length);
assertEquals(2, listModel.getSourceProducts().length);
}
@Test(expected = IllegalStateException.class)
public void testFailingWithIllegalStateException() throws Exception {
listModel.addElements("");
}
@Test
public void testClear() throws Exception {
listModel.addElements(new File("abc"));
listModel.addElements(new File("def"));
listModel.addElements(new Product("def", "producttype", 10, 10));
listModel.addElements(new Product("dummy", "producttype", 10, 10));
assertEquals(4, listModel.getSize());
listModel.clear();
assertEquals(0, listModel.getSize());
assertEquals(0, listModel.getSourceProducts().length);
assertEquals(0, ((String[]) property.getValue()).length);
}
@Test
public void testSetElements() throws ValidationException {
final String[] elements1 = {"a", "b", "c"};
listModel.setPaths(elements1);
assertEquals(3, listModel.getSize());
final String[] values1 = property.getValue();
assertArrayEquals(elements1, values1);
final String[] elements2 = {"f", "s", "g", "k"};
listModel.setPaths(elements2);
assertEquals(4, listModel.getSize());
final String[] values2 = property.getValue();
assertArrayEquals(elements2, values2);
}
@Test
public void testSetPropertyEmptyDoesNotDeleteSourceProducts() throws ValidationException {
final Product product = new Product("name", "type", 1, 1);
listModel.addElements(product);
assertEquals(1, listModel.getSize());
final String[] elements1 = {"a", "b", "c"};
listModel.setPaths(elements1);
assertEquals(4, listModel.getSize());
final String[] values1 = property.getValue();
assertArrayEquals(elements1, values1);
property.setValue(null);
assertEquals(1, listModel.getSize());
assertSame(product, listModel.getElementAt(0));
}
@Test
public void testExternalPropertyValueChange() throws ValidationException {
assertEquals(0, listModel.getSize());
final String[] values = {"h", "i"};
property.setValue(values);
assertEquals(2, listModel.getSize());
assertEquals("h", ((File)listModel.getElementAt(0)).getPath());
assertEquals("i", ((File)listModel.getElementAt(1)).getPath());
}
}
| 5,123 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BandSorterTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/BandSorterTest.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.ProductData;
import org.junit.Test;
import java.util.*;
import static org.junit.Assert.assertEquals;
/**
* @author Thomas Storm
*/
public class BandSorterTest {
@Test
public void testSort_With_Wavelengths_and_Digits() {
List<Band> bands = new ArrayList<>();
bands.add(createBand("spec_1", 200));
bands.add(createBand("spec_2", 300));
bands.add(createBand("spec_3", 400));
bands.add(createBand("spec_4", 500));
bands.add(createBand("spec_5", 600));
bands.add(createBand("spec_6", 700));
Collections.shuffle(bands);
Band[] bandsArray = bands.toArray(new Band[bands.size()]);
Arrays.sort(bandsArray, BandSorter.createComparator());
assertEquals("spec_1", bandsArray[0].getName());
assertEquals("spec_2", bandsArray[1].getName());
assertEquals("spec_3", bandsArray[2].getName());
assertEquals("spec_4", bandsArray[3].getName());
assertEquals("spec_5", bandsArray[4].getName());
assertEquals("spec_6", bandsArray[5].getName());
}
@Test
public void testSort_Without_Digits() {
List<Band> bands = new ArrayList<>();
bands.add(createBand("spec_a", 200));
bands.add(createBand("spec_b", 300));
bands.add(createBand("spec_c", 400));
bands.add(createBand("spec_d", 500));
bands.add(createBand("spec_e", 600));
bands.add(createBand("spec_f", 700));
Collections.shuffle(bands);
Band[] bandsArray = bands.toArray(new Band[bands.size()]);
BandSorter.sort(bandsArray);
assertEquals("spec_a", bandsArray[0].getName());
assertEquals("spec_b", bandsArray[1].getName());
assertEquals("spec_c", bandsArray[2].getName());
assertEquals("spec_d", bandsArray[3].getName());
assertEquals("spec_e", bandsArray[4].getName());
assertEquals("spec_f", bandsArray[5].getName());
}
@Test
public void testSort_Without_Wavelengths() {
List<Band> bands = new ArrayList<>();
bands.add(createBand("spec_1", 0));
bands.add(createBand("spec_2", 0));
bands.add(createBand("spec_3", 0));
bands.add(createBand("spec_4", 0));
bands.add(createBand("spec_5", 0));
bands.add(createBand("spec_6", 0));
Collections.shuffle(bands);
Band[] bandsArray = bands.toArray(new Band[bands.size()]);
BandSorter.sort(bandsArray);
assertEquals("spec_1", bandsArray[0].getName());
assertEquals("spec_2", bandsArray[1].getName());
assertEquals("spec_3", bandsArray[2].getName());
assertEquals("spec_4", bandsArray[3].getName());
assertEquals("spec_5", bandsArray[4].getName());
assertEquals("spec_6", bandsArray[5].getName());
}
@Test
public void testSort_Without_Wavelengths_And_Digits() {
List<Band> bands = new ArrayList<>();
bands.add(createBand("spec_a", 0));
bands.add(createBand("spec_b", 0));
bands.add(createBand("spec_c", 0));
bands.add(createBand("spec_d", 0));
bands.add(createBand("spec_e", 0));
bands.add(createBand("spec_f", 0));
Collections.shuffle(bands);
Band[] bandsArray = bands.toArray(new Band[bands.size()]);
BandSorter.sort(bandsArray);
assertEquals("spec_a", bandsArray[0].getName());
assertEquals("spec_b", bandsArray[1].getName());
assertEquals("spec_c", bandsArray[2].getName());
assertEquals("spec_d", bandsArray[3].getName());
assertEquals("spec_e", bandsArray[4].getName());
assertEquals("spec_f", bandsArray[5].getName());
}
@Test
public void testTransitive() {
List<Band> bands = new ArrayList<>();
bands.add(createBand("spec_a", 75));
bands.add(createBand("spec_b", 70));
bands.add(createBand("spec_c", 65));
final Comparator<Band> comparator = BandSorter.createComparator();
assertEquals(-1, comparator.compare(bands.get(0), bands.get(1)));
assertEquals(-1, comparator.compare(bands.get(1), bands.get(2)));
assertEquals(-2, comparator.compare(bands.get(0), bands.get(2)));
}
@Test
public void testSignHandlingCommutative() {
List<Band> bands = new ArrayList<>();
bands.add(createBand("spec_a", 75));
bands.add(createBand("spec_b", 70));
final Comparator<Band> comparator = BandSorter.createComparator();
assertEquals(-1, comparator.compare(bands.get(0), bands.get(1)));
assertEquals(1, comparator.compare(bands.get(1), bands.get(0)));
}
@Test
public void testSignHandlingAtEquality() {
List<Band> bands = new ArrayList<>();
bands.add(createBand("spec_a", 75));
bands.add(createBand("spec_b", 75));
bands.add(createBand("spec_c", 72));
final Comparator<Band> comparator = BandSorter.createComparator();
assertEquals(-1, comparator.compare(bands.get(0), bands.get(1)));
assertEquals(-2, comparator.compare(bands.get(0), bands.get(2)));
assertEquals(-1, comparator.compare(bands.get(1), bands.get(2)));
}
public static Band createBand(String name, int wavelength) {
Band a = new Band(name, ProductData.TYPE_INT16, 10, 10);
a.setSpectralWavelength(wavelength);
return a;
}
}
| 6,203 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumBandTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/spectrum/SpectrumBandTest.java | package org.esa.snap.ui.product.spectrum;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
/**
* Created by E1001827 on 21.2.2014.
*/
public class SpectrumBandTest {
private Band band;
@Before
public void setUp() {
band = new Band("name", ProductData.TYPE_INT8, 1, 1);
band.setUnit("unit");
}
@Test
public void testSpectrumBandIsNotCreatedFromNullBand() {
try {
SpectrumBand spectrumBand = new SpectrumBand(null, true);
Assert.fail("Exception expected");
} catch (NullPointerException npe) {
Assert.assertEquals(npe.getMessage(), "Assert.notNull(null) called");
}
}
@Test
public void testSpectrumBandIsCreatedCorrectlyWithFalseInitialState() {
SpectrumBand spectrumBand = new SpectrumBand(band, true);
Assert.assertNotNull(spectrumBand);
Assert.assertEquals(true, spectrumBand.isSelected());
spectrumBand.setSelected(false);
Assert.assertEquals(false, spectrumBand.isSelected());
}
@Test
public void testSpectrumBandIsCreatedCorrectlyWithTrueInitialState() {
SpectrumBand spectrumBand = new SpectrumBand(band, false);
Assert.assertNotNull(spectrumBand);
Assert.assertEquals(false, spectrumBand.isSelected());
spectrumBand.setSelected(true);
Assert.assertEquals(true, spectrumBand.isSelected());
}
@Test
public void testGetUnit() {
SpectrumBand spectrumBand = new SpectrumBand(band, false);
Assert.assertEquals("unit", spectrumBand.getUnit());
}
@Test
public void testGetOriginalBand() {
SpectrumBand spectrumBand = new SpectrumBand(band, false);
Assert.assertEquals(band, spectrumBand.getOriginalBand());
}
}
| 1,906 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DisplayableSpectrumTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/spectrum/DisplayableSpectrumTest.java | package org.esa.snap.ui.product.spectrum;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by E1001827 on 21.2.2014.
*/
public class DisplayableSpectrumTest {
@Test
public void testNewDisplayableSpectrumIsSetupCorrectly() {
String spectrumName = "name";
DisplayableSpectrum displayableSpectrum = new DisplayableSpectrum(spectrumName, 1);
assertEquals(spectrumName, displayableSpectrum.getName());
assertEquals(DisplayableSpectrum.NO_UNIT, displayableSpectrum.getUnit());
assertNull(displayableSpectrum.getLineStyle());
assertEquals(SpectrumShapeProvider.DEFAULT_SCALE_GRADE, displayableSpectrum.getSymbolSize());
assertEquals(SpectrumShapeProvider.getScaledShape(1, SpectrumShapeProvider.DEFAULT_SCALE_GRADE),
displayableSpectrum.getScaledShape());
assertEquals(1, displayableSpectrum.getSymbolIndex());
assertTrue(displayableSpectrum.isSelected());
assertFalse(displayableSpectrum.isRemainingBandsSpectrum());
assertFalse(displayableSpectrum.hasBands());
assertEquals(0, displayableSpectrum.getSpectralBands().length);
assertEquals(0, displayableSpectrum.getSelectedBands().length);
}
@Test
public void testNewDisplayableSpectrumIsSetUpCorrectlyWithBands() {
String spectrumName = "name";
SpectrumBand[] spectralBands = new SpectrumBand[2];
for (int i = 0; i < spectralBands.length; i++) {
Band band = createBand(i);
band.setUnit("unit");
spectralBands[i] = new SpectrumBand(band, true);
}
DisplayableSpectrum displayableSpectrum = new DisplayableSpectrum(spectrumName, spectralBands, 1);
assertEquals(spectrumName, displayableSpectrum.getName());
assertEquals("unit", displayableSpectrum.getUnit());
assertTrue(displayableSpectrum.hasBands());
assertEquals(2, displayableSpectrum.getSpectralBands().length);
assertEquals(2, displayableSpectrum.getSelectedBands().length);
assertTrue(displayableSpectrum.isBandSelected(0));
assertTrue(displayableSpectrum.isBandSelected(1));
}
@Test
public void testBandsAreAddedCorrectlyToDisplayableSpectrum() {
String spectrumName = "name";
DisplayableSpectrum displayableSpectrum = new DisplayableSpectrum(spectrumName, 1);
SpectrumBand[] bands = new SpectrumBand[3];
for (int i = 0; i < bands.length; i++) {
Band band = createBand(i);
band.setUnit("unit" + i);
bands[i] = new SpectrumBand(band, i % 2 == 0);
displayableSpectrum.addBand(bands[i]);
}
assertEquals(spectrumName, displayableSpectrum.getName());
assertEquals(DisplayableSpectrum.MIXED_UNITS, displayableSpectrum.getUnit());
assertTrue(displayableSpectrum.hasBands());
assertEquals(3, displayableSpectrum.getSpectralBands().length);
assertEquals(bands[0].getOriginalBand(), displayableSpectrum.getSpectralBands()[0]);
assertEquals(bands[1].getOriginalBand(), displayableSpectrum.getSpectralBands()[1]);
assertEquals(bands[2].getOriginalBand(), displayableSpectrum.getSpectralBands()[2]);
assertEquals(2, displayableSpectrum.getSelectedBands().length);
assertEquals(bands[0].getOriginalBand(), displayableSpectrum.getSpectralBands()[0]);
assertEquals(bands[2].getOriginalBand(), displayableSpectrum.getSpectralBands()[2]);
assertTrue(displayableSpectrum.isBandSelected(0));
assertFalse(displayableSpectrum.isBandSelected(1));
assertTrue(displayableSpectrum.isBandSelected(2));
}
private Band createBand(int number) {
return new Band("name" + number, ProductData.TYPE_INT8, 1, 1);
}
}
| 3,902 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumChooserMainForManualTesting.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/spectrum/SpectrumChooserMainForManualTesting.java | package org.esa.snap.ui.product.spectrum;
import org.esa.snap.core.datamodel.Band;
import org.esa.snap.core.datamodel.ProductData;
public class SpectrumChooserMainForManualTesting {
/*
* Used for testing UI
*/
public static void main(String[] args) {
final DisplayableSpectrum[] spectra = new DisplayableSpectrum[3];
spectra[0] = createSpectrum(0);
spectra[1] = createSpectrum(1);
spectra[2] = new DisplayableSpectrum(DisplayableSpectrum.REMAINING_BANDS_NAME, 3);
spectra[2].addBand(createBand(11));
SpectrumChooser chooser = new SpectrumChooser(null, spectra);
chooser.show();
System.exit(0);
}
private static DisplayableSpectrum createSpectrum(int offset) {
int numBands = 5;
String name = "Radiances";
final DisplayableSpectrum spectrum = new DisplayableSpectrum(name + " " + (offset + 1), offset + 1);
final boolean selected = offset % 2 == 1;
spectrum.setSelected(selected);
spectrum.setLineStyle(SpectrumStrokeProvider.getStroke(offset));
final int bandOffset = numBands * offset;
for (int i = 0; i < numBands; i++) {
spectrum.addBand(createBand(i + bandOffset));
}
return spectrum;
}
static private SpectrumBand createBand(int index) {
final Band band = new Band("Radiance_" + (index + 1), ProductData.TYPE_INT16, 100, 100);
band.setDescription("Radiance for band " + (index + 1));
band.setSpectralWavelength((float) Math.random());
band.setSpectralBandwidth((float) Math.random());
band.setUnit("sr^-1");
if (index == 7) {
band.setUnit("dl");
}
return new SpectrumBand(band, true);
}
}
| 1,772 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SpectrumShapeProviderTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/spectrum/SpectrumShapeProviderTest.java | package org.esa.snap.ui.product.spectrum;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author Marco Peters
*/
public class SpectrumShapeProviderTest {
@Test
public void testGetValidIndex_WithoutEmptySymbol() throws Exception {
assertEquals(1, SpectrumShapeProvider.getValidIndex(0, false));
assertEquals(2, SpectrumShapeProvider.getValidIndex(1, false));
assertEquals(3, SpectrumShapeProvider.getValidIndex(2, false));
assertEquals(4, SpectrumShapeProvider.getValidIndex(3, false));
assertEquals(5, SpectrumShapeProvider.getValidIndex(4, false));
assertEquals(6, SpectrumShapeProvider.getValidIndex(5, false));
assertEquals(7, SpectrumShapeProvider.getValidIndex(6, false));
assertEquals(8, SpectrumShapeProvider.getValidIndex(7, false));
assertEquals(9, SpectrumShapeProvider.getValidIndex(8, false));
assertEquals(10, SpectrumShapeProvider.getValidIndex(9, false));
assertEquals(1, SpectrumShapeProvider.getValidIndex(10, false));
assertEquals(2, SpectrumShapeProvider.getValidIndex(11, false));
assertEquals(3, SpectrumShapeProvider.getValidIndex(12, false));
}
@Test
public void testGetValidIndex_WithEmptySymbol() throws Exception {
assertEquals(0, SpectrumShapeProvider.getValidIndex(0, true));
assertEquals(1, SpectrumShapeProvider.getValidIndex(1, true));
assertEquals(2, SpectrumShapeProvider.getValidIndex(2, true));
assertEquals(3, SpectrumShapeProvider.getValidIndex(3, true));
assertEquals(4, SpectrumShapeProvider.getValidIndex(4, true));
assertEquals(5, SpectrumShapeProvider.getValidIndex(5, true));
assertEquals(6, SpectrumShapeProvider.getValidIndex(6, true));
assertEquals(7, SpectrumShapeProvider.getValidIndex(7, true));
assertEquals(8, SpectrumShapeProvider.getValidIndex(8, true));
assertEquals(9, SpectrumShapeProvider.getValidIndex(9, true));
assertEquals(10, SpectrumShapeProvider.getValidIndex(10, true));
assertEquals(0, SpectrumShapeProvider.getValidIndex(11, true));
assertEquals(1, SpectrumShapeProvider.getValidIndex(12, true));
}
} | 2,225 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
MetadataElementLeafNodeTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/product/metadata/MetadataElementLeafNodeTest.java | package org.esa.snap.ui.product.metadata;
import com.bc.ceres.annotation.STTM;
import org.esa.snap.core.datamodel.ProductData;
import org.junit.Test;
import org.openide.nodes.PropertySupport;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertEquals;
@SuppressWarnings("rawtypes")
public class MetadataElementLeafNodeTest {
@Test
@STTM("SNAP-1684")
public void testEmptyProperty() throws InvocationTargetException, IllegalAccessException {
final MetadataElementLeafNode.EmptyProperty emptyProperty = new MetadataElementLeafNode.EmptyProperty("TEST_ME");
assertEquals("<empty>", emptyProperty.getValue());
}
@Test
@STTM("SNAP-1684")
public void testAddDataSpecificProperty_int32() throws InvocationTargetException, IllegalAccessException {
final List<PropertySupport> attributePropertyList = new ArrayList<>();
final MetadataTableLeaf leaf = new MetadataTableLeaf("don_t_care", ProductData.TYPE_INT32, ProductData.createInstance(new int[]{19}), null, null);
final MetadataElementLeafNode leafNode = new MetadataElementLeafNode(leaf);
leafNode.addDataTypeSpecificProperty(leaf, attributePropertyList);
assertEquals(1, attributePropertyList.size());
final PropertySupport propertySupport = attributePropertyList.get(0);
assertEquals(19, ((Integer) propertySupport.getValue()).intValue());
}
@Test
@STTM("SNAP-1684")
public void testAddDataSpecificProperty_uint32() throws InvocationTargetException, IllegalAccessException {
final List<PropertySupport> attributePropertyList = new ArrayList<>();
final MetadataTableLeaf leaf = new MetadataTableLeaf("don_t_care", ProductData.TYPE_UINT32, ProductData.createInstance(new int[]{20}), null, null);
final MetadataElementLeafNode leafNode = new MetadataElementLeafNode(leaf);
leafNode.addDataTypeSpecificProperty(leaf, attributePropertyList);
assertEquals(1, attributePropertyList.size());
final PropertySupport propertySupport = attributePropertyList.get(0);
assertEquals(20, ((Long) propertySupport.getValue()).longValue());
}
@Test
@STTM("SNAP-1684")
public void testAddDataSpecificProperty_UTC() throws InvocationTargetException, IllegalAccessException {
final List<PropertySupport> attributePropertyList = new ArrayList<>();
final MetadataTableLeaf leaf = new MetadataTableLeaf("don_t_care", ProductData.TYPE_UTC, new ProductData.UTC(589, 134, 33), null, null);
final MetadataElementLeafNode leafNode = new MetadataElementLeafNode(leaf);
leafNode.addDataTypeSpecificProperty(leaf, attributePropertyList);
assertEquals(1, attributePropertyList.size());
final PropertySupport propertySupport = attributePropertyList.get(0);
assertEquals("12-AUG-2001 00:02:14.000033", propertySupport.getValue());
}
@Test
@STTM("SNAP-1684")
public void testAddDataSpecificProperty_float64() throws InvocationTargetException, IllegalAccessException {
final List<PropertySupport> attributePropertyList = new ArrayList<>();
final MetadataTableLeaf leaf = new MetadataTableLeaf("don_t_care", ProductData.TYPE_FLOAT64, ProductData.createInstance(new double[]{21.0}), null, null);
final MetadataElementLeafNode leafNode = new MetadataElementLeafNode(leaf);
leafNode.addDataTypeSpecificProperty(leaf, attributePropertyList);
assertEquals(1, attributePropertyList.size());
final PropertySupport propertySupport = attributePropertyList.get(0);
assertEquals(21.0, (Double) propertySupport.getValue(), 1e-8);
}
@Test
@STTM("SNAP-1684")
public void testAddDataSpecificProperty_default() throws InvocationTargetException, IllegalAccessException {
final List<PropertySupport> attributePropertyList = new ArrayList<>();
final MetadataTableLeaf leaf = new MetadataTableLeaf("don_t_care", ProductData.TYPE_ASCII, ProductData.createInstance("Heffalump"), null, null);
final MetadataElementLeafNode leafNode = new MetadataElementLeafNode(leaf);
leafNode.addDataTypeSpecificProperty(leaf, attributePropertyList);
assertEquals(1, attributePropertyList.size());
final PropertySupport propertySupport = attributePropertyList.get(0);
assertEquals("Heffalump", propertySupport.getValue());
}
}
| 4,497 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UTMAutomaticCrsProviderTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/crs/projdef/UTMAutomaticCrsProviderTest.java | package org.esa.snap.ui.crs.projdef;
import org.esa.snap.core.datamodel.GeoPos;
import org.geotools.referencing.datum.DefaultGeodeticDatum;
import org.junit.Test;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import static org.junit.Assert.assertEquals;
/**
* @author Marco Peters
*/
public class UTMAutomaticCrsProviderTest {
@Test
public void getCRS() throws Exception {
CoordinateReferenceSystem crs;
UTMAutomaticCrsProvider autoUtmCrsProvider = new UTMAutomaticCrsProvider(DefaultGeodeticDatum.WGS84);
// The string is different to the one in the UI, because we use DefaultGeodeticDatum.WGS84, but in the UI we
// use the datum from the database.
crs = autoUtmCrsProvider.getCRS(new GeoPos(31.0, 33.0), null, DefaultGeodeticDatum.WGS84);
assertEquals("UTM Zone 36 / WGS84", crs.getName().getCode());
crs = autoUtmCrsProvider.getCRS(new GeoPos(-31.0, 33.0), null, DefaultGeodeticDatum.WGS84);
assertEquals("UTM Zone 36, South / WGS84", crs.getName().getCode());
crs = autoUtmCrsProvider.getCRS(new GeoPos(54.0, 10.0), null, DefaultGeodeticDatum.WGS84);
assertEquals("UTM Zone 32 / WGS84", crs.getName().getCode());
crs = autoUtmCrsProvider.getCRS(new GeoPos(36.0, -100.0), null, DefaultGeodeticDatum.WGS84);
assertEquals("UTM Zone 14 / WGS84", crs.getName().getCode());
}
} | 1,410 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramGraphIOTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/diagram/DiagramGraphIOTest.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.diagram;
import org.junit.Test;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import static org.esa.snap.core.util.Debug.assertNotNull;
import static org.junit.Assert.assertEquals;
public class DiagramGraphIOTest {
@Test
public void testIOWithEqualXValues() throws IOException {
double[] expectedXValues = new double[]{0, 1, 2, 3, 4, 5};
double[] expectedY1Values = new double[]{0, 1, 4, 9, 16, 25};
double[] expectedY2Values = new double[]{0, 1, 2, 3, 5, 8};
double[] expectedY3Values = new double[]{0.5, 0.4, 0.3, 0.2, 0.1, 0.0};
DiagramGraph[] expectedGraphs = new DefaultDiagramGraph[]{
new DefaultDiagramGraph("x", expectedXValues, "y1", expectedY1Values),
new DefaultDiagramGraph("x", expectedXValues, "y2", expectedY2Values),
new DefaultDiagramGraph("x", expectedXValues, "y3", expectedY3Values)
};
testIO(expectedGraphs);
}
@Test
public void testIOWithDifferentXValues() throws IOException {
double[] expectedX1Values = new double[]{0, 1, 2, 3, 4, 5};
double[] expectedY1Values = new double[]{0, 1, 2, 3, 5, 8};
double[] expectedX2Values = new double[]{4, 9, 16, 25}; // length = 4!
double[] expectedY2Values = new double[]{0.3, 0.2, 0.1, 0.0}; // length = 4!
DiagramGraph[] expectedGraphs = new DefaultDiagramGraph[]{
new DefaultDiagramGraph("x1", expectedX1Values, "y1", expectedY1Values),
new DefaultDiagramGraph("x2", expectedX2Values, "y2", expectedY2Values),
};
testIO(expectedGraphs);
}
private void testIO(DiagramGraph[] expectedGraphs) throws IOException {
StringWriter writer1 = new StringWriter();
DiagramGraphIO.writeGraphs(expectedGraphs, writer1);
DiagramGraph[] actualGraphs = DiagramGraphIO.readGraphs(new StringReader(writer1.toString()));
assertEqualGraphs(actualGraphs, expectedGraphs);
StringWriter writer2 = new StringWriter();
DiagramGraphIO.writeGraphs(expectedGraphs, writer2);
assertEquals(writer1.toString(), writer2.toString());
}
private void assertEqualGraphs(DiagramGraph[] actualGraphs, DiagramGraph[] expectedGraphs) {
assertNotNull(actualGraphs.length);
assertEquals(expectedGraphs.length, actualGraphs.length);
for (int i = 0; i < expectedGraphs.length; i++) {
assertEqualGraphs(expectedGraphs[i], actualGraphs[i]);
}
}
private void assertEqualGraphs(DiagramGraph expectedGraph, DiagramGraph actualGraph) {
assertNotNull(actualGraph);
assertEquals(expectedGraph.getXName(), actualGraph.getXName());
assertEquals(expectedGraph.getYName(), actualGraph.getYName());
assertEquals(expectedGraph.getNumValues(), actualGraph.getNumValues());
for (int i = 0; i < expectedGraph.getNumValues(); i++) {
assertEquals(expectedGraph.getXValueAt(i), actualGraph.getXValueAt(i), 1e-10);
assertEquals(expectedGraph.getYValueAt(i), actualGraph.getYValueAt(i), 1e-10);
}
}
}
| 3,908 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramAxisTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/diagram/DiagramAxisTest.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.diagram;
import org.junit.Before;
import org.junit.Test;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Vector;
import static org.junit.Assert.*;
public class DiagramAxisTest {
DiagramAxis diagramAxis;
private EventCounter eventCounter;
@Before
public void setUp() {
Diagram diagram = new Diagram();
diagramAxis = new DiagramAxis();
diagram.setXAxis(diagramAxis);
eventCounter = new EventCounter();
diagram.addChangeListener(eventCounter);
}
@Test
public void testProperties() {
eventCounter.reset();
diagramAxis.setName("bibo");
assertEquals("bibo", diagramAxis.getName());
assertEquals(1, eventCounter.counts);
diagramAxis.setName(null);
assertNull(diagramAxis.getName());
assertEquals(2, eventCounter.counts);
diagramAxis.setUnit("bibo");
assertEquals("bibo", diagramAxis.getUnit());
assertEquals(3, eventCounter.counts);
diagramAxis.setUnit(null);
assertNull(diagramAxis.getUnit());
assertEquals(4, eventCounter.counts);
assertEquals(1.0, diagramAxis.getUnitFactor(), 1e-10);
diagramAxis.setUnitFactor(0.5);
assertEquals(0.5, diagramAxis.getUnitFactor(), 1e-10);
assertEquals(5, eventCounter.counts);
diagramAxis.setNumMajorTicks(5);
assertEquals(5, diagramAxis.getNumMajorTicks());
assertEquals(6, eventCounter.counts);
diagramAxis.setNumMinorTicks(3);
assertEquals(3, diagramAxis.getNumMinorTicks());
assertEquals(7, eventCounter.counts);
diagramAxis.setValueRange(13.1, 16.2);
assertEquals(16.2, diagramAxis.getMaxValue(), 1e-9);
assertEquals(13.1, diagramAxis.getMinValue(), 1e-9);
assertEquals(8, eventCounter.counts);
try {
diagramAxis.setValueRange(14.1, 11.2);
fail();
} catch (Exception e) {
assertEquals("java.lang.IllegalArgumentException", e.getClass().getName());
}
assertEquals(8, eventCounter.counts);
}
@Test
public void testSetSubDivision() {
diagramAxis.setSubDivision(12.4, 83.6, 7, 4);
assertEquals(12.4, diagramAxis.getMinValue(), 1e-9);
assertEquals(83.6, diagramAxis.getMaxValue(), 1e-9);
assertEquals(7, diagramAxis.getNumMajorTicks());
assertEquals(4, diagramAxis.getNumMinorTicks());
assertEquals(3, eventCounter.counts);
}
@Test
public void testSetOptimalSubDivision() {
diagramAxis.setValueRange(13.1, 16.2);
assertEquals(1, eventCounter.counts);
diagramAxis.setOptimalSubDivision(4, 6, 8);
assertEquals(16.5, diagramAxis.getMaxValue(), 1e-9);
assertEquals(12.75, diagramAxis.getMinValue(), 1e-9);
assertEquals(6, diagramAxis.getNumMajorTicks());
assertEquals(8, diagramAxis.getNumMinorTicks());
assertEquals(4, eventCounter.counts);
}
@Test
public void testGetOptimalTickDistance() {
assertEquals(10d, DiagramAxis.getOptimalTickDistance(12, 31, 3), 1e-6);
assertEquals(0.1d, DiagramAxis.getOptimalTickDistance(0.12, 0.31, 3), 1e-9);
assertEquals(2.5d, DiagramAxis.getOptimalTickDistance(52, 57, 3), 1e-6);
assertEquals(2.5d, DiagramAxis.getOptimalTickDistance(15, 20, 3), 1e-6);
assertEquals(4.0d, DiagramAxis.getOptimalTickDistance(14.8, 20.3, 3), 1e-6);
assertEquals(5.0d, DiagramAxis.getOptimalTickDistance(14.8, 24.8, 3), 1e-6);
assertEquals(2.0d, DiagramAxis.getOptimalTickDistance(14.8, 18.8, 3), 1e-6);
assertEquals(2.0d, DiagramAxis.getOptimalTickDistance(10.2, 13.8, 3), 1e-6);
assertEquals(2.0d, DiagramAxis.getOptimalTickDistance(10.2, 13.8, 3), 1e-6);
assertEquals(7500.0d, DiagramAxis.getOptimalTickDistance(-10200, 5.0, 3), 1e-6);
}
/**
* A listener used to check the bean properties of DiagramAxis.
*/
static class DiagramAxisPropertyChangeListener implements PropertyChangeListener {
Vector _events;
public void propertyChange(PropertyChangeEvent evt) {
if (_events == null) {
_events = new Vector();
}
_events.add(evt);
}
public PropertyChangeEvent[] getEvents() {
if (_events == null || _events.size() == 0) {
return null;
}
return (PropertyChangeEvent[]) _events.toArray(new PropertyChangeEvent[_events.size()]);
}
public void reset() {
if (_events != null) {
_events.clear();
}
}
}
private static class EventCounter implements DiagramChangeListener {
int counts = 0;
public void reset() {
counts = 0;
}
public void diagramChanged(Diagram diagram) {
counts++;
}
}
}
| 5,718 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DiagramTest.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/test/java/org/esa/snap/ui/diagram/DiagramTest.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.diagram;
import org.esa.snap.core.util.math.Range;
import org.junit.Test;
import java.awt.geom.Point2D;
import static org.junit.Assert.assertEquals;
public class DiagramTest {
@Test
public void testTransform() {
Diagram.RectTransform rectTransform = new Diagram.RectTransform(new Range(0, 10),
new Range(-1, +1),
new Range(100, 200),
new Range(100, 0));
Point2D a, b;
a = new Point2D.Double(5, 0);
b = rectTransform.transformA2B(a, null);
assertEquals(new Point2D.Double(150.0, 50.0), b);
assertEquals(a, rectTransform.transformB2A(b, null));
a = new Point2D.Double(7.5, -0.25);
b = rectTransform.transformA2B(a, null);
assertEquals(new Point2D.Double(175.0, 62.5), b);
assertEquals(a, rectTransform.transformB2A(b, null));
}
}
| 1,622 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImageInfoEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/ImageInfoEditor.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;
import com.bc.ceres.binding.Property;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.binding.ValueRange;
import com.bc.ceres.swing.binding.BindingContext;
import com.jidesoft.popup.JidePopup;
import com.jidesoft.swing.JidePopupMenu;
import org.esa.snap.core.datamodel.ColorPaletteDef;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.util.NamingConvention;
import org.esa.snap.core.util.math.Histogram;
import org.esa.snap.core.util.math.MathUtils;
import org.esa.snap.core.util.math.Range;
import org.esa.snap.ui.color.ColorChooserPanel;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.text.NumberFormatter;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.text.DecimalFormat;
/**
* Unstable interface. Do not use.
*
* @author Norman Fomferra
* @author Daniel Knowles (NASA)
* @author Bing Yang (NASA)
* @version $Revision$ $Date$
* @since BEAM 4.5.1
*/
// OCT 2019 - Knowles / Yang
// - Added a boolean field "logScaled" for determining if log scaled.
// - Added abstract method "checkSliderRangeCompatibility" to be used for slider value adjacency checks.
// - Added abstract method "checkLogCompatibility" to be used for log scaling illegal value checks.
// - Incorporated the above checks within the listener of the slider.
// FEB 2020 - Knowles
// - Added computePercent() method to enable any percent range of the histogram to be calculated
public abstract class ImageInfoEditor extends JPanel {
public static final String PROPERTY_NAME_MODEL = "model";
public static final String NO_DISPLAY_INFO_TEXT = "No information available.";
public static final String FONT_NAME = "Verdana";
public static final int FONT_SIZE = 9;
public static final int INVALID_INDEX = -1;
public static final int PALETTE_HEIGHT = 16;
public static final int SLIDER_WIDTH = 12;
public static final int SLIDER_HEIGHT = 10;
public static final int SLIDER_VALUES_AREA_HEIGHT = 50;
public static final int HOR_BORDER_SIZE = 10;
public static final int VER_BORDER_SIZE = 4;
public static final int PREF_HISTO_WIDTH = 256; //196;
public static final int PREF_HISTO_HEIGHT = 196; //128;
public static final Dimension PREF_COMPONENT_SIZE
= new Dimension(PREF_HISTO_WIDTH + 2 * HOR_BORDER_SIZE,
PREF_HISTO_HEIGHT + PALETTE_HEIGHT + SLIDER_HEIGHT / 2
+ 2 * HOR_BORDER_SIZE + FONT_SIZE);
public static final BasicStroke STROKE_1 = new BasicStroke(1.0f);
public static final BasicStroke STROKE_2 = new BasicStroke(2.0f);
public static final BasicStroke DASHED_STROKE = new BasicStroke(0.75F, BasicStroke.CAP_SQUARE,
BasicStroke.JOIN_MITER, 1.0F, new float[]{5.0F},
0.0F);
private ImageInfoEditorModel model;
private Font labelFont;
private final Shape sliderShape;
private int sliderTextBaseLineY;
private final Rectangle sliderBaseLineRect;
private final Rectangle paletteRect;
private final Rectangle histoRect;
private double roundFactor;
private final InternalMouseListener internalMouseListener;
private double[] factors;
private Color[] palette;
private ModelCL modelCL;
private JidePopup popup;
private BufferedImage paletteBackgound;
private boolean logScaled = false;
public ImageInfoEditor() {
labelFont = createLabelFont();
sliderShape = createSliderShape();
sliderBaseLineRect = new Rectangle();
paletteRect = new Rectangle();
histoRect = new Rectangle();
internalMouseListener = new InternalMouseListener();
modelCL = new ModelCL();
addChangeListener(new RepaintCL());
}
public final ImageInfoEditorModel getModel() {
return model;
}
public final void setModel(final ImageInfoEditorModel model) {
final ImageInfoEditorModel oldModel = this.model;
if (oldModel != model) {
this.model = model;
deinstallMouseListener();
if (oldModel != null) {
oldModel.removeChangeListener(modelCL);
}
if (this.model != null) {
roundFactor = MathUtils.computeRoundFactor(this.model.getMinSample(), this.model.getMaxSample(), 2);
installMouseListener();
model.addChangeListener(modelCL);
}
firePropertyChange(PROPERTY_NAME_MODEL, oldModel, this.model);
fireStateChanged();
}
if (isShowing()) {
repaint();
}
}
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
public ChangeListener[] getChangeListeners() {
return listenerList.getListeners(ChangeListener.class);
}
protected void fireStateChanged() {
final ChangeEvent event = new ChangeEvent(this);
Object[] listeners = listenerList.getListenerList();
for (int i = listeners.length - 2; i >= 0; i -= 2) {
if (listeners[i] == ChangeListener.class) {
((ChangeListener) listeners[i + 1]).stateChanged(event);
}
}
}
public boolean computePercent(boolean logScaled, double threshhold) {
final Histogram histogram = new Histogram(getModel().getHistogramBins(),
scaleInverse(getModel().getMinSample()),
scaleInverse(getModel().getMaxSample()));
Range autoStretchRange = histogram.findRangeForPercent(threshhold);
if (autoStretchRange == null) {
return false;
}
if (logScaled && scale(autoStretchRange.getMin()) <= 0) {
return false;
}
computeFactors();
setFirstSliderSample(scale(autoStretchRange.getMin()));
setLastSliderSample(scale(autoStretchRange.getMax()));
partitionSliders(false);
computeZoomInToSliderLimits();
return true;
}
public boolean setRGBminmax(double min, double max) {
computeFactors();
setFirstSliderSample(min);
setLastSliderSample(max);
partitionSliders(false);
computeZoomInToSliderLimits();
return true;
}
public boolean compute100Percent(boolean logScaled) {
if (logScaled && getModel().getMinSample() <= 0) {
return false;
}
computeFactors();
setFirstSliderSample(getModel().getMinSample());
setLastSliderSample(getModel().getMaxSample());
partitionSliders(false);
computeZoomInToSliderLimits();
return true;
}
public void distributeSlidersEvenly() {
final double pos1 = scaleInverse(getFirstSliderSample());
final double pos2 = scaleInverse(getLastSliderSample());
final double delta = pos2 - pos1;
final double evenSpace = delta / (getSliderCount() - 2 + 1);
for (int i = 0; i < getSliderCount(); i++) {
final double value = scale(pos1 + evenSpace * i);
setSliderSample(i, value, false);
}
}
private void partitionSliders(boolean adjusting) {
final double pos1 = scaleInverse(getFirstSliderSample());
final double pos2 = scaleInverse(getLastSliderSample());
final double delta = pos2 - pos1;
for (int i = 0; i < (getSliderCount() - 1); i++) {
final double value = scale(pos1 + factors[i] * delta);
setSliderSample(i, value, adjusting);
}
}
private void computeFactors() {
factors = new double[getSliderCount()];
final double firstPS = scaleInverse(getFirstSliderSample());
final double lastPS = scaleInverse(getLastSliderSample());
double dsn = lastPS - firstPS;
if (dsn == 0 || Double.isNaN(dsn)) {
dsn = Double.MIN_VALUE;
}
for (int i = 0; i < getSliderCount(); i++) {
final double sample = scaleInverse(getSliderSample(i));
final double dsi = sample - firstPS;
factors[i] = dsi / dsn;
}
}
@Override
public Dimension getPreferredSize() {
return PREF_COMPONENT_SIZE;
}
@Override
public void setBounds(int x, int y, int width, int heigth) {
super.setBounds(x, y, width, heigth);
computeSizeAttributes();
}
public void computeZoomInToSliderLimits() {
final double firstSliderValue = scaleInverse(getFirstSliderSample());
final double lastSliderValue = scaleInverse(getLastSliderSample());
final double percentOffset = 0.0;
final double minViewSample = scale(firstSliderValue - percentOffset);
final double maxViewSample = scale(lastSliderValue + percentOffset);
getModel().setMinHistogramViewSample(minViewSample);
getModel().setMaxHistogramViewSample(maxViewSample);
repaint();
}
public void computeZoomOutToFullHistogramm() {
getModel().setMinHistogramViewSample(getMinSample());
getModel().setMaxHistogramViewSample(getMaxSample());
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (getModel() == null || getWidth() == 0 || getHeight() == 0) {
return;
}
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setFont(labelFont);
computeSizeAttributes();
if (isValidModel()) {
drawPalette(g2d);
drawSliders(g2d);
drawHistogramPane(g2d);
} else {
FontMetrics fontMetrics = g2d.getFontMetrics();
drawMissingBasicDisplayInfoMessage(g2d, fontMetrics);
}
}
private boolean isHistogramAvailable() {
return model.isHistogramAvailable();
}
private boolean isValidModel() {
return model != null
&& model.getMinSample() <= model.getMaxSample()
&& model.getSampleScaling() != null
&& model.getSampleStx() != null;
}
public void computeZoomOutVertical() {
getModel().setHistogramViewGain(getModel().getHistogramViewGain() * (1.0 / 1.4));
repaint();
}
public void computeZoomInVertical() {
getModel().setHistogramViewGain(getModel().getHistogramViewGain() * 1.4);
repaint();
}
private void drawMissingBasicDisplayInfoMessage(Graphics2D g2d, FontMetrics fontMetrics) {
int totWidth = getWidth();
int totHeight = getHeight();
g2d.drawString(NO_DISPLAY_INFO_TEXT,
(totWidth - fontMetrics.stringWidth(NO_DISPLAY_INFO_TEXT)) / 2,
(totHeight + fontMetrics.getHeight()) / 2);
}
private void drawPalette(Graphics2D g2d) {
if (paletteBackgound == null
|| paletteBackgound.getWidth() != paletteRect.width
|| paletteBackgound.getHeight() != paletteRect.height) {
this.paletteBackgound = createAlphaBackground(paletteRect.width, paletteRect.height);
}
g2d.drawImage(paletteBackgound, paletteRect.x, paletteRect.y, null);
long paletteX1 = paletteRect.x + Math.round(getRelativeSliderPos(getFirstSliderSample()));
long paletteX2 = paletteRect.x + Math.round(getRelativeSliderPos(getLastSliderSample()));
g2d.setStroke(STROKE_1);
Color[] colorPalette = getColorPalette();
if (colorPalette != null) {
for (int x = paletteRect.x; x < paletteRect.x + paletteRect.width; x++) {
long divisor = paletteX2 - paletteX1;
int palIndex;
if (divisor == 0) {
palIndex = x < paletteX1 ? 0 : colorPalette.length - 1;
} else {
palIndex = (int) ((colorPalette.length * (x - paletteX1)) / divisor);
}
if (palIndex < 0) {
palIndex = 0;
}
if (palIndex > colorPalette.length - 1) {
palIndex = colorPalette.length - 1;
}
g2d.setColor(colorPalette[palIndex]);
g2d.drawLine(x, paletteRect.y, x, paletteRect.y + paletteRect.height);
}
}
g2d.setStroke(STROKE_1);
g2d.setColor(Color.darkGray);
g2d.draw(paletteRect);
}
private static BufferedImage createAlphaBackground(int width, int height) {
BufferedImage background = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
DataBufferInt dataBuffer = (DataBufferInt) background.getRaster().getDataBuffer();
int[] data = dataBuffer.getData();
int gray = Color.LIGHT_GRAY.getRGB();
int white = Color.WHITE.getRGB();
for (int i = 0; i < data.length; i++) {
int x = i % width;
int y = i / width;
data[i] = ((x / 4) % 2 == (y / 4) % 2) ? gray : white;
}
return background;
}
private Color[] getColorPalette() {
if (palette == null) {
palette = getModel().createColorPalette();
}
return palette;
}
private void drawSliders(Graphics2D g2d) {
g2d.translate(sliderBaseLineRect.x, sliderBaseLineRect.y);
g2d.setStroke(STROKE_1);
for (int i = 0; i < getSliderCount(); i++) {
if (isSliderVisible(i)) {
double sliderPos = getRelativeSliderPos(getSliderSample(i));
g2d.translate(sliderPos, 0.0);
final Color sliderColor = getSliderColor(i);
g2d.setPaint(sliderColor);
g2d.fill(sliderShape);
int gray = (sliderColor.getRed() + sliderColor.getGreen() + sliderColor.getBlue()) / 3;
g2d.setColor(gray < 128 ? Color.white : Color.black);
g2d.draw(sliderShape);
String text = getFormattedValue(getSliderSample(i));
g2d.setColor(Color.black);
// save the old transformation
final AffineTransform oldTransform = g2d.getTransform();
g2d.transform(AffineTransform.getRotateInstance(Math.PI / 2));
g2d.drawString(text, 3 + 0.5f * SLIDER_HEIGHT, 0.35f * FONT_SIZE);
// restore the old transformation
g2d.setTransform(oldTransform);
g2d.translate(-sliderPos, 0.0);
}
}
g2d.translate(-sliderBaseLineRect.x, -sliderBaseLineRect.y);
}
private String getFormattedValue(double value) {
if (value < 0.1 && value > -0.1 && value != 0.0) {
return new DecimalFormat("0.##E0").format(value);
}
return new DecimalFormat("#0.0#").format(round(value));
}
private void drawHistogramPane(Graphics2D g2d) {
Shape oldClip = g2d.getClip();
g2d.setClip(histoRect.x - 1, histoRect.y - 1, histoRect.width + 2, histoRect.height + 2);
drawHistogram(g2d);
drawGradationCurve(g2d);
drawHistogramBorder(g2d);
g2d.setClip(oldClip);
}
private void drawHistogramBorder(Graphics2D g2d) {
g2d.setStroke(STROKE_1);
g2d.setColor(Color.darkGray);
g2d.draw(histoRect);
}
private void drawGradationCurve(Graphics2D g2d) {
g2d.setColor(Color.white);
g2d.setStroke(STROKE_2);
int x1 = histoRect.x;
int y1 = histoRect.y + histoRect.height - 1;
int x2 = (int) getAbsoluteSliderPos(getFirstSliderSample());
int y2 = y1;
g2d.drawLine(x1, y1, x2, y2);
x1 = x2;
y1 = y2;
x2 = (int) getAbsoluteSliderPos(getLastSliderSample());
y2 = histoRect.y + 1;
final byte[] gammaCurve = getModel().getGammaCurve();
if (gammaCurve != null) {
int xx = x1;
int yy = y1;
for (int x = x1 + 1; x <= x2; x++) {
int i = MathUtils.roundAndCrop((255.9f * (x - x1)) / (x2 - x1), 0, 255);
int y = y1 + ((y2 - y1) * (gammaCurve[i] & 0xff)) / 256;
g2d.drawLine(xx, yy, x, y);
//System.out.println("x=" + x + ", y=" + y);
xx = x;
yy = y;
}
} else {
g2d.drawLine(x1, y1, x2, y2);
}
x1 = x2;
y1 = y2;
x2 = histoRect.x + histoRect.width;
y2 = histoRect.y + 1;
g2d.drawLine(x1, y1, x2, y2);
// Vertical lines
g2d.setStroke(DASHED_STROKE);
for (int i = 0; i < getSliderCount(); i++) {
x1 = (int) getAbsoluteSliderPos(getSliderSample(i));
y1 = histoRect.y + histoRect.height - 1;
x2 = x1;
y2 = histoRect.y + 1;
g2d.drawLine(x1, y1, x2, y2);
}
}
private void drawHistogram(Graphics2D g2d) {
if (model.isHistogramAvailable()) {
final Paint oldPaint = g2d.getPaint();
g2d.setPaint(Color.DARK_GRAY);
final int[] histogramBins = model.getHistogramBins();
final double maxHistogramCounts = getMaxVisibleHistogramCounts(histogramBins, 1.0 / 16.0);
final double viewBinCount = getHistogramViewBinCount();
if (viewBinCount > 0.0 && maxHistogramCounts > 0.0) {
g2d.setStroke(new BasicStroke(1.0f));
final double minViewBinIndex = getMinHistogramViewBinIndex();
final double binsPerPixel = viewBinCount / histoRect.width;
final double maxBarHeight = 0.9 * histoRect.height;
final double gain = model.getHistogramViewGain();
final double countsScale = (gain * maxBarHeight) / maxHistogramCounts;
final Rectangle2D.Double r = new Rectangle2D.Double();
for (int i = 0; i < histoRect.width; i++) {
final int binIndex = (int) Math.floor(minViewBinIndex + i * binsPerPixel);
double binHeight = 0.0;
if (binIndex >= 0 && binIndex < histogramBins.length) {
final double counts = histogramBins[binIndex];
binHeight = countsScale * counts;
}
if (binHeight >= histoRect.height) {
// must crop here because on highly centered histograms this value is FAR beyond the rectangle
// and then triggers an exception when trying to draw it.
binHeight = histoRect.height - 1;
}
r.setRect(histoRect.x + i, histoRect.y + histoRect.height - 1 - binHeight, 1.0, binHeight);
g2d.fill(r);
}
}
g2d.setPaint(oldPaint);
}
}
private static double getMaxVisibleHistogramCounts(final int[] histogramBins, double ratio) {
double totalHistogramCounts = 0.0;
for (int histogramBin : histogramBins) {
totalHistogramCounts += histogramBin;
}
final double limitHistogramCounts = totalHistogramCounts * ratio;
double maxHistogramCounts = 0.0;
for (int histogramBin : histogramBins) {
if (histogramBin < limitHistogramCounts) {
maxHistogramCounts = Math.max(maxHistogramCounts, histogramBin);
}
}
return maxHistogramCounts;
}
private void installMouseListener() {
addMouseListener(internalMouseListener);
addMouseMotionListener(internalMouseListener);
}
private void deinstallMouseListener() {
removeMouseListener(internalMouseListener);
removeMouseMotionListener(internalMouseListener);
}
private double getMaxSample() {
return getModel().getMaxSample();
}
private double getMinSample() {
return getModel().getMinSample();
}
private int getSliderCount() {
return getModel().getSliderCount();
}
private double getMinSliderSample(int sliderIndex) {
if (sliderIndex == 0) {
return getMinSample();
} else {
return getSliderSample(sliderIndex - 1);
}
}
private double getMaxSliderSample(int sliderIndex) {
if (sliderIndex == getSliderCount() - 1) {
return getMaxSample();
} else {
return getSliderSample(sliderIndex + 1);
}
}
private double getFirstSliderSample() {
return getSliderSample(0);
}
private void setFirstSliderSample(double v) {
setSliderSample(0, v);
}
private double getLastSliderSample() {
return getSliderSample(getModel().getSliderCount() - 1);
}
private void setLastSliderSample(double v) {
setSliderSample(getModel().getSliderCount() - 1, v);
}
private double getSliderSample(int index) {
return getModel().getSliderSample(index);
}
private void setSliderSample(int index, double v) {
getModel().setSliderSample(index, v);
}
protected abstract void applyChanges();
private void setSliderSample(int index, double newValue, boolean adjusting) {
if (adjusting) {
double minValue = Double.NEGATIVE_INFINITY;
if (index > 0 && index < getSliderCount() - 1) {
minValue = getSliderSample(index - 1);
}
if (newValue < minValue) {
newValue = minValue;
}
}
setSliderSample(index, newValue);
}
private Color getSliderColor(int index) {
ImageInfo.UncertaintyVisualisationMode uvMode = getModel().getImageInfo().getUncertaintyVisualisationMode();
if (uvMode != null) {
if (uvMode == ImageInfo.UncertaintyVisualisationMode.Transparency_Blending) {
return Color.WHITE;
} else if (uvMode == ImageInfo.UncertaintyVisualisationMode.Monochromatic_Blending) {
return getModel().getSliderColor(getSliderCount() - 1);
}
}
return getModel().getSliderColor(index);
}
private void setSliderColor(int index, Color c) {
getModel().setSliderColor(index, c);
applyChanges();
}
private static Font createLabelFont() {
return new Font(FONT_NAME, Font.PLAIN, FONT_SIZE);
}
public static Shape createSliderShape() {
GeneralPath path = new GeneralPath();
path.moveTo(0.0F, -0.5F * SLIDER_HEIGHT);
path.lineTo(+0.5F * SLIDER_WIDTH, 0.5F * SLIDER_HEIGHT);
path.lineTo(-0.5F * SLIDER_WIDTH, 0.5F * SLIDER_HEIGHT);
path.closePath();
return path;
}
private double computeSliderValueForX(int sliderIndex, int x) {
final double minVS = scaleInverse(getModel().getMinHistogramViewSample());
final double maxVS = scaleInverse(getModel().getMaxHistogramViewSample());
final double value = scale(minVS + (x - sliderBaseLineRect.x) * (maxVS - minVS) / sliderBaseLineRect.width);
if (isFirstSliderIndex(sliderIndex)) {
return Math.min(value, getLastSliderSample());
}
if (isLastSliderIndex(sliderIndex)) {
return Math.max(value, getFirstSliderSample());
}
return computeAdjustedSliderValue(sliderIndex, value);
}
private double computeAdjustedSliderValue(int sliderIndex, double value) {
double valueD = value;
double minSliderValue = getMinSliderSample(sliderIndex);
double maxSliderValue = getMaxSliderSample(sliderIndex);
if (valueD < minSliderValue) {
valueD = minSliderValue;
}
if (valueD > maxSliderValue) {
valueD = maxSliderValue;
}
return valueD;
}
private boolean isFirstSliderIndex(int sliderIndex) {
return sliderIndex == 0;
}
private boolean isLastSliderIndex(int sliderIndex) {
return getSliderCount() - 1 == sliderIndex;
}
private double round(double value) {
return MathUtils.round(value, roundFactor);
}
private double getAbsoluteSliderPos(double sample) {
return sliderBaseLineRect.x + getRelativeSliderPos(sample);
}
private double getRelativeSliderPos(double sample) {
return getNormalizedHistogramViewSampleValue(sample) * sliderBaseLineRect.width;
}
private void computeSizeAttributes() {
int totWidth = getWidth();
int totHeight = getHeight();
int imageWidth = totWidth - 2 * HOR_BORDER_SIZE;
sliderTextBaseLineY = totHeight - VER_BORDER_SIZE - SLIDER_VALUES_AREA_HEIGHT;
sliderBaseLineRect.x = HOR_BORDER_SIZE;
sliderBaseLineRect.y = sliderTextBaseLineY - SLIDER_HEIGHT / 2;
sliderBaseLineRect.width = imageWidth;
sliderBaseLineRect.height = 1;
paletteRect.x = HOR_BORDER_SIZE;
paletteRect.y = sliderBaseLineRect.y - PALETTE_HEIGHT;
paletteRect.width = imageWidth;
paletteRect.height = PALETTE_HEIGHT;
histoRect.x = HOR_BORDER_SIZE;
histoRect.y = VER_BORDER_SIZE;
histoRect.width = imageWidth;
histoRect.height = paletteRect.y - histoRect.y - 3;
}
private double getHistogramViewBinCount() {
return Math.min(getDisplayableBinCount(), model.getHistogramBins().length);
}
private double getDisplayableBinCount() {
final double max = Math.min(getMaxSample(), getModel().getMaxHistogramViewSample());
final double min = Math.max(getMinSample(), getModel().getMinHistogramViewSample());
return getBinCountInRange(min, max);
}
private double getBinCountInRange(double minSample, double maxSample) {
if (!isHistogramAvailable()) {
return -1.0;
}
final double minHistogramSample = model.getMinSample();
final double maxHistogramSample = model.getMaxSample();
if (minSample >= maxHistogramSample || maxSample <= minHistogramSample) {
return 0.0;
}
minSample = Math.max(minSample, minHistogramSample);
maxSample = Math.min(maxSample, maxHistogramSample);
final double a = scaleInverse(maxSample) - scaleInverse(minSample);
final double b = scaleInverse(maxHistogramSample) - scaleInverse(minHistogramSample);
return (a / b) * model.getHistogramBins().length;
}
private double getMinHistogramViewBinIndex() {
if (!isHistogramAvailable()) {
return -1.0;
}
final double minHistogramSample = model.getMinSample();
final double minHistogramViewSample = model.getMinHistogramViewSample();
if (minHistogramSample != minHistogramViewSample) {
final double a = scaleInverse(minHistogramViewSample) - scaleInverse(minHistogramSample);
final double b = scaleInverse(model.getMaxSample()) - scaleInverse(minHistogramSample);
return (a / b) * model.getHistogramBins().length;
}
return 0.0;
}
private double getNormalizedHistogramViewSampleValue(double sample) {
final double minVisibleSample = scaleInverse(getModel().getMinHistogramViewSample());
final double maxVisibleSample = scaleInverse(getModel().getMaxHistogramViewSample());
sample = scaleInverse(sample);
double delta = maxVisibleSample - minVisibleSample;
if (delta == 0 || Double.isNaN(delta)) {
delta = 1;
}
return (sample - minVisibleSample) / delta;
}
private void editSliderColor(MouseEvent evt, final int sliderIndex) {
final Color selectedColor = getSliderColor(sliderIndex);
final ColorChooserPanel panel = new ColorChooserPanel(selectedColor);
panel.addPropertyChangeListener(ColorChooserPanel.SELECTED_COLOR_PROPERTY, evt1 -> {
setSliderColor(sliderIndex, panel.getSelectedColor());
hidePopup();
});
showPopup(evt, panel);
}
private boolean isSliderVisible(int sliderIndex) {
if (sliderIndex == 0 || sliderIndex == getSliderCount() - 1) {
return true;
}
ImageInfo.UncertaintyVisualisationMode uvMode = getModel().getImageInfo().getUncertaintyVisualisationMode();
return uvMode == null
|| uvMode == ImageInfo.UncertaintyVisualisationMode.None
|| uvMode == ImageInfo.UncertaintyVisualisationMode.Polychromatic_Blending
|| uvMode == ImageInfo.UncertaintyVisualisationMode.Polychromatic_Overlay;
}
private boolean isSliderEditable(int sliderIndex) {
ImageInfo.UncertaintyVisualisationMode uvMode = getModel().getImageInfo().getUncertaintyVisualisationMode();
return uvMode == null
|| uvMode == ImageInfo.UncertaintyVisualisationMode.None
|| uvMode == ImageInfo.UncertaintyVisualisationMode.Polychromatic_Blending
|| uvMode == ImageInfo.UncertaintyVisualisationMode.Polychromatic_Overlay
|| (uvMode == ImageInfo.UncertaintyVisualisationMode.Monochromatic_Blending && isLastSliderIndex(sliderIndex));
}
private boolean canChangeSliderCount() {
ImageInfo.UncertaintyVisualisationMode uvMode = getModel().getImageInfo().getUncertaintyVisualisationMode();
return uvMode == null
|| uvMode == ImageInfo.UncertaintyVisualisationMode.None
|| uvMode == ImageInfo.UncertaintyVisualisationMode.Polychromatic_Blending
|| uvMode == ImageInfo.UncertaintyVisualisationMode.Polychromatic_Overlay;
}
private void editSliderSample(MouseEvent evt, final int sliderIndex) {
final PropertyContainer vc = new PropertyContainer();
vc.addProperty(Property.create("sample", getSliderSample(sliderIndex)));
vc.getDescriptor("sample").setDisplayName("sample");
vc.getDescriptor("sample").setUnit(getModel().getParameterUnit());
final ValueRange valueRange;
if (sliderIndex == 0) {
valueRange = new ValueRange(Double.NEGATIVE_INFINITY, round(getMaxSliderSample(sliderIndex)));
} else if (sliderIndex == getSliderCount() - 1) {
valueRange = new ValueRange(round(getMinSliderSample(sliderIndex)), Double.POSITIVE_INFINITY);
} else {
valueRange = new ValueRange(round(getMinSliderSample(sliderIndex)), round(getMaxSliderSample(sliderIndex)));
}
vc.getDescriptor("sample").setValueRange(valueRange);
final BindingContext ctx = new BindingContext(vc);
final NumberFormatter formatter = new NumberFormatter(new DecimalFormat("#0.000000000#"));
formatter.setValueClass(Double.class); // to ensure that double values are returned
final JFormattedTextField field = new JFormattedTextField(formatter);
field.setColumns(11);
field.setHorizontalAlignment(JFormattedTextField.RIGHT);
ctx.bind("sample", field);
showPopup(evt, field);
ctx.addPropertyChangeListener("sample", pce -> {
hidePopup();
Double value = (Double) ctx.getBinding("sample").getPropertyValue();
if (
checkSliderRangeCompatibility(value, valueRange.getMin(), valueRange.getMax())
&& checkLogCompatibility(value, "slider", isLogScaled())
) {
setSliderSample(sliderIndex, value);
computeZoomInToSliderLimits();
applyChanges();
}
});
}
private void showPopup(MouseEvent evt, JComponent component) {
hidePopup();
popup = new JidePopup();
popup.setOwner(this);
popup.setDefaultFocusComponent(component);
popup.getContentPane().add(component);
popup.setAttachable(true);
popup.setMovable(false);
popup.showPopup(evt.getXOnScreen(), evt.getYOnScreen());
}
private void hidePopup() {
if (popup != null && popup.isVisible()) {
popup.hidePopupImmediately();
popup = null;
}
}
private class InternalMouseListener implements MouseListener, MouseMotionListener {
private int draggedSliderIndex;
private boolean dragging;
private InternalMouseListener() {
draggedSliderIndex = INVALID_INDEX;
factors = null;
dragging = false;
}
public boolean isDragging() {
return dragging;
}
public void setDragging(boolean dragging) {
this.dragging = dragging;
}
@Override
public void mousePressed(MouseEvent mouseEvent) {
hidePopup();
resetState();
// on linux: popup is triggered on mousePressed
// on windows: popup is triggered on mouseReleased
if (!maybeShowSliderActions(mouseEvent)) {
setDraggedSliderIndex(getNearestSliderIndex(mouseEvent.getX(), mouseEvent.getY()));
if (isFirstSliderDragged() || isLastSliderDragged()) {
computeFactors();
}
}
}
@Override
public void mouseReleased(MouseEvent evt) {
if (isDragging()) {
doDragSlider(evt, false);
setDragging(false);
setDraggedSliderIndex(INVALID_INDEX);
applyChanges();
} else if (!maybeShowSliderActions(evt) && SwingUtilities.isLeftMouseButton(evt)) {
int mode = 0;
int sliderIndex = getSelectedSliderIndex(evt);
if (sliderIndex != INVALID_INDEX && getModel().isColorEditable()) {
mode = 1;
}
if (mode == 0) {
if (sliderIndex == INVALID_INDEX) {
sliderIndex = getSelectedSliderTextIndex(evt);
}
if (sliderIndex != INVALID_INDEX) {
mode = 2;
}
}
if (mode == 1) {
editSliderColor(evt, sliderIndex);
} else if (mode == 2) {
editSliderSample(evt, sliderIndex);
}
}
}
@Override
public void mouseClicked(MouseEvent evt) {
maybeShowSliderActions(evt);
}
@Override
public void mouseEntered(MouseEvent mouseEvent) {
resetState();
}
@Override
public void mouseExited(MouseEvent mouseEvent) {
resetState();
}
@Override
public void mouseDragged(MouseEvent mouseEvent) {
setDragging(true);
doDragSlider(mouseEvent, true);
}
private void doDragSlider(MouseEvent mouseEvent, boolean adjusting) {
if (getDraggedSliderIndex() != INVALID_INDEX) {
int x = mouseEvent.getX();
x = Math.max(x, sliderBaseLineRect.x);
x = Math.min(x, sliderBaseLineRect.x + sliderBaseLineRect.width);
final double newSample = computeSliderValueForX(getDraggedSliderIndex(), x);
setSliderSample(getDraggedSliderIndex(), newSample, adjusting);
if (isFirstSliderDragged() || isLastSliderDragged()) {
partitionSliders(adjusting);
}
}
}
@Override
public void mouseMoved(MouseEvent mouseEvent) {
if (isDragging()) {
mouseDragged(mouseEvent);
}
}
private boolean maybeShowSliderActions(MouseEvent mouseEvent) {
if (getModel().isColorEditable() && mouseEvent.isPopupTrigger()) {
final int sliderIndex = getSelectedSliderIndex(mouseEvent);
showSliderActions(mouseEvent, sliderIndex);
return true;
}
return false;
}
private void setDraggedSliderIndex(final int draggedSliderIndex) {
if (this.draggedSliderIndex != draggedSliderIndex) {
this.draggedSliderIndex = draggedSliderIndex;
}
}
public int getDraggedSliderIndex() {
return draggedSliderIndex;
}
private void showSliderActions(MouseEvent evt, final int sliderIndex) {
final JPopupMenu menu = new JidePopupMenu();
boolean showPopupMenu = false;
JMenuItem menuItem;
if (canChangeSliderCount()) {
menuItem = createMenuItemAddNewSlider(sliderIndex, evt);
if (menuItem != null) {
menu.add(menuItem);
showPopupMenu = true;
}
if (getSliderCount() > 2 && sliderIndex != INVALID_INDEX) {
menuItem = createMenuItemDeleteSlider(sliderIndex);
menu.add(menuItem);
showPopupMenu = true;
}
}
if (getSliderCount() > 2
&& sliderIndex > 0
&& sliderIndex < getSliderCount() - 1
&& isSliderEditable(sliderIndex)) {
menuItem = createMenuItemCenterSampleValue(sliderIndex);
menu.add(menuItem);
menuItem = createMenuItemCenterColorValue(sliderIndex);
menu.add(menuItem);
showPopupMenu = true;
}
if (showPopupMenu) {
menu.show(evt.getComponent(), evt.getX(), evt.getY());
}
}
private JMenuItem createMenuItemCenterColorValue(final int sliderIndex) {
JMenuItem menuItem = new JMenuItem();
menuItem.setText("Center Slider " + NamingConvention.COLOR_MIXED_CASE); /* I18N */
menuItem.setMnemonic('c');
menuItem.addActionListener(actionEvent -> {
final Color newColor = ColorPaletteDef.getCenterColor(getSliderColor(sliderIndex - 1),
getSliderColor(sliderIndex + 1));
setSliderColor(sliderIndex, newColor);
hidePopup();
applyChanges();
});
return menuItem;
}
private JMenuItem createMenuItemCenterSampleValue(final int sliderIndex) {
JMenuItem menuItem = new JMenuItem();
menuItem.setText("Center Slider Position"); /* I18N */
menuItem.setMnemonic('s');
menuItem.addActionListener(actionEvent -> {
final double center = scale(0.5 * (scaleInverse(getSliderSample(sliderIndex - 1)) + scaleInverse(
getSliderSample(sliderIndex + 1))));
setSliderSample(sliderIndex, center, false);
hidePopup();
applyChanges();
});
return menuItem;
}
private JMenuItem createMenuItemDeleteSlider(final int removeIndex) {
JMenuItem menuItem = new JMenuItem("Remove Slider");
menuItem.setMnemonic('D');
menuItem.addActionListener(e -> {
getModel().removeSlider(removeIndex);
hidePopup();
applyChanges();
});
return menuItem;
}
private JMenuItem createMenuItemAddNewSlider(int insertIndex, final MouseEvent evt) {
if (insertIndex == getModel().getSliderCount() - 1) {
return null;
}
if (insertIndex == INVALID_INDEX && isClickOutsideExistingSliders(evt.getX())) {
return null;
}
if (insertIndex == INVALID_INDEX && !isVerticalInColorBarArea(evt.getY())) {
return null;
}
if (insertIndex == INVALID_INDEX) {
insertIndex = getNearestLeftSliderIndex(evt.getX());
}
if (insertIndex == INVALID_INDEX) {
return null;
}
final int index = insertIndex;
JMenuItem menuItem = new JMenuItem("Add new Slider");
menuItem.setMnemonic('A');
menuItem.addActionListener(e -> {
assert getModel() != null : "getModel() != null";
if (index < getModel().getSliderCount() - 1) {
getModel().createSliderAfter(index);
}
hidePopup();
applyChanges();
});
return menuItem;
}
private boolean isClickOutsideExistingSliders(int x) {
return x < getAbsoluteSliderPos(getFirstSliderSample()) || x > getAbsoluteSliderPos(getLastSliderSample());
}
private boolean isFirstSliderDragged() {
return getDraggedSliderIndex() == 0;
}
private boolean isLastSliderDragged() {
return getDraggedSliderIndex() == getSliderCount() - 1;
}
private boolean isVerticalInColorBarArea(int y) {
final int dy = Math.abs(paletteRect.y + PALETTE_HEIGHT / 2 - y);
return dy < PALETTE_HEIGHT / 2;
}
private boolean isVerticalInSliderArea(int y) {
final int dy = Math.abs(sliderBaseLineRect.y - y);
return dy < SLIDER_HEIGHT / 2;
}
private int getSelectedSliderIndex(MouseEvent evt) {
if (isVerticalInSliderArea(evt.getY())) {
final int sliderIndex = getNearestSliderIndex(evt.getX());
final double dx = Math.abs(getAbsoluteSliderPos(getSliderSample(sliderIndex)) - evt.getX());
if (dx < Math.floor(SLIDER_WIDTH / 2.0)) {
return sliderIndex;
}
}
return INVALID_INDEX;
}
private int getSelectedSliderTextIndex(MouseEvent evt) {
double dy = Math.abs(sliderTextBaseLineY + SLIDER_VALUES_AREA_HEIGHT - evt.getY());
if (dy < SLIDER_VALUES_AREA_HEIGHT) {
final int sliderIndex = getNearestSliderIndex(evt.getX());
final double dx = Math.abs(getAbsoluteSliderPos(getSliderSample(sliderIndex)) - evt.getX());
if (dx < Math.floor(FONT_SIZE / 2.0)) {
return sliderIndex;
}
}
return INVALID_INDEX;
}
private int getNearestSliderIndex(int x, int y) {
if (isVerticalInSliderArea(y)) {
return getNearestSliderIndex(x);
}
return INVALID_INDEX;
}
private int getNearestLeftSliderIndex(int x) {
final int index = getNearestSliderIndex(x);
final double pos = getRelativeSliderPos(getSliderSample(index));
if (pos > x) {
if (index > 0) {
return index - 1;
}
return INVALID_INDEX;
}
return index;
}
private int getNearestSliderIndex(int x) {
int nearestIndex = INVALID_INDEX;
double minDx = Float.MAX_VALUE;
double dx = 0.0;
for (int i = 0; i < getSliderCount(); i++) {
dx = getAbsoluteSliderPos(getSliderSample(i)) - x;
if (Math.abs(dx) <= minDx) {
nearestIndex = i;
minDx = Math.abs(dx);
}
}
// Find correct index for two points at the same, last position
if (nearestIndex == getSliderCount() - 1) {
final int i = getSliderCount() - 1;
if (getAbsoluteSliderPos(getSliderSample(i - 1)) == getAbsoluteSliderPos(getSliderSample(i))) {
nearestIndex = dx <= 0.0 ? i : i - 1;
}
}
return nearestIndex;
}
private void resetState() {
setDraggedSliderIndex(INVALID_INDEX);
factors = null;
}
}
private double scale(double value) {
assert model != null;
return model.getSampleScaling().scale(value);
}
private double scaleInverse(double value) {
assert model != null;
return model.getSampleScaling().scaleInverse(value);
}
private class RepaintCL implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
palette = null;
repaint();
}
}
private class ModelCL implements ChangeListener {
@Override
public void stateChanged(ChangeEvent e) {
fireStateChanged();
}
}
/**
* Determine whether value is illegal value (zero or less) if in log mode
* @param value
* @param componentName identify theGUI component
* @param isLogScaled
* @return
*/
protected abstract boolean checkLogCompatibility(double value, String componentName, boolean isLogScaled);
/**
* Determine whether a value is in between a min and a max value (or adjacent values)
* @param value
* @param min
* @param max
* @return
*/
protected abstract boolean checkSliderRangeCompatibility(double value, double min, double max);
public boolean isLogScaled() {
return logScaled;
}
public void setLogScaled(boolean logScaled) {
this.logScaled = logScaled;
}
}
| 47,312 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
package-info.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/package-info.java | /*
* Copyright (C) 2015 Brockmann Consult GmbH ([email protected])
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
/**
* Provides utility classes for building Swing user interfaces using the SNAP data model.
*/
package org.esa.snap.ui; | 844 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ExpressionPane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/ExpressionPane.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;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.jexp.Function;
import org.esa.snap.core.jexp.Namespace;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.jexp.Parser;
import org.esa.snap.core.jexp.Term;
import org.esa.snap.core.jexp.impl.Functions;
import org.esa.snap.core.jexp.impl.NamespaceImpl;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Window;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.Stack;
/**
* The expression pane is a UI component which is used to edit mathematical expressions. There are four methods which
* can be used to customize the UI of the expression pane: {@code {@link #setLeftAccessory}}, {@code {@link
* #setRightAccessory}}, {@code {@link #setTopAccessory}} and {@code {@link #setBottomAccessory}}.
*/
public class ExpressionPane extends JPanel {
public static final String HELP_ID = "expressionEditor";
/**
* The prefix used to store the code history in the preferences.
*/
public static final String CODE_HISTORY_PREFERENCES_PREFIX = "expression.history.";
private static final int CODE_HISTORY_MAX = 100;
/**
* The string used to represent an expression placeholder for text insertion.
*/
public static final String PLACEHOLDER = "@";
private static final int PLACEHOLDER_LEN = PLACEHOLDER.length();
private static final String[] CONSTANT_LITERALS = new String[]{
"PI",
"E",
"NaN",
"true",
"false",
"X",
"Y",
"LAT",
"LON",
"TIME",
"0.5",
"0.0",
"1.0",
"2.0",
"0",
"1",
"2",
"273.15",
};
private static final String[] OPERATOR_PATTERNS = new String[]{
"@ ? @ : @",
"if @ then @ else @",
"@ || @",
"@ or @",
"@ && @",
"@ and @",
"@ < @",
"@ <= @",
"@ > @",
"@ >= @",
"@ == @",
"@ <= @",
"@ | @",
"@ ^ @",
"@ & @",
"@ + @",
"@ - @",
"@ * @",
"@ / @",
"@ % @",
"+@",
"-@",
"~@",
"!@",
"not @"
};
private static final String[] FUNCTION_CALL_PATTERNS;
private static Font exprTextAreaFont = new Font("Courier", Font.PLAIN, 12);
private static Font insertCompFont = new Font("Courier", Font.PLAIN, 11);
private static Color insertCompColor = new Color(0, 0, 128);
private static Color okMsgColor = new Color(0, 128, 0);
private static Color warnMsgColor = new Color(128, 0, 0);
private Parser parser;
private final Stack<String> undoBuffer;
private boolean booleanExpressionPreferred;
private JTextArea codeArea;
private JLabel messageLabel;
private ExpressionPane.ActionPane actionPane;
private String lastErrorMessage;
private PropertyMap preferences;
private List<String> history;
private int historyIndex;
private boolean emptyExpressionAllowed;
static {
List<Function> functions = Functions.getAll();
FUNCTION_CALL_PATTERNS = new String[functions.size()];
for (int i = 0; i < FUNCTION_CALL_PATTERNS.length; i++) {
FUNCTION_CALL_PATTERNS[i] = getFunctionCallPattern(functions.get(i));
}
}
/**
* Constructs a new expression pane.
*
* @param requiresBoolExpr if {@code true} the expressions are checked to return a boolean value.
* @param parser the parser used to check expression syntax
* @param preferences a property map which stores expression pane related properties such as the code history
*/
public ExpressionPane(boolean requiresBoolExpr, Parser parser, PropertyMap preferences) {
super(new BorderLayout(4, 4));
undoBuffer = new Stack<>();
this.parser = parser;
booleanExpressionPreferred = requiresBoolExpr;
history = new LinkedList<>();
historyIndex = -1;
emptyExpressionAllowed = true;
setPreferences(preferences);
createUI();
}
public int showModalDialog(Window parent, String title) {
ModalDialog dialog = new ExpressionPaneDialog(parent, title);
return dialog.show();
}
public PropertyMap getPreferences() {
return preferences;
}
public void setPreferences(PropertyMap preferences) {
this.preferences = preferences;
if (this.preferences != null) {
loadCodeHistory();
}
}
public void setEmptyExpressionAllowed(boolean allow) {
this.emptyExpressionAllowed = allow;
}
public boolean isEmptyExpressionAllowed() {
return emptyExpressionAllowed;
}
public void updateCodeHistory() {
String code = getCode();
if (code != null) {
code = code.trim();
if (!code.equals("")) {
addToCodeHistory(code, true);
storeCodeHistory();
}
}
}
private void addToCodeHistory(String code, boolean head) {
if (code != null) {
code = code.trim();
if (!code.equals("")) {
if (history.contains(code)) {
history.remove(code);
}
if (head) {
history.add(0, code);
} else {
history.add(code);
}
}
}
}
public void loadCodeHistory() {
if (preferences != null) {
history.clear();
for (int index = 0; index < CODE_HISTORY_MAX; index++) {
final String code = preferences.getPropertyString(CODE_HISTORY_PREFERENCES_PREFIX + index);
addToCodeHistory(code, false);
}
historyIndex = -1;
updateUIState();
}
}
public void storeCodeHistory() {
if (history != null && preferences != null) {
final Iterator<String> iterator = history.iterator();
for (int index = 0; index < CODE_HISTORY_MAX && iterator.hasNext(); index++) {
String code = iterator.next();
preferences.setPropertyString(CODE_HISTORY_PREFERENCES_PREFIX + index, code);
}
}
}
protected void dispose() {
undoBuffer.clear();
parser = null;
codeArea = null;
messageLabel = null;
actionPane = null;
}
public void setLeftAccessory(Component component) {
add(component, BorderLayout.WEST);
}
public void setRightAccessory(Component component) {
add(component, BorderLayout.EAST);
}
public void setTopAccessory(Component component) {
add(component, BorderLayout.NORTH);
}
public void setBottomAccessory(Component component) {
add(component, BorderLayout.SOUTH);
}
public JTextArea getCodeArea() {
return codeArea;
}
public boolean isBooleanExpressionPreferred() {
return booleanExpressionPreferred;
}
public void setBooleanExpressionPreferred(boolean booleanExpressionPreferred) {
this.booleanExpressionPreferred = booleanExpressionPreferred;
}
public Parser getParser() {
return parser;
}
public void setParser(Parser parser) {
Parser oldValue = this.parser;
if (oldValue == parser) {
return;
}
this.parser = parser;
firePropertyChange("parser", oldValue, parser);
}
public String getCode() {
return codeArea.getText();
}
public void setCode(String newCode) {
setCode(newCode, false, -1);
}
public void setCode(String newCode, boolean recordUndo, int caretPos) {
String oldCode = codeArea.getText();
if (recordUndo) {
pushCodeOnUndoStack(oldCode);
}
codeArea.setText(newCode == null ? "" : newCode);
checkCode(newCode);
updateUIState();
if (caretPos >= 0) {
codeArea.setCaretPosition(caretPos);
}
codeArea.requestFocus();
firePropertyChange("code", oldCode, newCode);
}
public void clearCode() {
setCode("");
}
public void selectAllCode() {
codeArea.selectAll();
codeArea.requestFocus();
}
public void undoLastEdit() {
if (!undoBuffer.isEmpty()) {
String code = undoBuffer.pop();
setCode(code);
updateUIState();
codeArea.requestFocus();
}
}
public void insertCodePattern(String pattern) {
String oldCode = getCode();
int newCaretPos;
StringBuffer sb = new StringBuffer(oldCode.length() + 2 * pattern.length());
int selPos1 = codeArea.getSelectionStart();
int selPos2 = codeArea.getSelectionEnd();
if (selPos1 >= 0 && selPos2 >= 0 && selPos1 > selPos2) {
int temp = selPos1;
selPos1 = selPos2;
selPos2 = temp;
}
int phPatPos = pattern.indexOf(PLACEHOLDER);
// If code was selected,
if (selPos2 > selPos1) {
String selCode = oldCode.substring(selPos1, selPos2);
// ...look if there is a placeholder in the pattern
append(sb, oldCode.substring(0, selPos1));
if (phPatPos >= 0) {
// replace placeholder in pattern with selected text
append(sb, pattern.substring(0, phPatPos));
append(sb, selCode.trim());
append(sb, pattern.substring(phPatPos + PLACEHOLDER_LEN));
} else {
// replace selected text with pattern
append(sb, pattern);
}
newCaretPos = sb.length();
append(sb, oldCode.substring(selPos2));
} else {
// If no code was selected,
// ...look if there is a placeholder in the code
int phPos = oldCode.indexOf(PLACEHOLDER);
if (phPos >= 0 && phPatPos == -1) {
// replace placeholder in code with pattern
append(sb, oldCode.substring(0, phPos));
append(sb, pattern);
newCaretPos = sb.length();
append(sb, oldCode.substring(phPos + PLACEHOLDER_LEN));
} else {
// ... look for the caret pos
int caretPos = codeArea.getCaretPosition();
// ... and divide code in a left and right part
String lCode = oldCode.substring(0, caretPos).trim();
String rCode = oldCode.substring(caretPos).trim();
// if there is text to the left and the pattern starts with a placeholder
if (lCode.length() > 0 && pattern.startsWith(PLACEHOLDER)) {
// if there is text to the right and the pattern ends with a placeholder
if (rCode.length() > 0 && pattern.endsWith(PLACEHOLDER)) {
// ...replace both placeholder in the pattern
append(sb, lCode);
append(sb, pattern.substring(PLACEHOLDER_LEN, pattern.length() - PLACEHOLDER_LEN));
newCaretPos = sb.length();
append(sb, rCode);
} else {
// ...replace left placeholder in the pattern
append(sb, lCode);
append(sb, pattern.substring(PLACEHOLDER_LEN));
newCaretPos = sb.length();
append(sb, rCode);
}
// if there is text to the right and the pattern ends with a placeholder
} else if (rCode.length() > 0 && pattern.endsWith(PLACEHOLDER)) {
// ...replace right placeholder in the pattern
append(sb, lCode);
append(sb, pattern.substring(0, pattern.length() - PLACEHOLDER_LEN));
newCaretPos = sb.length();
append(sb, rCode);
} else {
// ...insert pattern at caret position
append(sb, lCode);
append(sb, pattern);
newCaretPos = sb.length();
append(sb, rCode);
}
}
}
setCode(sb.toString(), true, newCaretPos);
}
private static void append(StringBuffer sb, String s) {
int n1 = sb.length();
int n2 = s.length();
if (n1 > 0 && n2 > 0) {
char ch1 = sb.charAt(n1 - 1);
char ch2 = s.charAt(0);
if (ch1 != ' ' && ch2 != ' ' && ch1 != ',' && ch1 != '(' && ch2 != ')') {
sb.append(' ');
}
}
sb.append(s);
}
public ActionPane createActionPane() {
return new ActionPane();
}
public JButton createInsertButton(final String pattern) {
JButton button = new JButton(pattern);
button.setFont(insertCompFont);
button.setForeground(insertCompColor);
button.addActionListener(e -> insertCodePattern(pattern));
return button;
}
private JComboBox<String> createInsertComboBox(final String title, final String[] patterns) {
ArrayList<String> itemList = new ArrayList<>();
itemList.add(title);
itemList.addAll(Arrays.asList(patterns));
final JComboBox<String> comboBox = new JComboBox<>(itemList.toArray(new String[itemList.size()]));
comboBox.setFont(insertCompFont);
comboBox.setEditable(false);
comboBox.setForeground(insertCompColor);
comboBox.addActionListener(e -> {
if (comboBox.getSelectedIndex() != 0) {
insertCodePattern((String) comboBox.getSelectedItem());
comboBox.setSelectedIndex(0);
}
});
return comboBox;
}
public JList<String> createPatternList() {
return createPatternList(null);
}
public JList<String> createPatternList(final String[] patterns) {
final JList<String> patternList = new JList<>(patterns);
patternList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
final ListCellRenderer<? super String> cellRenderer = patternList.getCellRenderer();
final Border cellBorder = BorderFactory.createEtchedBorder();
patternList.setCellRenderer((list, value, index, isSelected, cellHasFocus) -> {
final Component component1 = cellRenderer.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (component1 instanceof JComponent) {
((JComponent) component1).setBorder(cellBorder);
}
return component1;
});
patternList.setFont(insertCompFont);
patternList.setBackground(getBackground());
patternList.setForeground(insertCompColor);
patternList.addMouseListener(new MouseAdapter() {
/**
* Invoked when the mouse has been clicked on a component.
*/
@Override
public void mouseClicked(MouseEvent e) {
final int index = patternList.locationToIndex(e.getPoint());
if (index >= 0) {
final String value = patternList.getModel().getElementAt(index);
final String pattern = BandArithmetic.createExternalName(value);
insertCodePattern(pattern);
patternList.clearSelection();
}
}
});
return patternList;
}
protected JPanel createPatternListPane(final String labelText, final String[] patterns) {
JList<String> list = createPatternList(patterns);
JScrollPane scrollableList = new JScrollPane(list);
JPanel pane = new JPanel(new BorderLayout());
pane.add(BorderLayout.NORTH, new JLabel(labelText));
pane.add(BorderLayout.CENTER, scrollableList);
return pane;
}
protected void createUI() {
codeArea = new JTextArea(10, 40);
codeArea.setName("codeArea");
codeArea.setLineWrap(true);
codeArea.setWrapStyleWord(true);
codeArea.setFont(exprTextAreaFont);
codeArea.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
checkCode();
}
public void removeUpdate(DocumentEvent e) {
checkCode();
}
public void changedUpdate(DocumentEvent e) {
checkCode();
}
});
actionPane = createActionPane();
actionPane.setName("actionPane");
messageLabel = new JLabel();
messageLabel.setFont(getFont().deriveFont(10.0F));
messageLabel.setHorizontalAlignment(JLabel.RIGHT);
final JPanel panel = new JPanel(new BorderLayout());
panel.add(actionPane, BorderLayout.WEST);
panel.add(messageLabel, BorderLayout.EAST);
JScrollPane scrollableTextArea = new JScrollPane(codeArea);
JPanel codePane = new JPanel(new BorderLayout());
codePane.add(new JLabel("Expression:"), BorderLayout.NORTH); /*I18N*/
codePane.add(scrollableTextArea, BorderLayout.CENTER);
codePane.add(panel, BorderLayout.SOUTH);
add(codePane, BorderLayout.CENTER);
setCode("");
}
protected JPanel createPatternInsertionPane() {
final GridBagLayout gbl = new GridBagLayout();
JPanel patternPane = new JPanel(gbl);
GridBagConstraints gbc = new GridBagConstraints();
gbc.ipadx = 1;
gbc.ipady = 1;
gbc.anchor = GridBagConstraints.NORTHWEST;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.weightx = 1;
gbc.gridy = 0;
if (booleanExpressionPreferred) {
final JButton andButton = createInsertButton("@ and @");
final JButton orButton = createInsertButton("@ or @");
final JButton notButton = createInsertButton("not @");
andButton.setName("andButton");
orButton.setName("orButton");
notButton.setName("notButton");
add(patternPane, andButton, gbc);
gbc.gridy++;
add(patternPane, orButton, gbc);
gbc.gridy++;
add(patternPane, notButton, gbc);
gbc.gridy++;
} else {
final JButton plusButton = createInsertButton("@ + @");
final JButton minusButton = createInsertButton("@ - @");
final JButton mulButton = createInsertButton("@ * @");
final JButton divButton = createInsertButton("@ / @");
plusButton.setName("plusButton");
minusButton.setName("minusButton");
mulButton.setName("mulButton");
divButton.setName("divButton");
add(patternPane, plusButton, gbc);
gbc.gridy++;
add(patternPane, minusButton, gbc);
gbc.gridy++;
add(patternPane, mulButton, gbc);
gbc.gridy++;
add(patternPane, divButton, gbc);
gbc.gridy++;
}
final String[] functionNames = getFunctionTemplates();
final JButton parenButton = createInsertButton("(@)");
parenButton.setName("parenButton");
final JComboBox<String> functBox = createInsertComboBox("Functions...", functionNames);
final JComboBox<String> operBox = createInsertComboBox("Operators...", OPERATOR_PATTERNS);
final JComboBox<String> constBox = createInsertComboBox("Constants...", CONSTANT_LITERALS);
functBox.setName("functBox");
operBox.setName("operBox");
constBox.setName("constBox");
add(patternPane, parenButton, gbc);
gbc.gridy++;
add(patternPane, constBox, gbc);
gbc.gridy++;
add(patternPane, operBox, gbc);
gbc.gridy++;
add(patternPane, functBox, gbc);
gbc.gridy++;
return patternPane;
}
private String[] getFunctionTemplates() {
final Namespace defaultNamespace = parser.getDefaultNamespace();
// collect names
String[] functionNames;
if (defaultNamespace instanceof NamespaceImpl) {
final NamespaceImpl namespace = (NamespaceImpl) defaultNamespace;
final Function[] functions = namespace.getAllFunctions();
functionNames = new String[functions.length];
for (int i = 0; i < functions.length; i++) {
functionNames[i] = createFunctionTemplate(functions[i]);
}
} else {
functionNames = FUNCTION_CALL_PATTERNS;
}
// remove double values
Set<String> set = new HashSet<>();
Collections.addAll(set, functionNames);
functionNames = set.toArray(new String[set.size()]);
Arrays.sort(functionNames);
return functionNames;
}
private static String createFunctionTemplate(Function function) {
StringBuilder sb = new StringBuilder(16);
sb.append(function.getName());
sb.append("(");
for (int i = 0; i < function.getNumArgs(); i++) {
if (i > 0) {
sb.append(",");
}
sb.append("@");
}
sb.append(")");
return sb.toString();
}
protected JPanel createDefaultAccessoryPane(Component subAssessory) {
JPanel patternPane = createPatternInsertionPane();
// JPanel historyPane = createHistoryPane();
// _actionPane = createActionPane();
JPanel p1 = new JPanel(new BorderLayout());
p1.add(new JLabel(" "), BorderLayout.NORTH);
p1.add(patternPane, BorderLayout.CENTER);
JPanel p2 = new JPanel(new BorderLayout(4, 4));
p2.add(p1, BorderLayout.NORTH);
// p2.add(historyPane, BorderLayout.CENTER);
// p2.add(_actionPane, BorderLayout.SOUTH);
if (subAssessory != null) {
JPanel p3 = new JPanel(new BorderLayout(4, 4));
p3.add(subAssessory, BorderLayout.WEST);
p3.add(p2, BorderLayout.EAST);
return p3;
} else {
return p1;
}
}
private static void add(JPanel panel, Component comp, GridBagConstraints gbc) {
final GridBagLayout gbl = (GridBagLayout) panel.getLayout();
gbl.setConstraints(comp, gbc);
panel.add(comp, gbc);
}
protected void checkCode() {
checkCode(getCode());
}
protected void checkCode(String code) {
lastErrorMessage = null;
String message;
Color foreground;
if ((code == null || code.trim().isEmpty())) {
if (emptyExpressionAllowed) {
return;
} else {
lastErrorMessage = "Empty expression not allowed."; /*I18N*/
message = lastErrorMessage;
foreground = warnMsgColor;
}
} else if (code.contains(PLACEHOLDER)) {
lastErrorMessage = "Replace '@' by inserting an element."; /*I18N*/
message = lastErrorMessage;
foreground = warnMsgColor;
} else {
if (parser != null) {
try {
Term term = parser.parse(code);
if (term != null && !BandArithmetic.areRastersEqualInSize(term)) {
message = "Referenced rasters must all be of the same size";
foreground = warnMsgColor;
} else if (term == null || !booleanExpressionPreferred || term.isB()) {
message = "Ok, no errors."; /*I18N*/
foreground = okMsgColor;
} else {
message = "Ok, but not a boolean expression."; /*I18N*/
foreground = warnMsgColor;
}
} catch (ParseException e) {
lastErrorMessage = e.getMessage();
message = lastErrorMessage;
foreground = warnMsgColor;
}
} else {
message = "Ok, no errors."; /*I18N*/
foreground = okMsgColor;
}
}
messageLabel.setText(message);
messageLabel.setToolTipText(message);
messageLabel.setForeground(foreground);
}
public String getLastErrorMessage() {
return lastErrorMessage;
}
protected void updateUIState() {
if (actionPane != null) {
actionPane.updateUIState();
}
}
private void pushCodeOnUndoStack(String code) {
if (undoBuffer.isEmpty() || !code.equals(undoBuffer.peek())) {
undoBuffer.push(code);
}
}
private static String getTypeString(int type) {
if (type == Term.TYPE_B) {
return "boolean";
} else if (type == Term.TYPE_I) {
return "int";
} else if (type == Term.TYPE_D) {
return "double";
} else {
return "?";
}
}
public static String getParamTypeString(String name, Term[] args) {
StringBuilder sb = new StringBuilder();
sb.append(name);
sb.append('(');
for (int i = 0; i < args.length; i++) {
if (i > 0) {
sb.append(',');
}
sb.append(getTypeString(args[i].getRetType()));
}
sb.append(')');
return sb.toString();
}
private static String getFunctionCallPattern(Function function) {
String functionName = function.getName();
int numArgs = function.getNumArgs();
if (numArgs == -1) {
return function.getName() + "(@, @, ...)";
} else if (numArgs == 0) {
return function.getName() + "()";
} else {
functionName += function.getName() + "(@";
for (int j = 1; j < numArgs; j++) {
functionName += ", @";
}
return functionName + ")";
}
}
class ActionPane extends JPanel {
private AbstractButton selAllButton;
private AbstractButton undoButton;
private AbstractButton clearButton;
private AbstractButton historyUpButton;
private AbstractButton historyDownButton;
public ActionPane() {
createUI();
}
protected void createUI() {
selAllButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/SelectAll24.gif"), false);
selAllButton.setName("selAllButton");
selAllButton.setToolTipText("Select all");
selAllButton.addActionListener(e -> selectAllCode());
clearButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Remove24.gif"), false);
clearButton.setName("clearButton");
clearButton.setToolTipText("Clear");
clearButton.addActionListener(e -> clearCode());
undoButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/Undo24.gif"), false);
undoButton.setName("undoButton");
undoButton.setToolTipText("Undo");
undoButton.addActionListener(e -> undoLastEdit());
historyUpButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/HistoryUp24.gif"), false);
historyUpButton.setName("historyUpButton");
historyUpButton.setToolTipText("Scroll history up");
historyUpButton.addActionListener(e -> {
if (history.size() > 0 && historyIndex < history.size()) {
historyIndex++;
setCode(history.get(historyIndex));
}
});
historyDownButton = ToolButtonFactory.createButton(UIUtils.loadImageIcon("icons/HistoryDown24.gif"),
false);
historyDownButton.setName("historyDownButton");
historyDownButton.setToolTipText("Scroll history down");
historyDownButton.addActionListener(e -> {
if (history.size() > 0 && historyIndex >= 0) {
final int oldHistoryIndex = historyIndex;
historyIndex--;
setCode(history.get(oldHistoryIndex));
}
});
add(selAllButton, BorderLayout.WEST);
add(clearButton, BorderLayout.CENTER);
add(undoButton, BorderLayout.EAST);
add(historyUpButton);
add(historyDownButton);
}
protected void updateUIState() {
String text = codeArea.getText();
final boolean hasText = text.length() > 0;
final boolean canUndo = !undoBuffer.isEmpty();
final boolean hasHistory = history != null && !history.isEmpty();
selAllButton.setEnabled(hasText);
clearButton.setEnabled(hasText);
undoButton.setEnabled(canUndo);
historyUpButton.setEnabled(hasHistory && historyIndex < history.size() - 1);
historyDownButton.setEnabled(hasHistory && historyIndex >= 0);
}
}
class ExpressionPaneDialog extends ModalDialog {
public ExpressionPaneDialog(Window parent, String title) {
super(parent, title, ExpressionPane.this, ModalDialog.ID_OK_CANCEL | ModalDialog.ID_HELP,
ExpressionPane.HELP_ID);
}
@Override
protected void onOK() {
updateCodeHistory();
super.onOK();
}
@Override
protected boolean verifyUserInput() {
checkCode();
String lastErrorMessage = getLastErrorMessage();
if (lastErrorMessage != null) {
JOptionPane.showMessageDialog(getJDialog(), lastErrorMessage, "Error", JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
}
}
| 32,117 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BoundaryOverlay.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/BoundaryOverlay.java | package org.esa.snap.ui;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.grender.Rendering;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
/**
* This class is an overlay that draws products from a {@link WorldMapPaneDataModel} and lets client decide how to
* render the selected product.
*
* @author Thomas Storm
* @author Tonio Fincke
* @author Marco Peters
*/
public abstract class BoundaryOverlay implements LayerCanvas.Overlay {
private final WorldMapPaneDataModel dataModel;
private LayerCanvas layerCanvas;
protected BoundaryOverlay(WorldMapPaneDataModel dataModel) {
this.dataModel = dataModel;
}
@Override
public void paintOverlay(LayerCanvas canvas, Rendering rendering) {
layerCanvas = canvas;
for (final GeoPos[] extraGeoBoundary : dataModel.getAdditionalGeoBoundaries()) {
drawGeoBoundary(rendering.getGraphics(), extraGeoBoundary, false, null, null);
}
final Product selectedProduct = dataModel.getSelectedProduct();
for (final Product product : dataModel.getProducts()) {
if (selectedProduct != product) {
drawProduct(rendering.getGraphics(), product, false);
}
}
handleSelectedProduct(rendering, selectedProduct);
}
protected abstract void handleSelectedProduct(Rendering rendering, Product selectedProduct);
protected void drawProduct(final Graphics2D g2d, final Product product, final boolean isCurrent) {
final GeoCoding geoCoding = product.getSceneGeoCoding();
if (geoCoding == null) {
return;
}
GeneralPath[] boundaryPaths = WorldMapPane.getGeoBoundaryPaths(product);
final String text = String.valueOf(product.getRefNo());
final PixelPos textCenter = getProductCenter(product);
drawGeoBoundary(g2d, boundaryPaths, isCurrent, text, textCenter);
}
private void drawGeoBoundary(final Graphics2D g2d, final GeneralPath[] boundaryPaths, final boolean isCurrent,
final String text, final PixelPos textCenter) {
final AffineTransform transform = layerCanvas.getViewport().getModelToViewTransform();
for (GeneralPath boundaryPath : boundaryPaths) {
boundaryPath.transform(transform);
drawPath(isCurrent, g2d, boundaryPath, 0.0f);
}
drawText(g2d, text, textCenter, 0.0f);
}
private void drawGeoBoundary(final Graphics2D g2d, final GeoPos[] geoBoundary, final boolean isCurrent,
final String text, final PixelPos textCenter) {
final GeneralPath gp = convertToPixelPath(geoBoundary);
drawPath(isCurrent, g2d, gp, 0.0f);
drawText(g2d, text, textCenter, 0.0f);
}
private void drawPath(final boolean isCurrent, Graphics2D g2d, final GeneralPath gp, final float offsetX) {
g2d = prepareGraphics2D(offsetX, g2d);
if (isCurrent) {
g2d.setColor(new Color(255, 200, 200, 30));
} else {
g2d.setColor(new Color(255, 255, 255, 30));
}
g2d.fill(gp);
if (isCurrent) {
g2d.setColor(new Color(255, 0, 0));
} else {
g2d.setColor(Color.WHITE);
}
g2d.draw(gp);
}
private GeneralPath convertToPixelPath(final GeoPos[] geoBoundary) {
final GeneralPath gp = new GeneralPath();
for (int i = 0; i < geoBoundary.length; i++) {
final GeoPos geoPos = geoBoundary[i];
final AffineTransform m2vTransform = layerCanvas.getViewport().getModelToViewTransform();
final Point2D viewPos = m2vTransform.transform(new PixelPos.Double(geoPos.lon, geoPos.lat), null);
if (i == 0) {
gp.moveTo(viewPos.getX(), viewPos.getY());
} else {
gp.lineTo(viewPos.getX(), viewPos.getY());
}
}
gp.closePath();
return gp;
}
private void drawText(Graphics2D g2d, final String text, final PixelPos textCenter, final float offsetX) {
if (text == null || textCenter == null) {
return;
}
g2d = prepareGraphics2D(offsetX, g2d);
final FontMetrics fontMetrics = g2d.getFontMetrics();
final Color color = g2d.getColor();
g2d.setColor(Color.black);
g2d.drawString(text,
(float)(textCenter.x - fontMetrics.stringWidth(text) / 2.0f),
(float)(textCenter.y + fontMetrics.getAscent() / 2.0f));
g2d.setColor(color);
}
private Graphics2D prepareGraphics2D(final float offsetX, Graphics2D g2d) {
if (offsetX != 0.0f) {
g2d = (Graphics2D) g2d.create();
final AffineTransform transform = g2d.getTransform();
final AffineTransform offsetTrans = new AffineTransform();
offsetTrans.setToTranslation(+offsetX, 0);
transform.concatenate(offsetTrans);
g2d.setTransform(transform);
}
return g2d;
}
private PixelPos getProductCenter(final Product product) {
final GeoCoding geoCoding = product.getSceneGeoCoding();
PixelPos centerPos = null;
if (geoCoding != null) {
final double pixelX = Math.floor(0.5f * product.getSceneRasterWidth()) + 0.5f;
final double pixelY = Math.floor(0.5f * product.getSceneRasterHeight()) + 0.5f;
final GeoPos geoPos = geoCoding.getGeoPos(new PixelPos(pixelX, pixelY), null);
final AffineTransform transform = layerCanvas.getViewport().getModelToViewTransform();
final Point2D point2D = transform.transform(new Point2D.Double(geoPos.getLon(), geoPos.getLat()), null);
centerPos = new PixelPos(point2D.getX(), point2D.getY());
}
return centerPos;
}
}
| 6,189 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
HSVImageProfilePane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/HSVImageProfilePane.java | /*
* Copyright (C) 2015 by Array Systems Computing Inc. http://www.array.ca
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 3 of the License, or (at your option)
* any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, see http://www.gnu.org/licenses/
*/
package org.esa.snap.ui;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.PropertyMap;
public class HSVImageProfilePane extends RGBImageProfilePane {
public final static String[] HSV_COMP_NAMES = new String[]{
"Hue", /*I18N*/
"Saturation", /*I18N*/
"Value" /*I18N*/
};
public HSVImageProfilePane(final PropertyMap preferences, final Product product,
final Product[] openedProducts, final int[] defaultBandIndices) {
super(preferences, product, openedProducts, defaultBandIndices);
storeInProductCheck.setText("Store HSV channels as virtual bands in current product");
}
@Override
protected String getComponentName(final int index) {
return HSV_COMP_NAMES[index];
}
}
| 1,539 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BoundaryOverlayImpl.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/BoundaryOverlayImpl.java | package org.esa.snap.ui;
import com.bc.ceres.grender.Rendering;
import org.esa.snap.core.datamodel.Product;
/**
* This class extends a {@link BoundaryOverlay} by the ability to draw a selected product.
*
* @author Thomas Storm
* @author Tonio Fincke
*/
public class BoundaryOverlayImpl extends BoundaryOverlay {
protected BoundaryOverlayImpl(WorldMapPaneDataModel dataModel) {
super(dataModel);
}
@Override
protected void handleSelectedProduct(Rendering rendering, Product selectedProduct) {
if (selectedProduct != null) {
drawProduct(rendering.getGraphics(), selectedProduct, true);
}
}
}
| 656 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DecimalCellEditor.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/DecimalCellEditor.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;
import javax.swing.DefaultCellEditor;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.Border;
import javax.swing.border.LineBorder;
import java.awt.Color;
import java.awt.Component;
/**
* A {@code DecimalCellEditor} which is able to validate the entered value.
* If the value is not valid the cell is marked with a red border and the value is rejected.
* The cell value is right aligned.
*/
public class DecimalCellEditor extends DefaultCellEditor {
private Border defaultBorder;
private double minValue;
private double maxValue;
/**
* Creates a new editor. The bounds of the valid value range are set
* to {@link Double#MIN_VALUE} and {@link Double#MAX_VALUE}
*/
public DecimalCellEditor() {
this(Double.MIN_VALUE, Double.MAX_VALUE);
}
/**
* Creates a new editor. The bounds of the valid value range are set
* to specified {@code minValue} and {@code maxValue}
*
* @param minValue the minimum value of the valid range
* @param maxValue the maximum value of the valid range
*/
public DecimalCellEditor(double minValue, double maxValue) {
super(new JTextField());
this.minValue = minValue;
this.maxValue = maxValue;
JTextField textField = (JTextField) getComponent();
defaultBorder = textField.getBorder();
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
int column) {
JComponent component = (JComponent) super.getTableCellEditorComponent(table, value, isSelected, row,
column);
final JTextField textField = (JTextField) component;
textField.selectAll();
textField.setBorder(defaultBorder);
textField.setHorizontalAlignment(JTextField.RIGHT);
return component;
}
@Override
public boolean stopCellEditing() {
JTextField textField = (JTextField) getComponent();
double value;
try {
value = Double.parseDouble(textField.getText());
} catch (NumberFormatException ignored) {
((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
return false;
}
boolean validValue = validateValue(value);
if (!validValue) {
((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
return false;
}
if (!super.stopCellEditing()) {
((JComponent) getComponent()).setBorder(new LineBorder(Color.red));
return false;
}
return true;
}
protected boolean validateValue(double value) {
return value >= minValue && value <= maxValue;
}
@Override
public Object getCellEditorValue() {
JTextField textField = (JTextField) getComponent();
try {
return Double.parseDouble(textField.getText());
} catch (NumberFormatException ignored) {
return Double.NaN;
}
}
}
| 3,928 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GridBagUtils.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/GridBagUtils.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;
import org.esa.snap.core.util.Guardian;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.util.StringTokenizer;
/**
* A utility class providing helper methods for <code>JPanel</code>s with a <code>GridBagLayout</code> layout manager.
*
* @author Sabine Embacher
* @version $Revision$ $Date$
*/
public class GridBagUtils {
public static JPanel createPanel() {
return new JPanel(new GridBagLayout());
}
public static JPanel createDefaultEmptyBorderPanel() {
JPanel panel = createPanel();
panel.setBorder(UIDefaults.getDialogBorder());
return panel;
}
/**
* Creates a <code>GridBagConstraints</code> instance with the attributes given as a comma separated key-value pairs
* in a text string.
* <p>According to the public <code>GridBagConstraints</code> attributes, the following key-value pairs are can
* occur in the text string:
* <p>
* <ul> <li><code>{@link GridBagConstraints#gridx gridx}=<b>RELATIVE</b>|<i>integer</i></code></li> <li><code>{@link
* GridBagConstraints#gridy gridy}=<b>RELATIVE</b>|<i>integer</i></code></li> <li><code>{@link
* GridBagConstraints#gridwidth gridwidth}=<b>REMAINDER</b>|<b>RELATIVE</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#gridheight gridheight}=<b>REMAINDER</b>|<b>RELATIVE</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#weightx weightx}=<i>double</i></code></li> <li><code>{@link
* GridBagConstraints#weighty weighty}=<i>double</i></code></li> <li><code>{@link GridBagConstraints#anchor
* anchor}=<b>CENTER</b>|<b>NORTH</b>|<b>NORTHEAST</b>|<b>EAST</b>|<b>SOUTHEAST</b>|<b>SOUTH</b>|<b>SOUTHWEST</b>|<b>WEST</b>|<b>NORTHWEST</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#fill fill}=<b>NONE</b>|<b>HORIZONTAL</b>|<b>VERTICAL</b>|<b>BOTH</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#insets insets.bottom}=<i>integer</i></code></li> <li><code>{@link
* GridBagConstraints#insets insets.left}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#insets
* insets.right}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#insets
* insets.top}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#ipadx
* ipadx}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#ipady ipady}=<i>integer</i></code></li>
* </ul>
*
* @param code a textual representation of the attributes to be set
*/
public static GridBagConstraints createConstraints(String code) {
GridBagConstraints gbc = new GridBagConstraints();
setAttributes(gbc, code);
return gbc;
}
/**
* Creates a <code>GridBagConstraints</code> instance with the following attributes:
* <ul>
* <li>{@link GridBagConstraints#anchor anchor}=<b>WEST</b></li>
* <li>{@link GridBagConstraints#insets insets.top}=<b>0</b></li>
* <li>{@link GridBagConstraints#insets insets.left}=<b>3</b></li>
* <li>{@link GridBagConstraints#insets insets.bottom}=<b>0</b></li>
* <li>{@link GridBagConstraints#insets insets.right}=<b>3</b></li>
* </ul>
*/
public static GridBagConstraints createDefaultConstraints() {
GridBagConstraints gbc = new GridBagConstraints();
gbc.anchor = GridBagConstraints.WEST;
gbc.insets = new Insets(0, 3, 0, 3);
return gbc;
}
/**
* Adds a component to a panel with a grid bag layout.
*
* @param panel the panel to which to add the component
* @param comp the component to be added
* @param gbc the grid bag constraints to be used, can be <code>null</code> if <code>code</code> is not
* <code>null</code>
*/
public static void addToPanel(JPanel panel, Component comp, GridBagConstraints gbc) {
LayoutManager layoutManager = panel.getLayout();
if (!(layoutManager instanceof GridBagLayout)) {
throw new IllegalArgumentException("'panel' does not have a GridBagLayout manager");
}
GridBagLayout gbl = (GridBagLayout) layoutManager;
gbl.setConstraints(comp, gbc);
panel.add(comp);
}
/**
* Adds a component to a panel with a grid bag layout. <p>For the <code>code</code> parameter, see also {@link
* #setAttributes(GridBagConstraints, String)}.
*
* @param panel the panel to which to add the component
* @param comp the component to be added
* @param gbc the grid bag constraints to be used, can be <code>null</code> if <code>code</code> is not
* <code>null</code>
* @param code the code containing the constraints, can be <code>null</code> if <code>gbc</code> is not
* <code>null</code>
* @see #setAttributes(GridBagConstraints, String)
*/
public static void addToPanel(JPanel panel, Component comp, GridBagConstraints gbc, String code) {
addToPanel(panel, comp, setAttributes(gbc, code));
}
public static void addHorizontalFiller(JPanel panel, GridBagConstraints gbc) {
int fillOld = gbc.fill;
int anchorOld = gbc.anchor;
double weightxOld = gbc.weightx;
if (gbc.gridx >= 0) {
gbc.gridx++;
}
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.anchor = GridBagConstraints.CENTER;
gbc.weightx = 1.0;
addToPanel(panel, new JLabel(" "), gbc);
gbc.weightx = weightxOld;
gbc.anchor = anchorOld;
gbc.fill = fillOld;
}
public static void addVerticalFiller(JPanel panel, GridBagConstraints gbc) {
int fillOld = gbc.fill;
int anchorOld = gbc.anchor;
double weightyOld = gbc.weighty;
if (gbc.gridy >= 0) {
gbc.gridy++;
}
gbc.fill = GridBagConstraints.VERTICAL;
gbc.anchor = GridBagConstraints.CENTER;
gbc.weighty = 200.0;
addToPanel(panel, new JLabel(" "), gbc);
gbc.weighty = weightyOld;
gbc.anchor = anchorOld;
gbc.fill = fillOld;
}
/**
* Sets the attributes of a given <code>GridBagConstraints</code> instance to the attribute values given as a comma
* separated key-value pairs in a text string.
* <p>According to the public <code>GridBagConstraints</code> attributes, the following key-value pairs are can
* occur in the text string:
* <p>
* <ul> <li><code>{@link GridBagConstraints#gridx gridx}=<b>RELATIVE</b>|<i>integer</i></code></li> <li><code>{@link
* GridBagConstraints#gridy gridy}=<b>RELATIVE</b>|<i>integer</i></code></li> <li><code>{@link
* GridBagConstraints#gridwidth gridwidth}=<b>REMAINDER</b>|<b>RELATIVE</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#gridheight gridheight}=<b>REMAINDER</b>|<b>RELATIVE</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#weightx weightx}=<i>double</i></code></li> <li><code>{@link
* GridBagConstraints#weighty weighty}=<i>double</i></code></li> <li><code>{@link GridBagConstraints#anchor
* anchor}=<b>CENTER</b>|<b>NORTH</b>|<b>NORTHEAST</b>|<b>EAST</b>|<b>SOUTHEAST</b>|<b>SOUTH</b>|<b>SOUTHWEST</b>|<b>WEST</b>|<b>NORTHWEST</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#fill fill}=<b>NONE</b>|<b>HORIZONTAL</b>|<b>VERTICAL</b>|<b>BOTH</b>|<i>integer</i></code></li>
* <li><code>{@link GridBagConstraints#insets insets.bottom}=<i>integer</i></code></li> <li><code>{@link
* GridBagConstraints#insets insets.left}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#insets
* insets.right}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#insets
* insets.top}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#ipadx
* ipadx}=<i>integer</i></code></li> <li><code>{@link GridBagConstraints#ipady ipady}=<i>integer</i></code></li>
* </ul>
*
* @param gbc the grid bag constraints whose attributes are to be set, must not be null
* @param code a textual representation of the attributes to be set
*/
public static GridBagConstraints setAttributes(GridBagConstraints gbc, String code) {
Guardian.assertNotNull("gbc", gbc);
if (code == null || code.trim().length() == 0) {
return gbc;
}
StringTokenizer st = new StringTokenizer(code, ",", false);
while (st.hasMoreTokens()) {
String token = st.nextToken();
int pos = token.indexOf('=');
if (pos < 0) {
throw new IllegalArgumentException("illegal token '" + token + "'");
}
String key = token.substring(0, pos).trim();
String value = token.substring(pos + 1).trim();
try {
if (key.equals("gridx")) {
if (value.equals("RELATIVE")) {
gbc.gridx = GridBagConstraints.RELATIVE;
} else {
gbc.gridx = Integer.parseInt(value);
}
} else if (key.equals("gridy")) {
if (value.equals("RELATIVE")) {
gbc.gridy = GridBagConstraints.RELATIVE;
} else {
gbc.gridy = Integer.parseInt(value);
}
} else if (key.equals("gridwidth")) {
if (value.equals("RELATIVE")) {
gbc.gridwidth = GridBagConstraints.RELATIVE;
} else if (value.equals("REMAINDER")) {
gbc.gridwidth = GridBagConstraints.REMAINDER;
} else {
gbc.gridwidth = Integer.parseInt(value);
}
} else if (key.equals("gridheight")) {
if (value.equals("RELATIVE")) {
gbc.gridheight = GridBagConstraints.RELATIVE;
} else if (value.equals("REMAINDER")) {
gbc.gridheight = GridBagConstraints.REMAINDER;
} else {
gbc.gridheight = Integer.parseInt(value);
}
} else if (key.equals("weightx")) {
gbc.weightx = Double.parseDouble(value);
} else if (key.equals("weighty")) {
gbc.weighty = Double.parseDouble(value);
} else if (key.equals("anchor")) {
if (value.equals("CENTER")) {
gbc.anchor = GridBagConstraints.CENTER;
} else if (value.equals("NORTH")) {
gbc.anchor = GridBagConstraints.NORTH;
} else if (value.equals("NORTHEAST")) {
gbc.anchor = GridBagConstraints.NORTHEAST;
} else if (value.equals("EAST")) {
gbc.anchor = GridBagConstraints.EAST;
} else if (value.equals("SOUTHEAST")) {
gbc.anchor = GridBagConstraints.SOUTHEAST;
} else if (value.equals("SOUTH")) {
gbc.anchor = GridBagConstraints.SOUTH;
} else if (value.equals("SOUTHWEST")) {
gbc.anchor = GridBagConstraints.SOUTHWEST;
} else if (value.equals("WEST")) {
gbc.anchor = GridBagConstraints.WEST;
} else if (value.equals("NORTHWEST")) {
gbc.anchor = GridBagConstraints.NORTHWEST;
} else {
gbc.anchor = Integer.parseInt(value);
}
} else if (key.equals("fill")) {
if (value.equals("NONE")) {
gbc.fill = GridBagConstraints.NONE;
} else if (value.equals("HORIZONTAL")) {
gbc.fill = GridBagConstraints.HORIZONTAL;
} else if (value.equals("VERTICAL")) {
gbc.fill = GridBagConstraints.VERTICAL;
} else if (value.equals("BOTH")) {
gbc.fill = GridBagConstraints.BOTH;
} else {
gbc.fill = Integer.parseInt(value);
}
} else if (key.equals("insets.bottom")) {
gbc.insets.bottom = Integer.parseInt(value);
} else if (key.equals("insets.left")) {
gbc.insets.left = Integer.parseInt(value);
} else if (key.equals("insets.right")) {
gbc.insets.right = Integer.parseInt(value);
} else if (key.equals("insets.top")) {
gbc.insets.top = Integer.parseInt(value);
} else if (key.equals("insets")) {
gbc.insets.top = gbc.insets.left = gbc.insets.right = gbc.insets.bottom = Integer.parseInt(value);
} else if (key.equals("ipadx")) {
gbc.ipadx = Integer.parseInt(value);
} else if (key.equals("ipady")) {
gbc.ipady = Integer.parseInt(value);
} else {
throw new IllegalArgumentException("unknown key '" + key + "'");
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("illegal value '" + value + "' for key '" + key + "'");
}
}
return gbc;
}
}
| 14,453 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ModelessDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/ModelessDialog.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;
import javax.swing.JDialog;
import java.awt.Dialog;
import java.awt.Window;
/**
* <p>A helper class used to implement standard modeless dialogs.</p>
* <p>The dialog can be used directly (which doesn't make much sense) or the class is used as base class in
* order to override the methods {@link #onApply()}, {@link #onClose()} etc. which are called if a user
* presses the corresponding button.<p>
*
* @author Norman Fomferra
* @since BEAM 4.2
*/
public class ModelessDialog extends AbstractDialog {
public static final int ID_APPLY_CLOSE = ID_APPLY | ID_CLOSE;
public static final int ID_APPLY_CLOSE_HELP = ID_APPLY_CLOSE | ID_HELP;
public ModelessDialog(Window parent, String title, int buttonMask, String helpID) {
this(parent, title, buttonMask, null, helpID);
}
public ModelessDialog(Window parent, String title, Object content, int buttonMask, String helpID) {
this(parent, title, content, buttonMask, null, helpID);
}
public ModelessDialog(Window parent, String title, Object content, int buttonMask, Object[] otherButtons,
String helpID) {
this(parent, title, buttonMask, otherButtons, helpID);
setContent(content);
}
public ModelessDialog(Window parent, String title, int buttonMask, Object[] otherButtons, String helpID) {
super(new JDialog(parent, title, Dialog.ModalityType.MODELESS), buttonMask, otherButtons, helpID);
}
/**
* This method is called, when the user clicks the "close" button of the bottom button row
* or the "close" button of the top bar of the dialog window. It can also be called directly.
* The method sets the button identifier to {@link #ID_CLOSE} and calls {@link #onClose()}.
*/
@Override
public void close() {
setButtonID(ID_CLOSE);
onClose();
}
}
| 2,605 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FormatedFileHistory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/FormatedFileHistory.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;
import org.esa.snap.core.dataio.DecodeQualification;
import org.esa.snap.core.dataio.ProductReaderPlugIn;
import org.esa.snap.core.util.Guardian;
import java.io.File;
/**
* <code>FileHistory</code> is a fixed-size array for the pathes of files opened/saved by a user. If a new file is added
* and the file history is full, the list of registered files is shifted so that the oldest file path is beeing
* skipped..
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class FormatedFileHistory extends FileHistory {
private final ProductReaderPlugIn _productReaderPlugIn;
public FormatedFileHistory(FileHistory history, ProductReaderPlugIn readerPlugIn) {
this(history.getMaxNumEntries(), history.getPropertyKey(), readerPlugIn);
}
public FormatedFileHistory(int maxNumEntries, String propertyKey, ProductReaderPlugIn readerPlugIn) {
super(maxNumEntries, propertyKey);
Guardian.assertNotNull("readerPlugIn", readerPlugIn);
_productReaderPlugIn = readerPlugIn;
}
@Override
protected boolean isValidItem(String item) {
if (super.isValidItem(item)) {
final File file = new File(item);
return _productReaderPlugIn.getDecodeQualification(file) != DecodeQualification.UNABLE;
}
return false;
}
}
| 2,076 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BorderLayoutUtils.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/BorderLayoutUtils.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;
import javax.swing.JComponent;
import javax.swing.JPanel;
import java.awt.BorderLayout;
/**
* A utility class providing helper methods for <code>JPanel</code>s with a <code>BorderLayout</code> layout manager.
*
* @author Sabine Embacher
* @version $Revision$ $Date$
*/
public class BorderLayoutUtils {
public static BorderLayout createDefaultBorderLayout() {
return new BorderLayout(7, 7);
}
public static JPanel createPanel() {
return new JPanel(new BorderLayout());
}
public static JPanel createPanel(JComponent centerComponent, JComponent placedComponent,
String borderLayoutConstraint) {
JPanel panel = createPanel();
return addToPanel(panel, centerComponent, placedComponent, borderLayoutConstraint);
}
public static JPanel createDefaultEmptyBorderPanel() {
JPanel centerPanel = new JPanel(createDefaultBorderLayout());
centerPanel.setBorder(UIDefaults.getDialogBorder());
return centerPanel;
}
public static JPanel addToPanel(JPanel panel,
JComponent centerComponent,
JComponent arrangedComponent,
String borderLayoutConstraint) {
panel.add(centerComponent, BorderLayout.CENTER);
panel.add(arrangedComponent, borderLayoutConstraint);
return panel;
}
}
| 2,184 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SequentialDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/SequentialDialog.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;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Canvas;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.Vector;
/**
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class SequentialDialog {
public static final int ID_BACK = 0x0001;
public static final int ID_NEXT = 0x0002;
public static final int ID_FINISH = 0x0004;
public static final int ID_CANCEL = 0x0008;
public static final int ID_HELP = 0x0010;
private JFrame frame;
private JDialog dialog;
private int buttonID = ID_CANCEL;
private Vector names = new Vector();
private int cardIndex = -1;
private String titleBase;
private JButton backButton = new JButton();
private JButton nextButton = new JButton();
private JButton finishButton = new JButton();
private JButton cancelButton = new JButton();
private JButton helpButton = new JButton();
private CardLayout cardLayout = new CardLayout(6, 6);
private JPanel cardPanel = new JPanel(cardLayout);
public SequentialDialog(JFrame frame, String titleBase) {
this(frame, titleBase, null, false);
}
public SequentialDialog(JFrame frame, String titleBase, Icon image, boolean hasHelp) {
this.frame = frame;
this.cardIndex = -1;
this.dialog = new JDialog(frame, titleBase, true);
this.titleBase = titleBase;
// Panel for buttons
JPanel buttonRow = new JPanel();
buttonRow.setLayout(new BoxLayout(buttonRow, BoxLayout.X_AXIS));
buttonRow.setBorder(BorderFactory.createEmptyBorder(6, 6, 6, 6));
JPanel panel1 = new JPanel(new BorderLayout());
panel1.add(BorderLayout.NORTH, new HorizontalLine(4, 4));
panel1.add(BorderLayout.SOUTH, buttonRow);
if (image != null) {
dialog.getContentPane().add(BorderLayout.WEST, new JLabel(image));
}
dialog.getContentPane().add(BorderLayout.CENTER, cardPanel);
dialog.getContentPane().add(BorderLayout.SOUTH, panel1);
backButton.setText("< Back");
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonID = ID_BACK;
onBack();
}
});
nextButton.setText("Next >");
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonID = ID_NEXT;
onNext();
}
});
finishButton.setText("Finish");
finishButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonID = ID_FINISH;
onFinish();
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonID = ID_CANCEL;
onCancel();
}
});
helpButton.setText("Help");
helpButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buttonID = ID_HELP;
onHelp();
}
});
Dimension hgap = new Dimension(6, 0);
buttonRow.add(Box.createHorizontalGlue());
buttonRow.add(backButton);
buttonRow.add(Box.createRigidArea(hgap));
buttonRow.add(nextButton);
buttonRow.add(Box.createRigidArea(hgap));
buttonRow.add(finishButton);
buttonRow.add(Box.createRigidArea(hgap));
buttonRow.add(cancelButton);
if (hasHelp) {
buttonRow.add(Box.createRigidArea(hgap));
buttonRow.add(helpButton);
}
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
buttonID = ID_CANCEL;
onCancel();
}
});
}
public JFrame getFrame() {
return frame;
}
public JDialog getDialog() {
return dialog;
}
public int getButtonID() {
return buttonID;
}
public int getCardCount() {
return cardPanel.getComponentCount();
}
public Component getCard(int index) {
return cardPanel.getComponent(index);
}
public Component getCurrentCard() {
return cardIndex < 0 ? null : getCard(cardIndex);
}
public String getCardName(int index) {
return (String) names.elementAt(index);
}
public void addCard(String name, Component card) {
cardPanel.add(card, name);
names.addElement(name);
}
public int show() {
if (getCardCount() > 0) {
showCard(0);
}
dialog.pack();
center();
dialog.setVisible(true);
return getButtonID();
}
public void hide() {
dialog.setVisible(false);
}
public void center() {
UIUtils.centerComponent(dialog, frame);
}
protected void onBack() {
showCard(getPreviousCardIndex());
}
protected void onNext() {
if (verifyUserInput()) {
showCard(getNextCardIndex());
}
}
protected void onFinish() {
if (verifyUserInput()) {
hide();
}
}
protected void onCancel() {
hide();
}
protected void onHelp() {
}
protected int getCurrentCardIndex() {
return cardIndex;
}
protected int getPreviousCardIndex() {
int cardIndexMin = 0;
return (cardIndex > cardIndexMin) ? (cardIndex - 1) : cardIndexMin;
}
protected int getNextCardIndex() {
int cardIndexMax = getCardCount() - 1;
return (cardIndex < cardIndexMax) ? (cardIndex + 1) : cardIndexMax;
}
protected void showCard(int index) {
cardIndex = index;
cardLayout.show(cardPanel, getCardName(index));
dialog.setTitle(titleBase
+ " - Step "
+ (cardIndex + 1)
+ " of "
+ getCardCount());
updateButtonStates();
}
protected void updateButtonStates() {
backButton.setEnabled(isBackPossible());
nextButton.setEnabled(isNextPossible());
finishButton.setEnabled(isFinishPossible());
}
protected boolean isBackPossible() {
return getCurrentCardIndex() > 0;
}
protected boolean isNextPossible() {
return getCurrentCardIndex() < getCardCount() - 1;
}
protected boolean isFinishPossible() {
return getCurrentCardIndex() == getCardCount() - 1;
}
protected boolean verifyUserInput() {
return true;
}
static class HorizontalLine extends Canvas {
Dimension prefSize;
HorizontalLine(int w, int h) {
prefSize = new Dimension(w, h);
}
@Override
public Dimension getMinimumSize() {
return prefSize;
}
@Override
public Dimension getPreferredSize() {
return prefSize;
}
@Override
public void paint(Graphics g) {
Dimension size = this.getSize();
int x1 = 0;
int x2 = size.width - 1;
int y1 = size.height / 2;
int y2 = y1 + 1;
g.setColor(this.getBackground().brighter());
g.drawLine(x1, y1, x2, y1);
g.setColor(this.getBackground().darker());
g.drawLine(x1, y2, x2, y2);
}
}
}
| 8,803 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PopupMenuHandler.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/PopupMenuHandler.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;
import org.esa.snap.core.util.Guardian;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Arrays;
/**
* A handler which can be registered on components as a mouse listener.
* <p>This handler pops-up a popup menu if the corresponding event is a popup menu trigger on a given platform. The
* popup-menu is created by the <code>PopupMenuFactory</code> instance passed to the constructor of this class.
*
* @author Norman Fomferra
* @see PopupMenuFactory
*/
public class PopupMenuHandler implements MouseListener, KeyListener {
private PopupMenuFactory popupMenuFactory;
/**
* Constructs a new pop-up menu handler for th given pop-up menu factory.
*
* @param popupMenuFactory the factory for the menu, must not be <code>null</code>
*/
public PopupMenuHandler(PopupMenuFactory popupMenuFactory) {
Guardian.assertNotNull("popupMenuFactory", popupMenuFactory);
this.popupMenuFactory = popupMenuFactory;
}
/**
* Invoked when the mouse has been clicked on a component.
*/
public void mouseClicked(MouseEvent event) {
maybeShowPopupMenu(event);
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
public void mousePressed(MouseEvent event) {
maybeShowPopupMenu(event);
}
/**
* Invoked when a mouse button has been released on a component.
*/
public void mouseReleased(MouseEvent event) {
maybeShowPopupMenu(event);
}
/**
* Invoked when the mouse enters a component.
*/
public void mouseEntered(MouseEvent event) {
}
/**
* Invoked when the mouse exits a component.
*/
public void mouseExited(MouseEvent event) {
}
/**
* Invoked when a key has been pressed.
*/
public void keyPressed(KeyEvent event) {
}
/**
* Invoked when a key has been released.
*/
public void keyReleased(KeyEvent event) {
}
/**
* Invoked when a key has been typed. This event occurs when a key press is followed by a key release.
*/
public void keyTyped(KeyEvent event) {
}
private void maybeShowPopupMenu(MouseEvent event) {
if (event.isPopupTrigger()) {
if (event.getComponent().isVisible()) {
showPopupMenu(event);
}
}
}
private void showPopupMenu(MouseEvent event) {
JPopupMenu popupMenu = popupMenuFactory.createPopupMenu(event.getComponent());
if (popupMenu == null) {
popupMenu = popupMenuFactory.createPopupMenu(event);
}
if (popupMenu != null) {
rearrangeMenuItems(popupMenu);
UIUtils.showPopup(popupMenu, event);
}
}
private void rearrangeMenuItems(JPopupMenu popupMenu) {
Component[] components = popupMenu.getComponents();
Arrays.sort(components, (o1, o2) -> getGroupName(o1).compareToIgnoreCase(getGroupName(o2)));
popupMenu.removeAll();
Component lastComponent = null;
String lastGroupName = null;
for (Component component : components) {
String groupName = getGroupName(component);
if (lastGroupName != null
&& !lastGroupName.equals(groupName)
&& !(lastComponent instanceof JSeparator)) {
popupMenu.addSeparator();
}
lastGroupName = groupName;
lastComponent = component;
if (component instanceof JMenuItem) {
popupMenu.add((JMenuItem) component);
} else if (component instanceof Action) {
popupMenu.add((Action) component);
} else {
popupMenu.add(component);
}
}
}
private String getGroupName(Component component) {
Action action = null;
if (component instanceof AbstractButton) {
action = ((AbstractButton) component).getAction();
} else if (component instanceof Action) {
action = (Action) component;
}
if (action != null) {
Object parent = action.getValue("parent");
if (parent != null) {
return parent.toString();
}
}
return "";
}
}
| 5,304 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RegionBoundsInputUI.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/RegionBoundsInputUI.java | package org.esa.snap.ui;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.swing.binding.BindingContext;
import tec.uom.se.unit.Units;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;
/**
* This user interface provides a world map and text fields to define region bounds.
* The input values from the text fields and from the world map are reflected in the {@link BindingContext}, which can
* be retrieved using {@link #getBindingContext()}.
*/
public class RegionBoundsInputUI {
public final static String PROPERTY_NORTH_BOUND = RegionSelectableWorldMapPane.NORTH_BOUND;
public final static String PROPERTY_EAST_BOUND = RegionSelectableWorldMapPane.EAST_BOUND;
public final static String PROPERTY_SOUTH_BOUND = RegionSelectableWorldMapPane.SOUTH_BOUND;
public final static String PROPERTY_WEST_BOUND = RegionSelectableWorldMapPane.WEST_BOUND;
private final BindingContext bindingContext;
private final JLabel northLabel;
private final JFormattedTextField northLatField;
private final JLabel northDegreeLabel;
private final JLabel eastLabel;
private final JFormattedTextField eastLonField;
private final JLabel eastDegreeLabel;
private final JLabel southLabel;
private final JFormattedTextField southLatField;
private final JLabel southDegreeLabel;
private final JLabel westLabel;
private final JFormattedTextField westLonField;
private final JLabel westDegreeLabel;
private final JPanel worldMapPaneUI;
private JPanel ui;
/**
* Initializes a RegionBoundsInputUI.
* This constructor creates the user interface and a binding context with default values.
* The created binding context can be retrieved via {@link #getBindingContext()}.
*/
public RegionBoundsInputUI() {
this(75, 30, 35, -15);
}
/**
* Initializes a RegionBoundsInputUI with the given parameters.
* If the parameters are valid geographic coordinates, they are used to initialize the user
* interface and to create a binding context.
* If the values are invalid, default values will be used.
* The created binding context can be retrieved via {@link #getBindingContext()}.
*
* @param northBound The northern bounding latitude value
* @param eastBound The eastern bound longitude value
* @param southBound The southern bound latitude value
* @param westBound The western bound longitude value
*/
public RegionBoundsInputUI(final double northBound,
final double eastBound,
final double southBound,
final double westBound) {
this(createBindingContext(northBound, eastBound, southBound, westBound));
}
/**
* Initializes a RegionBoundsInputUI with the given {@link BindingContext bindingContext}.
* The bindingContext has to contain four parameters: {@link #PROPERTY_NORTH_BOUND northBound} ,
* {@link #PROPERTY_SOUTH_BOUND southBound}, {@link #PROPERTY_WEST_BOUND westBound} and
* {@link #PROPERTY_EAST_BOUND eastBound}.
* If the bindingContext contains geographic coordinates, these coordinates are used to initialize the user
* interface.
*
* @param bindingContext The binding context which is needed for initialisation.
*/
public RegionBoundsInputUI(final BindingContext bindingContext) {
RegionSelectableWorldMapPane.ensureValidBindingContext(bindingContext);
this.bindingContext = bindingContext;
final WorldMapPaneDataModel worldMapPaneDataModel = new WorldMapPaneDataModel();
final RegionSelectableWorldMapPane worldMapPane = new RegionSelectableWorldMapPane(worldMapPaneDataModel, bindingContext);
worldMapPaneUI = worldMapPane.createUI();
northLabel = new JLabel("North:");
northDegreeLabel = createDegreeLabel();
northLatField = createTextField();
eastDegreeLabel = createDegreeLabel();
eastLabel = new JLabel("East:");
eastLonField = createTextField();
southLabel = new JLabel("South:");
southDegreeLabel = createDegreeLabel();
southLatField = createTextField();
westDegreeLabel = createDegreeLabel();
westLabel = new JLabel("West:");
westLonField = createTextField();
bindingContext.bind(PROPERTY_WEST_BOUND, westLonField);
bindingContext.bind(PROPERTY_EAST_BOUND, eastLonField);
bindingContext.bind(PROPERTY_NORTH_BOUND, northLatField);
bindingContext.bind(PROPERTY_SOUTH_BOUND, southLatField);
}
/**
* Enables or disables all child components.
*
* @param enabled -
*/
public void setEnabled(final boolean enabled) {
northLabel.setEnabled(enabled);
northLatField.setEnabled(enabled);
northDegreeLabel.setEnabled(enabled);
eastLabel.setEnabled(enabled);
eastLonField.setEnabled(enabled);
eastDegreeLabel.setEnabled(enabled);
southLabel.setEnabled(enabled);
southLatField.setEnabled(enabled);
southDegreeLabel.setEnabled(enabled);
westLabel.setEnabled(enabled);
westLonField.setEnabled(enabled);
westDegreeLabel.setEnabled(enabled);
worldMapPaneUI.setEnabled(enabled);
}
/**
* @return a {@link JPanel} which contains the user interface elements
*/
public JPanel getUI() {
if (ui == null) {
final JPanel fieldsPanel = GridBagUtils.createPanel();
final GridBagConstraints fieldsGBC = GridBagUtils.createDefaultConstraints();
fieldsGBC.anchor = GridBagConstraints.WEST;
fieldsGBC.gridy = 0;
GridBagUtils.addToPanel(fieldsPanel, northLabel, fieldsGBC, "gridx=3");
GridBagUtils.addToPanel(fieldsPanel, northLatField, fieldsGBC, "gridx=4");
GridBagUtils.addToPanel(fieldsPanel, northDegreeLabel, fieldsGBC, "gridx=5");
fieldsGBC.gridy = 1;
GridBagUtils.addToPanel(fieldsPanel, westLabel, fieldsGBC, "gridx=0");
GridBagUtils.addToPanel(fieldsPanel, westLonField, fieldsGBC, "gridx=1");
GridBagUtils.addToPanel(fieldsPanel, westDegreeLabel, fieldsGBC, "gridx=2");
GridBagUtils.addToPanel(fieldsPanel, eastLabel, fieldsGBC, "gridx=6");
GridBagUtils.addToPanel(fieldsPanel, eastLonField, fieldsGBC, "gridx=7");
GridBagUtils.addToPanel(fieldsPanel, eastDegreeLabel, fieldsGBC, "gridx=8");
fieldsGBC.gridy = 2;
GridBagUtils.addToPanel(fieldsPanel, southLabel, fieldsGBC, "gridx=3");
GridBagUtils.addToPanel(fieldsPanel, southLatField, fieldsGBC, "gridx=4");
GridBagUtils.addToPanel(fieldsPanel, southDegreeLabel, fieldsGBC, "gridx=5");
ui = GridBagUtils.createPanel();
final GridBagConstraints mainGBC = GridBagUtils.createDefaultConstraints();
mainGBC.fill = GridBagConstraints.HORIZONTAL;
mainGBC.gridy = 0;
GridBagUtils.addToPanel(ui, fieldsPanel, mainGBC);
mainGBC.gridy = 1;
GridBagUtils.addToPanel(ui, worldMapPaneUI, mainGBC, "insets.top=10");
}
return ui;
}
/**
* Returns the binding context which contains property values {@link #PROPERTY_NORTH_BOUND northBound} ,
* {@link #PROPERTY_SOUTH_BOUND southBound}, {@link #PROPERTY_WEST_BOUND westBound}, and
* {@link #PROPERTY_EAST_BOUND eastBound}. This method should be used to get the bounds set by the UI components.
* It is needed when no binding context has been passed to the RegionBoundsInputUI initially.
*
* @return the binding context.
*/
public BindingContext getBindingContext() {
return bindingContext;
}
private static BindingContext createBindingContext(double northBound, double eastBound, double southBound, double westBound) {
final Bounds bounds = new Bounds(northBound, eastBound, southBound, westBound);
final PropertyContainer container = PropertyContainer.createObjectBacked(bounds);
return new BindingContext(container);
}
private JFormattedTextField createTextField() {
final int fieldWidth = 60;
final DoubleFormatter textFormatter = new DoubleFormatter("###0.0##");
final JFormattedTextField textField = new JFormattedTextField(textFormatter);
textField.setHorizontalAlignment(JTextField.RIGHT);
final int defaultHeight = textField.getPreferredSize().height;
final Dimension size = new Dimension(fieldWidth, defaultHeight);
textField.setMinimumSize(size);
textField.setPreferredSize(size);
textField.setMaximumSize(size);
return textField;
}
private JLabel createDegreeLabel() {
return new JLabel(Units.DEGREE_ANGLE.toString());
}
private static class DoubleFormatter extends JFormattedTextField.AbstractFormatter {
private final DecimalFormat format;
DoubleFormatter(String pattern) {
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
format = new DecimalFormat(pattern, decimalFormatSymbols);
format.setParseIntegerOnly(false);
format.setParseBigDecimal(false);
format.setDecimalSeparatorAlwaysShown(true);
}
@Override
public Object stringToValue(String text) throws ParseException {
return format.parse(text).doubleValue();
}
@Override
public String valueToString(Object value) throws ParseException {
if (value == null) {
return "";
}
return format.format(value);
}
}
private static class Bounds {
double northBound;
double eastBound;
double southBound;
double westBound;
private Bounds(double northBound, double eastBound, double southBound, double westBound) {
this.northBound = northBound;
this.eastBound = eastBound;
this.southBound = southBound;
this.westBound = westBound;
}
}
}
| 10,494 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultAppContext.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/DefaultAppContext.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;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.util.DefaultPropertyMap;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.ui.product.ProductSceneView;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import java.awt.Window;
/**
* This trivial implementation of the {@link AppContext} class
* is only for testing.
*/
public class DefaultAppContext implements AppContext {
private Window applicationWindow;
private String applicationName;
private ProductManager productManager;
private Product selectedProduct;
private PropertyMap preferences;
private ProductSceneView selectedSceneView;
public DefaultAppContext(String applicationName) {
this(applicationName,
new JFrame(applicationName),
new ProductManager(),
new DefaultPropertyMap());
}
public DefaultAppContext(String applicationName,
Window applicationWindow,
ProductManager productManager,
PropertyMap preferences) {
this.applicationWindow = applicationWindow;
this.applicationName = applicationName;
this.productManager = productManager;
this.preferences = preferences;
}
@Override
public String getApplicationName() {
return applicationName;
}
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public Window getApplicationWindow() {
return applicationWindow;
}
public void setApplicationWindow(Window applicationWindow) {
this.applicationWindow = applicationWindow;
}
@Override
public PropertyMap getPreferences() {
return preferences;
}
public void setPreferences(PropertyMap preferences) {
this.preferences = preferences;
}
@Override
public ProductManager getProductManager() {
return productManager;
}
public void setProductManager(ProductManager productManager) {
this.productManager = productManager;
}
@Override
public Product getSelectedProduct() {
return selectedProduct;
}
public void setSelectedProduct(Product selectedProduct) {
this.selectedProduct = selectedProduct;
}
@Override
public void handleError(String message, Throwable t) {
if (t != null) {
t.printStackTrace();
}
JOptionPane.showMessageDialog(getApplicationWindow(), message);
}
@Override
public ProductSceneView getSelectedProductSceneView() {
return selectedSceneView;
}
public void setSelectedSceneView(ProductSceneView selectedView) {
this.selectedSceneView = selectedView;
}
}
| 3,608 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FileHistory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/FileHistory.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;
import java.io.File;
/**
* <code>FileHistory</code> is a fixed-size array for the pathes of files opened/saved by a user. If a new file is added
* and the file history is full, the list of registered files is shifted so that the oldest file path is beeing
* skipped..
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class FileHistory extends UserInputHistory {
public FileHistory(int maxNumEntries, String propertyKey) {
super(maxNumEntries, propertyKey);
}
@Override
protected boolean isValidItem(String item) {
if (item != null && item.length() > 0) {
return new File(item).exists();
}
return false;
}
}
| 1,447 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractImageInfoEditorModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/AbstractImageInfoEditorModel.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;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.datamodel.Scaling;
import org.esa.snap.core.datamodel.Stx;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.EventListenerList;
/**
* Unstable interface. Do not use.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
* @since BEAM 4.5.1
*/
public abstract class AbstractImageInfoEditorModel implements ImageInfoEditorModel {
private final ImageInfo imageInfo;
private final EventListenerList listenerList;
private Scaling scaling;
private Stx stx;
private String name;
private String unit;
private Double histogramViewGain;
private Double minHistogramViewSample;
private Double maxHistogramViewSample;
protected AbstractImageInfoEditorModel(ImageInfo imageInfo) {
this.imageInfo = imageInfo;
this.listenerList = new EventListenerList();
}
@Override
public ImageInfo getImageInfo() {
return imageInfo;
}
@Override
public void setDisplayProperties(String name, String unit, Stx stx, Scaling scaling) {
setParameterName(name);
setParameterUnit(unit);
setSampleScaling(scaling);
setSampleStx(stx);
fireStateChanged();
}
@Override
public String getParameterName() {
return name;
}
private void setParameterName(String name) {
this.name = name;
}
@Override
public String getParameterUnit() {
return unit;
}
private void setParameterUnit(String unit) {
this.unit = unit;
}
@Override
public Scaling getSampleScaling() {
return scaling;
}
@Override
public void setSampleScaling(Scaling scaling) {
Assert.notNull(scaling, "scaling");
this.scaling = scaling;
}
@Override
public Stx getSampleStx() {
return stx;
}
private void setSampleStx(Stx stx) {
Assert.notNull(stx, "stx");
this.stx = stx;
}
@Override
public double getMinSample() {
return scaling == null ? 0 : stx.getMinimum();
}
@Override
public double getMaxSample() {
return scaling == null ? 0 : stx.getMaximum();
}
@Override
public boolean isHistogramAvailable() {
return getHistogramBins() != null && getHistogramBins().length > 0;
}
@Override
public int[] getHistogramBins() {
return stx == null ? null : stx.getHistogramBins();
}
@Override
public double getMinHistogramViewSample() {
if (minHistogramViewSample != null) {
return minHistogramViewSample;
}
return getMinSample();
}
@Override
public void setMinHistogramViewSample(double minViewSample) {
minHistogramViewSample = minViewSample;
}
@Override
public double getMaxHistogramViewSample() {
if (maxHistogramViewSample != null) {
return maxHistogramViewSample;
}
return getMaxSample();
}
@Override
public void setMaxHistogramViewSample(double maxViewSample) {
maxHistogramViewSample = maxViewSample;
}
@Override
public double getHistogramViewGain() {
if (histogramViewGain != null) {
return histogramViewGain;
}
return 1.0;
}
@Override
public void setHistogramViewGain(double gain) {
histogramViewGain = gain;
}
@Override
public void addChangeListener(ChangeListener l) {
listenerList.add(ChangeListener.class, l);
}
@Override
public void removeChangeListener(ChangeListener l) {
listenerList.remove(ChangeListener.class, l);
}
@Override
public void fireStateChanged() {
final ChangeEvent event = new ChangeEvent(this);
ChangeListener[] changeListeners = listenerList.getListeners(ChangeListener.class);
for (ChangeListener changeListener : changeListeners) {
changeListener.stateChanged(event);
}
}
}
| 4,833 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UIDefaults.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/UIDefaults.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;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import java.awt.Color;
import java.awt.Font;
/**
* A utility class which creates GUI componants with default settings.
*
* @author Sabine Embacher
* @version $Revision$ $Date$
*/
public class UIDefaults {
public static final Color HEADER_COLOR = new Color(82, 109, 165);
public static final int INSET_SIZE = 6;
public static final EmptyBorder DIALOG_BORDER = new EmptyBorder(INSET_SIZE, INSET_SIZE, INSET_SIZE, INSET_SIZE);
public static final Border SLIDER_BOX_BORDER = BorderFactory.createEtchedBorder(new Color(166, 202, 240),
new Color(91, 135, 206));
private static final Font _verySmallSansSerifFont = new Font("SansSerif", Font.PLAIN, 9);
private static final Font _smallSansSerifFont = new Font("SansSerif", Font.PLAIN, 11);
public static EmptyBorder getDialogBorder() {
return DIALOG_BORDER;
}
public static Font getVerySmallSansSerifFont() {
return _verySmallSansSerifFont;
}
public static Font getSmallSansSerifFont() {
return _smallSansSerifFont;
}
}
| 1,987 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ModalDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/ModalDialog.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;
import javax.swing.JDialog;
import java.awt.Window;
/**
* A helper class used to implement standard modal dialogs.
* <p>The dialog can be used directly or the class is used as base class in order to override the methods {@link #onOK()},
* {@link #onCancel()} etc. which are called if a user presses the corresponding button.
* <p>
*
* @author Norman Fomferra
* @since BEAM 1.0
*/
public class ModalDialog extends AbstractDialog {
public static final int ID_OK_CANCEL = ID_OK | ID_CANCEL;
public static final int ID_OK_CANCEL_HELP = ID_OK_CANCEL | ID_HELP;
public static final int ID_OK_APPLY_CANCEL = ID_OK | ID_APPLY | ID_CANCEL;
public static final int ID_OK_APPLY_CANCEL_HELP = ID_OK_APPLY_CANCEL | ID_HELP;
public static final int ID_YES_NO = ID_YES | ID_NO;
public static final int ID_YES_NO_HELP = ID_YES_NO | ID_HELP;
public ModalDialog(Window parent, String title, int buttonMask, String helpID) {
this(parent, title, buttonMask, null, helpID);
}
public ModalDialog(Window parent, String title, Object content, int buttonMask, String helpID) {
this(parent, title, content, buttonMask, null, helpID);
}
public ModalDialog(Window parent, String title, Object content, int buttonMask, Object[] otherButtons,
String helpID) {
this(parent, title, buttonMask, otherButtons, helpID);
setContent(content);
}
public ModalDialog(Window parent, String title, int buttonMask, Object[] otherButtons, String helpID) {
super(new JDialog(parent, title, JDialog.DEFAULT_MODALITY_TYPE), buttonMask, otherButtons, helpID);
}
/**
* This method is called, when the user clicks the "cancel" button or the "close" button of
* the top bar of the dialog window. It can also be called directly.
* The method sets the button identifier to {@link #ID_CANCEL} and calls {@link #onCancel()}.
*/
@Override
public void close() {
setButtonID(ID_CANCEL);
onCancel();
}
}
| 2,779 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DefaultImageInfoEditorModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/DefaultImageInfoEditorModel.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;
import com.bc.ceres.core.Assert;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.image.ImageManager;
import java.awt.Color;
/**
* Unstable interface. Do not use.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
* @since BEAM 4.5.1
*/
public class DefaultImageInfoEditorModel extends AbstractImageInfoEditorModel {
public DefaultImageInfoEditorModel(ImageInfo imageInfo) {
super(imageInfo);
Assert.argument(imageInfo.getColorPaletteDef() != null, "imageInfo");
}
@Override
public boolean isColorEditable() {
return true;
}
@Override
public int getSliderCount() {
return getImageInfo().getColorPaletteDef().getNumPoints();
}
@Override
public double getSliderSample(int index) {
return getImageInfo().getColorPaletteDef().getPointAt(index).getSample();
}
@Override
public void setSliderSample(int index, double sample) {
getImageInfo().getColorPaletteDef().getPointAt(index).setSample(sample);
fireStateChanged();
}
@Override
public Color getSliderColor(int index) {
return getImageInfo().getColorPaletteDef().getPointAt(index).getColor();
}
@Override
public void setSliderColor(int index, Color color) {
getImageInfo().getColorPaletteDef().getPointAt(index).setColor(color);
fireStateChanged();
}
@Override
public void createSliderAfter(int index) {
final boolean b = getImageInfo().getColorPaletteDef().createPointAfter(index, getSampleScaling());
if (b) {
fireStateChanged();
}
}
@Override
public void removeSlider(int index) {
getImageInfo().getColorPaletteDef().removePointAt(index);
fireStateChanged();
}
@Override
public Color[] createColorPalette() {
return ImageManager.createColorPalette(getImageInfo());
// return getImageInfo().getColorPaletteDef().createColorPalette(getSampleScaling());
}
@Override
public boolean isGammaUsed() {
return false;
}
@Override
public double getGamma() {
return 1;
}
@Override
public void setGamma(double gamma) {
// no support
}
@Override
public byte[] getGammaCurve() {
return null;
}
}
| 3,072 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SelectExportMethodDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/SelectExportMethodDialog.java | /*
* Created at 31.07.2004 18:25:19
* Copyright (c) 2004 by Norman Fomferra
*/
package org.esa.snap.ui;
import org.openide.util.HelpCtx;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SelectExportMethodDialog {
public final static int EXPORT_TO_CLIPBOARD = 0;
public final static int EXPORT_TO_FILE = 1;
public final static int EXPORT_CANCELED = -1;
/**
* Opens a modal dialog that asks the user which method to use in order to export data.
*
* @return {@link #EXPORT_TO_CLIPBOARD}, {@link #EXPORT_TO_FILE} or {@link #EXPORT_CANCELED}
*/
public static int run(Component parentComponent, String title, String text, String helpID) {
return run(parentComponent, title, text, new JCheckBox[0], helpID);
}
/**
* Opens a modal dialog that asks the user which method to use in order to export data.
*
* @return {@link #EXPORT_TO_CLIPBOARD}, {@link #EXPORT_TO_FILE} or {@link #EXPORT_CANCELED}
*/
public static int run(Component parentComponent, String title, String text, JCheckBox[] options, String helpID) {
DialogDescriptor descriptor = createDialog(parentComponent, title, text, helpID, options);
descriptor.dialog.setVisible(true);
return getChosenMethod(descriptor);
}
private static int getChosenMethod(DialogDescriptor descriptor) {
int method = EXPORT_CANCELED;
final Object value = descriptor.optionPane.getValue();
if (descriptor.copyToClipboardButton.equals(value)) {
method = EXPORT_TO_CLIPBOARD;
} else if (descriptor.writeToFileButton.equals(value)) {
method = EXPORT_TO_FILE;
}
return method;
}
private static DialogDescriptor createDialog(Component parentComponent, String title, String text, String helpID, JCheckBox[] options) {
final String copyToClipboardText = "Copy to Clipboard"; /*I18N*/
final String writeToFileText = "Write to File"; /*I18N*/
final String cancelText = "Cancel"; /*I18N*/
final String iconDir = "/org/esa/snap/resources/images/icons/";
final ImageIcon copyIcon = new ImageIcon(SelectExportMethodDialog.class.getResource(iconDir + "Copy16.gif"));
final ImageIcon saveIcon = new ImageIcon(SelectExportMethodDialog.class.getResource(iconDir + "Save16.gif"));
final JButton copyToClipboardButton = new JButton(copyToClipboardText);
copyToClipboardButton.setMnemonic('b');
copyToClipboardButton.setIcon(copyIcon);
final JButton writeToFileButton = new JButton(writeToFileText);
writeToFileButton.setMnemonic('W');
writeToFileButton.setIcon(saveIcon);
final JButton cancelButton = new JButton(cancelText);
cancelButton.setMnemonic('C');
cancelButton.setIcon(null);
final JPanel panel = new JPanel(new GridBagLayout());
final JPanel checkboxPanel = new JPanel(new GridBagLayout());
final GridBagConstraints c = new GridBagConstraints();
c.anchor = GridBagConstraints.LINE_START;
c.gridx = 0;
c.gridy = GridBagConstraints.RELATIVE;
for (JCheckBox option : options) {
checkboxPanel.add(option, c);
}
c.gridx = 0;
c.gridy = 0;
panel.add(checkboxPanel, c);
final JPanel buttonPanel = new JPanel(new FlowLayout());
c.gridy = GridBagConstraints.RELATIVE;
buttonPanel.add(copyToClipboardButton, c);
buttonPanel.add(writeToFileButton, c);
buttonPanel.add(cancelButton, c);
c.gridx = 0;
c.gridy = 1;
panel.add(buttonPanel, c);
final JOptionPane optionPane = new JOptionPane(text, /*I18N*/
JOptionPane.QUESTION_MESSAGE,
JOptionPane.DEFAULT_OPTION,
null,
new JPanel[]{panel},
copyToClipboardButton);
final JDialog dialog = optionPane.createDialog(parentComponent, title);
dialog.getContentPane().setLayout(new BoxLayout(dialog.getContentPane(), BoxLayout.Y_AXIS));
if (helpID != null) {
HelpCtx.setHelpIDString((JComponent) optionPane, helpID);
}
// Create action listener for all 3 buttons (as instance of an anonymous class)
final ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
optionPane.setValue(e.getSource());
dialog.setVisible(false);
dialog.dispose();
}
};
copyToClipboardButton.addActionListener(actionListener);
writeToFileButton.addActionListener(actionListener);
cancelButton.addActionListener(actionListener);
return new DialogDescriptor(dialog, optionPane, copyToClipboardButton, writeToFileButton);
}
private static class DialogDescriptor {
private final JDialog dialog;
private final JOptionPane optionPane;
private final JButton copyToClipboardButton;
private final JButton writeToFileButton;
private DialogDescriptor(JDialog dialog, JOptionPane optionPane, JButton copyToClipboardButton, JButton writeToFileButton) {
this.dialog = dialog;
this.optionPane = optionPane;
this.copyToClipboardButton = copyToClipboardButton;
this.writeToFileButton = writeToFileButton;
}
}
}
| 6,021 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SnapFileChooser.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/SnapFileChooser.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;
import com.bc.ceres.binding.ConversionException;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.SystemUtils;
import org.esa.snap.core.util.converters.RectangleConverter;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.runtime.Config;
import org.esa.snap.vfs.NioFile;
import org.esa.snap.vfs.preferences.model.VFSRemoteFileRepositoriesController;
import org.esa.snap.vfs.preferences.model.VFSRemoteFileRepository;
import org.esa.snap.vfs.remote.VFSPath;
import org.esa.snap.vfs.ui.file.chooser.VirtualFileSystemView;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.filechooser.FileSystemView;
import java.awt.Component;
import java.awt.Container;
import java.awt.Graphics;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.HeadlessException;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.util.List;
import java.util.Objects;
import java.util.logging.Level;
import java.util.prefs.Preferences;
/**
* The general SNAP file chooser.
*
* @author Norman Fomferra
*/
public class SnapFileChooser extends JFileChooser {
private static final Object syncFileFiltersObject = new Object();
private static final String PREFERENCES_BOUNDS_OPEN = "snap.fileChooser.dialogBounds.open";
private static final String PREFERENCES_BOUNDS_SAVE = "snap.fileChooser.dialogBounds.save";
private static final String PREFERENCES_BOUNDS_CUSTOM = "snap.fileChooser.dialogBounds.custom";
private final ResizeHandler resizeHandler;
private final Preferences snapPreferences;
private String lastFilename;
public SnapFileChooser() {
this(null, null);
}
public SnapFileChooser(FileSystemView fsv) {
this(null, fsv);
}
public SnapFileChooser(File currentDirectory) {
this(currentDirectory, null);
}
public SnapFileChooser(File currentDirectory, FileSystemView fsv) {
super(currentDirectory, fsv);
snapPreferences = Config.instance("snap").preferences();
resizeHandler = new ResizeHandler();
init();
}
@Override
public void setFileSystemView(FileSystemView fileSystemView) {
if (fileSystemView == null) {
throw new NullPointerException("fileSystemView is null");
}
Path configFile = VFSRemoteFileRepositoriesController.getDefaultConfigFilePath();
List<VFSRemoteFileRepository> vfsRepositories;
try {
vfsRepositories = VFSRemoteFileRepositoriesController.getVFSRemoteFileRepositories(configFile);
} catch (IOException e) {
throw new IllegalStateException(e);
}
if (!vfsRepositories.isEmpty()) {
VirtualFileSystemView fileSystemViewWrapper = new VirtualFileSystemView(fileSystemView, vfsRepositories) {
@Override
protected void notifyUser(String title, String message) {
showMessageDialog(title, message);
}
};
super.setFileSystemView(fileSystemViewWrapper);
} else {
super.setFileSystemView(fileSystemView);
}
}
private void showMessageDialog(String title, String message) {
JOptionPane.showMessageDialog(this, message, title, JOptionPane.WARNING_MESSAGE);
}
@Override
public Icon getIcon(File f) {
Icon icon = null;
if (f != null) {
if (f instanceof NioFile && f.toPath() instanceof VFSPath) {
icon = getFileSystemView().getSystemIcon(f);
} else {
icon = super.getIcon(f);
if (f.isDirectory() && isCompoundDocument(f)) {
return new CompoundDocumentIcon(icon);
}
}
}
return icon;
}
@Override
public boolean isTraversable(File f) {
return f.isDirectory() && !isCompoundDocument(f);
}
/**
* Overridden in order to recognize dialog size changes.
*
* @param parent the parent
* @return the dialog
* @throws HeadlessException if GraphicsEnvironment.isHeadless() returns true.
*/
@Override
protected JDialog createDialog(Component parent) throws HeadlessException {
final JDialog dialog = super.createDialog(parent);
Rectangle dialogBounds = loadDialogBounds();
if (dialogBounds != null) {
dialog.setBounds(dialogBounds);
}
dialog.addComponentListener(resizeHandler);
return dialog;
}
/**
* Called by the UI when the user hits the Approve button (labeled "Open" or "Save", by default). This can also be
* called by the programmer.
*/
@Override
public void approveSelection() {
Debug.trace("SnapFileChooser: approveSelection(): selectedFile = " + getSelectedFile());
Debug.trace("SnapFileChooser: approveSelection(): currentFilename = " + getCurrentFilename());
Debug.trace("SnapFileChooser: approveSelection(): currentDirectory = " + getCurrentDirectory());
if (getDialogType() != JFileChooser.OPEN_DIALOG) {
ensureSelectedFileHasValidExtension();
}
super.approveSelection();
}
/**
* Sets the dialog bounds to be used for the next {@link #showDialog(java.awt.Component, String)} call.
*
* @param rectangle the dialog bounds
*/
public void setDialogBounds(Rectangle rectangle) {
storeDialogBounds(rectangle);
}
/**
* @return The current filename, or {@code null}.
*/
public String getCurrentFilename() {
File selectedFile = getSelectedFile();
if (selectedFile != null) {
return selectedFile.getName();
}
return null;
}
/**
* Sets the current filename.
*
* @param currentFilename The current filename, or {@code null}.
*/
public void setCurrentFilename(String currentFilename) {
Debug.trace("SnapFileChooser: setCurrentFilename(\"" + currentFilename + "\")");
String defaultExtension = getDefaultExtension();
if (getDialogType() != JFileChooser.OPEN_DIALOG) {
if (currentFilename != null && defaultExtension != null) {
FileFilter fileFilter = getFileFilter();
if (fileFilter instanceof SnapFileFilter) {
SnapFileFilter filter = (SnapFileFilter) fileFilter;
if (!filter.checkExtension(currentFilename)) {
currentFilename = FileUtils.exchangeExtension(currentFilename, defaultExtension);
}
} else if (fileFilter instanceof FileNameExtensionFilter) {
FileNameExtensionFilter filter = (FileNameExtensionFilter) fileFilter;
if (!SnapFileFilter.checkExtensions(currentFilename, filter.getExtensions())) {
currentFilename = FileUtils.exchangeExtension(currentFilename, defaultExtension);
}
}
}
}
if (currentFilename != null && currentFilename.length() > 0) {
setSelectedFile(new File(getCurrentDirectory(), currentFilename));
}
}
/**
* Returns the currently selected SNAP file filter.
*
* @return the current SNAP file filter, or {@code null}
*/
public SnapFileFilter getSnapFileFilter() {
FileFilter ff = getFileFilter();
if (ff instanceof SnapFileFilter) {
return (SnapFileFilter) ff;
}
return null;
}
/**
* @return The current extension or {@code null} if it is unknown.
*/
public String getDefaultExtension() {
if (getSnapFileFilter() != null) {
return getSnapFileFilter().getDefaultExtension();
}
return null;
}
@Override
public FileFilter[] getChoosableFileFilters() {
synchronized (syncFileFiltersObject) {
return super.getChoosableFileFilters();
}
}
@Override
public void addChoosableFileFilter(FileFilter filter) {
synchronized (syncFileFiltersObject) {
super.addChoosableFileFilter(filter);
}
}
@Override
public String getName(File f) {
String filename = null;
if (f != null) {
if (f instanceof NioFile && f.toPath() instanceof VFSPath) {
filename = getFileSystemView().getSystemDisplayName(f);
} else {
filename = super.getName(f);
}
}
return filename;
}
/**
* Utility method which returns this file chooser's parent window.
*
* @return the parent window or {@code null}
*/
protected Window getWindow() {
Container w = this;
while (!(w instanceof Window)) {
w = w.getParent();
}
return (Window) w;
}
///////////////////////////////////////////////////////////////////////////
// private stuff
///////////////////////////////////////////////////////////////////////////
private void init() {
setAcceptAllFileFilterUsed(false);
addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, evt -> {
Object newValue = evt.getNewValue();
if (newValue instanceof File) {
lastFilename = ((File) newValue).getName();
}
});
addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, evt -> {
final SnapFileFilter snapFileFilter = getSnapFileFilter();
if (snapFileFilter != null) {
setFileSelectionMode(snapFileFilter.getFileSelectionMode().getValue());
} else {
setFileSelectionMode(FILES_ONLY);
}
if (getSelectedFile() != null) {
return;
}
if (lastFilename == null || lastFilename.length() == 0) {
return;
}
setCurrentFilename(lastFilename);
});
}
private boolean isCompoundDocument(File file) {
final FileFilter[] filters = getChoosableFileFilters();
for (FileFilter fileFilter : filters) {
if (fileFilter instanceof SnapFileFilter) {
SnapFileFilter snapFileFilter = (SnapFileFilter) fileFilter;
if (snapFileFilter.isCompoundDocument(file)) {
return true;
}
}
}
return false;
}
private void ensureSelectedFileHasValidExtension() {
File selectedFile = getSelectedFile();
if (selectedFile != null) {
SnapFileFilter mff = getSnapFileFilter();
if (mff != null
&& mff.getDefaultExtension() != null
&& !mff.checkExtension(selectedFile)) {
selectedFile = FileUtils.exchangeExtension(selectedFile, mff.getDefaultExtension());
Debug.trace("mod. selected file: " + selectedFile.getPath());
setSelectedFile(selectedFile);
}
}
}
private void storeDialogBounds(Rectangle bounds) {
int dialogType = getDialogType();
switch (dialogType) {
case OPEN_DIALOG:
putRectangleToPreferences(PREFERENCES_BOUNDS_OPEN, bounds);
break;
case SAVE_DIALOG:
putRectangleToPreferences(PREFERENCES_BOUNDS_SAVE, bounds);
break;
case CUSTOM_DIALOG:
default:
putRectangleToPreferences(PREFERENCES_BOUNDS_CUSTOM, bounds);
}
}
private Rectangle loadDialogBounds() {
switch (getDialogType()) {
case OPEN_DIALOG:
return getRectangleFromPreferences(PREFERENCES_BOUNDS_OPEN);
case SAVE_DIALOG:
return getRectangleFromPreferences(PREFERENCES_BOUNDS_SAVE);
case CUSTOM_DIALOG:
default:
return getRectangleFromPreferences(PREFERENCES_BOUNDS_CUSTOM);
}
}
private void putRectangleToPreferences(String key, Rectangle bounds) {
snapPreferences.put(key, new RectangleConverter().format(bounds));
}
private Rectangle getRectangleFromPreferences(String key) {
String rectString = snapPreferences.get(key, null);
if (rectString != null) {
try {
Rectangle rectangle = new RectangleConverter().parse(rectString);
GraphicsDevice[] screenDevices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices();
for (GraphicsDevice screenDevice : screenDevices) {
if (screenDevice.getDefaultConfiguration().getBounds().contains(rectangle.getLocation())) {
return rectangle;
}
}
} catch (ConversionException e) {
SystemUtils.LOG.log(Level.WARNING, "Not able to parse preferences value: " + rectString, e);
}
}
return null;
}
private static class CompoundDocumentIcon implements Icon {
private static final Icon compoundDocumentIcon = new ImageIcon(Objects.requireNonNull(CompoundDocumentIcon.class.getResource("CompoundDocument12.png")));
private final Icon baseIcon;
public CompoundDocumentIcon(Icon baseIcon) {
this.baseIcon = baseIcon;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
baseIcon.paintIcon(c, g, x, y);
compoundDocumentIcon.paintIcon(c, g,
x + baseIcon.getIconWidth() - compoundDocumentIcon.getIconWidth(),
y + baseIcon.getIconHeight() - compoundDocumentIcon.getIconHeight());
}
@Override
public int getIconWidth() {
return baseIcon.getIconWidth();
}
@Override
public int getIconHeight() {
return baseIcon.getIconHeight();
}
}
private class ResizeHandler extends ComponentAdapter {
@Override
public void componentMoved(ComponentEvent e) {
setDialogBounds(e.getComponent().getBounds());
}
@Override
public void componentResized(ComponentEvent e) {
setDialogBounds(e.getComponent().getBounds());
}
}
}
| 15,567 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SliderBoxImageDisplay.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/SliderBoxImageDisplay.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;
import javax.swing.JComponent;
import javax.swing.JLabel;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.awt.image.BufferedImage;
/**
* A component representing an image display with a draggable slider box in it.
*/
public class SliderBoxImageDisplay extends JComponent {
private static final int HANDLE_SIZE = 6;
private BufferedImage image;
private final int imageWidth;
private final int imageHeight;
private final SliderBoxChangeListener sliderBoxChangeListener;
private final JComponent sliderBox;
private int sliderSectionX;
private int sliderSectionY;
private Rectangle sliderRectOld;
private Point clickPos;
private boolean imageWidthFixed;
private boolean imageHeightFixed;
public SliderBoxImageDisplay(int imageWidth, int imageHeight, SliderBoxChangeListener sliderBoxChangeListener) {
this.imageWidth = imageWidth;
this.imageHeight = imageHeight;
this.sliderBoxChangeListener = sliderBoxChangeListener;
sliderBox = new JLabel();
sliderBox.setBounds(0, 0, 1, 1);
sliderBox.setOpaque(false);
sliderBox.setBorder(UIDefaults.SLIDER_BOX_BORDER);
setLayout(null);
setPreferredSize(new Dimension(imageWidth, imageHeight));
add(sliderBox);
clearSliderSections();
addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
sliderRectOld = new Rectangle(sliderBox.getBounds());
clickPos = new Point(e.getPoint());
computeSliderSections(e);
}
@Override
public void mouseReleased(MouseEvent e) {
sliderRectOld = null;
clickPos = null;
clearSliderSections();
}
});
addMouseMotionListener(new MouseMotionAdapter() {
@Override
public void mouseDragged(MouseEvent e) {
if (sliderRectOld == null || clickPos == null) {
return;
}
modifySliderBox(e);
}
});
}
public void setImage(BufferedImage image) {
this.image = image;
setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
repaint();
}
@Override
protected void paintComponent(Graphics graphics) {
graphics.setColor(getBackground());
if (image != null) {
graphics.drawImage(image, 0, 0, null);
}
}
public boolean isImageWidthFixed() {
return imageWidthFixed;
}
public void setImageWidthFixed(boolean imageWidthFixed) {
if (this.imageWidthFixed == imageWidthFixed) {
return;
}
this.imageWidthFixed = imageWidthFixed;
if (this.imageWidthFixed) {
setSliderBoxBounds(0, sliderBox.getY(), imageWidth, sliderBox.getHeight(), true);
}
}
public boolean isImageHeightFixed() {
return imageHeightFixed;
}
public void setImageHeightFixed(boolean imageHeightFixed) {
if (this.imageHeightFixed == imageHeightFixed) {
return;
}
this.imageHeightFixed = imageHeightFixed;
if (this.imageHeightFixed) {
setSliderBoxBounds(sliderBox.getX(), 0, sliderBox.getWidth(), imageHeight, true);
}
}
public SliderBoxChangeListener getSliderBoxChangeListener() {
return sliderBoxChangeListener;
}
public Rectangle getSliderBoxBounds() {
return sliderBox.getBounds();
}
public void setSliderBoxBounds(Rectangle rectangle) {
setSliderBoxBounds(rectangle, false);
}
public void setSliderBoxBounds(Rectangle rectangle, boolean fireEvent) {
setSliderBoxBounds(rectangle.x, rectangle.y, rectangle.width, rectangle.height, fireEvent);
}
public void setSliderBoxBounds(int x, int y, int width, int height) {
setSliderBoxBounds(x, y, width, height, false);
}
public void setSliderBoxBounds(int x, int y, int width, int height, boolean fireEvent) {
if (isImageWidthFixed()) {
x = 0;
width = imageWidth;
}
if (isImageHeightFixed()) {
y = 0;
height = imageHeight;
}
if (sliderBox.getX() == x
&& sliderBox.getY() == y
&& sliderBox.getWidth() == width
&& sliderBox.getHeight() == height) {
return;
}
sliderBox.setBounds(x, y, width, height); // also repaints!
if (sliderBoxChangeListener != null && fireEvent) {
sliderBoxChangeListener.sliderBoxChanged(sliderBox.getBounds());
}
}
private void clearSliderSections() {
sliderSectionX = -1;
sliderSectionY = -1;
}
private void computeSliderSections(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int x1 = sliderBox.getX();
int y1 = sliderBox.getY();
int x2 = sliderBox.getX() + sliderBox.getWidth();
int y2 = sliderBox.getY() + sliderBox.getHeight();
int dx1 = Math.abs(x1 - x);
int dy1 = Math.abs(y1 - y);
int dx2 = Math.abs(x2 - x);
int dy2 = Math.abs(y2 - y);
sliderSectionX = -1;
if (dx1 <= HANDLE_SIZE) {
sliderSectionX = 0; // left slider handle selected
} else if (dx2 <= HANDLE_SIZE) {
sliderSectionX = 2; // right slider handle selected
} else if (x >= x1 && x < x2) {
sliderSectionX = 1; // center slioder handle selected
}
sliderSectionY = -1;
if (dy1 <= HANDLE_SIZE) {
sliderSectionY = 0; // upper slider handle selected
} else if (dy2 <= HANDLE_SIZE) {
sliderSectionY = 2; // lower slider handle selected
} else if (y > y1 && y < y2) {
sliderSectionY = 1; // center slider handle selected
}
}
private void modifySliderBox(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int dx = x - clickPos.x;
int dy = y - clickPos.y;
int sbx = 0;
int sby = 0;
int sbw = 0;
int sbh = 0;
boolean validMode = false;
if (sliderSectionX == 0 && sliderSectionY == 0) {
sbx = sliderRectOld.x + dx;
sby = sliderRectOld.y + dy;
sbw = sliderRectOld.width - dx;
sbh = sliderRectOld.height - dy;
validMode = true;
} else if (sliderSectionX == 1 && sliderSectionY == 0) {
sbx = sliderRectOld.x;
sby = sliderRectOld.y + dy;
sbw = sliderRectOld.width;
sbh = sliderRectOld.height - dy;
validMode = true;
} else if (sliderSectionX == 2 && sliderSectionY == 0) {
sbx = sliderRectOld.x;
sby = sliderRectOld.y + dy;
sbw = sliderRectOld.width + dx;
sbh = sliderRectOld.height - dy;
validMode = true;
} else if (sliderSectionX == 0 && sliderSectionY == 1) {
sbx = sliderRectOld.x + dx;
sby = sliderRectOld.y;
sbw = sliderRectOld.width - dx;
sbh = sliderRectOld.height;
validMode = true;
} else if (sliderSectionX == 1 && sliderSectionY == 1) {
sbx = sliderRectOld.x + dx;
sby = sliderRectOld.y + dy;
sbw = sliderRectOld.width;
sbh = sliderRectOld.height;
validMode = true;
} else if (sliderSectionX == 2 && sliderSectionY == 1) {
sbx = sliderRectOld.x;
sby = sliderRectOld.y;
sbw = sliderRectOld.width + dx;
sbh = sliderRectOld.height;
validMode = true;
} else if (sliderSectionX == 0 && sliderSectionY == 2) {
sbx = sliderRectOld.x + dx;
sby = sliderRectOld.y;
sbw = sliderRectOld.width - dx;
sbh = sliderRectOld.height + dy;
validMode = true;
} else if (sliderSectionX == 1 && sliderSectionY == 2) {
sbx = sliderRectOld.x;
sby = sliderRectOld.y;
sbw = sliderRectOld.width;
sbh = sliderRectOld.height + dy;
validMode = true;
} else if (sliderSectionX == 2 && sliderSectionY == 2) {
sbx = sliderRectOld.x;
sby = sliderRectOld.y;
sbw = sliderRectOld.width + dx;
sbh = sliderRectOld.height + dy;
validMode = true;
}
if (validMode && sbw > 2 && sbh > 2) {
setSliderBoxBounds(sbx, sby, sbw, sbh, true);
}
}
public static interface SliderBoxChangeListener {
void sliderBoxChanged(Rectangle sliderBoxBounds);
}
}
| 9,739 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RegionSelectableWorldMapPane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/RegionSelectableWorldMapPane.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;
import com.bc.ceres.binding.PropertySet;
import com.bc.ceres.binding.ValidationException;
import com.bc.ceres.core.Assert;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.grender.Rendering;
import com.bc.ceres.grender.Viewport;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.figure.Figure;
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.ShapeFigure;
import com.bc.ceres.swing.figure.ViewportInteractor;
import com.bc.ceres.swing.figure.support.DefaultFigureEditor;
import com.bc.ceres.swing.figure.support.DefaultFigureStyle;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Cursor;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* This class wraps a {@link WorldMapPane} and extends it by functionality to draw and resize a selection rectangle.
*
* @author Thomas Storm
* @author Tonio Fincke
*/
public class RegionSelectableWorldMapPane {
static final String NORTH_BOUND = "northBound";
static final String SOUTH_BOUND = "southBound";
static final String WEST_BOUND = "westBound";
static final String EAST_BOUND = "eastBound";
private static final int OFFSET = 6;
private final BindingContext bindingContext;
private final DefaultFigureEditor figureEditor;
private boolean mustInitFigureEditor = true;
private final WorldMapPane worldMapPane;
private final RegionSelectionInteractor regionSelectionInteractor;
private final RegionSelectableWorldMapPane.CursorChanger cursorChanger = new CursorChanger();
private Rectangle2D selectionRectangle;
private Rectangle2D movableRectangle;
private Rectangle2D.Double defaultRectangle;
private Shape defaultShape;
private final RegionSelectableWorldMapPane.RegionSelectionDecoratingPanSupport panSupport;
private AtomicBoolean updatingModelBounds = new AtomicBoolean(false);
/**
* Creates a RegionSelectableWorldMapPane.
*
* @param dataModel The data model to be used
* @param bindingContext The binding context which has to contain at least the following properties:
* {@link #NORTH_BOUND northBound} ,
* {@link #SOUTH_BOUND southBound}, {@link #WEST_BOUND westBound}, and
* {@link #EAST_BOUND eastBound}. If all these property values are null, default values
* will be used. The property values are considered valid when the latitude values are
* within the allowed latitude range [-90, 90], the longitude values are within the
* allowed longitude range [-180, 180], the northBound is bigger than the southBound,
* the eastBound is bigger than the westBound, and no value is null. In this case,
* the world map will be initialized with these values.
* @throws IllegalArgumentException If the bindingContext is null, it does not contain the expected properties or
* the properties do not contain valid values
*/
public RegionSelectableWorldMapPane(WorldMapPaneDataModel dataModel, BindingContext bindingContext) {
ensureValidBindingContext(bindingContext);
this.bindingContext = bindingContext;
worldMapPane = new FigureEditorAwareWorldMapPane(dataModel, new SelectionOverlay(dataModel));
panSupport = new RegionSelectionDecoratingPanSupport(worldMapPane.getLayerCanvas());
worldMapPane.setPanSupport(panSupport);
figureEditor = new DefaultFigureEditor(worldMapPane.getLayerCanvas());
regionSelectionInteractor = new RegionSelectionInteractor();
worldMapPane.getLayerCanvas().addMouseMotionListener(cursorChanger);
}
public JPanel createUI() {
return worldMapPane;
}
static void ensureValidBindingContext(BindingContext bindingContext) {
if (bindingContext == null) {
throw new IllegalArgumentException("bindingContext must be not null");
}
ensureExistingProperty(bindingContext, NORTH_BOUND);
ensureExistingProperty(bindingContext, SOUTH_BOUND);
ensureExistingProperty(bindingContext, WEST_BOUND);
ensureExistingProperty(bindingContext, EAST_BOUND);
PropertySet propertySet = bindingContext.getPropertySet();
final Double northBound = propertySet.getValue(NORTH_BOUND);
final Double eastBound = propertySet.getValue(EAST_BOUND);
final Double southBound = propertySet.getValue(SOUTH_BOUND);
final Double westBound = propertySet.getValue(WEST_BOUND);
if (northBound == null && eastBound == null && southBound == null && westBound == null) {
setDefaultValues(bindingContext);
} else if (!geoBoundsAreValid(northBound, eastBound, southBound, westBound)) {
throw new IllegalArgumentException(MessageFormat.format("Given geo-bounds ({0}, {1}, {2}, {3}) are invalid.",
northBound, eastBound, southBound, westBound));
}
}
private DefaultFigureEditor getFigureEditor() {
initFigureEditor(figureEditor, null);
return figureEditor;
}
private void initFigureEditor(DefaultFigureEditor editor, Product selectedProduct) {
if (mustInitFigureEditor) {
initGeometries(selectedProduct);
final ShapeFigure polygonFigure = editor.getFigureFactory().createPolygonFigure(defaultShape, createFigureStyle(
(DefaultFigureStyle) editor.getDefaultPolygonStyle()));
if (polygonFigure != null) {
editor.getFigureCollection().addFigure(polygonFigure);
}
regionSelectionInteractor.updateProperties(defaultShape.getBounds2D());
mustInitFigureEditor = false;
}
}
private static void ensureExistingProperty(BindingContext bindingContext, String propertyName) {
Assert.argument(bindingContext.getPropertySet().getProperty(propertyName) != null,
"bindingContext must contain a property named " + propertyName);
}
private static void setDefaultValues(BindingContext bindingContext) {
bindingContext.getPropertySet().setValue(NORTH_BOUND, 75.0);
bindingContext.getPropertySet().setValue(WEST_BOUND, -15.0);
bindingContext.getPropertySet().setValue(SOUTH_BOUND, 35.0);
bindingContext.getPropertySet().setValue(EAST_BOUND, 30.0);
}
static boolean geoBoundsAreValid(Double northBound, Double eastBound, Double southBound, Double westBound) {
return northBound != null
&& eastBound != null
&& southBound != null
&& westBound != null
&& northBound > southBound
&& eastBound > westBound
&& isInValidLatitudeRange(northBound)
&& isInValidLatitudeRange(southBound)
&& isInValidLongitudeRange(eastBound)
&& isInValidLongitudeRange(westBound);
}
static void correctBoundsIfNecessary(Rectangle2D newFigureShape) {
double minX = newFigureShape.getMinX();
double minY = newFigureShape.getMinY();
double maxX = newFigureShape.getMaxX();
double maxY = newFigureShape.getMaxY();
minX = Math.min(maxX, Math.min(180, Math.max(-180, minX)));
minY = Math.min(maxY, Math.min(90, Math.max(-90, minY)));
maxX = Math.max(minX, Math.min(180, Math.max(-180, maxX)));
maxY = Math.max(minY, Math.min(90, Math.max(-90, maxY)));
minX = Math.min(maxX, Math.min(180, Math.max(-180, minX)));
minY = Math.min(maxY, Math.min(90, Math.max(-90, minY)));
if (newFigureShape.getMinX() != minX || newFigureShape.getMinY() != minY
|| newFigureShape.getMaxX() != maxX || newFigureShape.getMaxY() != maxY) {
// there were numerical issues with the direct approach that returned rectangles with a maxX slightly larger
// than 180 deg. To ensure data is always in the valid range, we subtract a small amount from width and height.
// tb 2015-11-02
final double width = maxX - minX;
final double height = maxY - minY;
newFigureShape.setRect(minX, minY, width - 1e-12, height - 1e-12);
}
}
private static boolean isInValidLongitudeRange(Double longitude) {
return longitude <= 180 && longitude >= -180;
}
private static boolean isInValidLatitudeRange(Double latitude) {
return latitude <= 90 && latitude >= -90;
}
private DefaultFigureStyle createFigureStyle(DefaultFigureStyle figureStyle) {
figureStyle.setFillColor(new Color(255, 200, 200));
figureStyle.setFillOpacity(0.2);
figureStyle.setStrokeColor(new Color(200, 0, 0));
figureStyle.setStrokeWidth(2);
return figureStyle;
}
private void updateRectangles() {
AffineTransform modelToView = worldMapPane.getLayerCanvas().getViewport().getModelToViewTransform();
selectionRectangle = modelToView.createTransformedShape(getFirstFigure().getBounds()).getBounds2D();
movableRectangle.setRect(selectionRectangle);
cursorChanger.updateRectanglesForDragCursor();
}
private Figure getFirstFigure() {
return getFigureEditor().getFigureCollection().getFigure(0);
}
private class CursorChanger implements MouseMotionListener {
private final String DEFAULT = "default";
private final String MOVE = "move";
private final String NORTH = "north";
private final String SOUTH = "south";
private final String WEST = "west";
private final String EAST = "east";
private final String NORTH_WEST = "northWest";
private final String NORTH_EAST = "northEast";
private final String SOUTH_WEST = "southWest";
private final String SOUTH_EAST = "southEast";
private Map<String, Cursor> cursorMap;
private Map<String, Rectangle2D.Double> rectangleMap;
private CursorChanger() {
cursorMap = new HashMap<>();
cursorMap.put(DEFAULT, Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
cursorMap.put(MOVE, Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
cursorMap.put(NORTH, Cursor.getPredefinedCursor(Cursor.N_RESIZE_CURSOR));
cursorMap.put(SOUTH, Cursor.getPredefinedCursor(Cursor.S_RESIZE_CURSOR));
cursorMap.put(WEST, Cursor.getPredefinedCursor(Cursor.W_RESIZE_CURSOR));
cursorMap.put(EAST, Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
cursorMap.put(NORTH_WEST, Cursor.getPredefinedCursor(Cursor.NW_RESIZE_CURSOR));
cursorMap.put(NORTH_EAST, Cursor.getPredefinedCursor(Cursor.NE_RESIZE_CURSOR));
cursorMap.put(SOUTH_WEST, Cursor.getPredefinedCursor(Cursor.SW_RESIZE_CURSOR));
cursorMap.put(SOUTH_EAST, Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
rectangleMap = new HashMap<>();
rectangleMap.put(DEFAULT, new Rectangle2D.Double());
rectangleMap.put(MOVE, new Rectangle2D.Double());
rectangleMap.put(NORTH, new Rectangle2D.Double());
rectangleMap.put(SOUTH, new Rectangle2D.Double());
rectangleMap.put(WEST, new Rectangle2D.Double());
rectangleMap.put(EAST, new Rectangle2D.Double());
rectangleMap.put(NORTH_EAST, new Rectangle2D.Double());
rectangleMap.put(NORTH_WEST, new Rectangle2D.Double());
rectangleMap.put(SOUTH_EAST, new Rectangle2D.Double());
rectangleMap.put(SOUTH_WEST, new Rectangle2D.Double());
}
@Override
public void mouseDragged(MouseEvent e) {
updateRectanglesForDragCursor();
updateCursor(e);
}
@Override
public void mouseMoved(MouseEvent e) {
updateCursor(e);
}
private void updateCursor(MouseEvent e) {
final boolean cursorOutsideOfSelectionRectangle =
!rectangleMap.get(DEFAULT).contains(e.getPoint()) &&
worldMapPane.getCursor() != cursorMap.get(DEFAULT);
if (cursorOutsideOfSelectionRectangle) {
worldMapPane.setCursor(cursorMap.get(DEFAULT));
} else {
final String[] regionIdentifiers = {
MOVE,
NORTH,
SOUTH,
WEST,
EAST,
NORTH_WEST,
NORTH_EAST,
SOUTH_WEST,
SOUTH_EAST
};
for (String region : regionIdentifiers) {
boolean cursorIsSet = setCursorWhenContained(cursorMap.get(region), rectangleMap.get(region), e.getPoint());
if (cursorIsSet) {
break;
}
}
}
}
private boolean setCursorWhenContained(Cursor cursor, Rectangle2D.Double rectangle, Point point) {
if (rectangle.contains(point)) {
if (worldMapPane.getCursor() != cursor) {
worldMapPane.setCursor(cursor);
}
return true;
}
return false;
}
private void updateRectanglesForDragCursor() {
Rectangle2D.Double rectangleForDragCursor = new Rectangle2D.Double(movableRectangle.getX() + OFFSET,
movableRectangle.getY() + OFFSET,
movableRectangle.getWidth() - 2 * OFFSET,
movableRectangle.getHeight() - 2 * OFFSET);
rectangleMap.get(MOVE).setRect(rectangleForDragCursor);
final double x = rectangleForDragCursor.getX();
final double y = rectangleForDragCursor.getY();
final double width = rectangleForDragCursor.getWidth();
final double height = rectangleForDragCursor.getHeight();
setRectangle(DEFAULT, x - 2 * OFFSET, y - 2 * OFFSET, width + 4 * OFFSET, height + 4 * OFFSET);
setRectangle(NORTH, x, y - 2 * OFFSET, width, 2 * OFFSET);
setRectangle(SOUTH, x, y + height, width, 2 * OFFSET);
setRectangle(WEST, x - 2 * OFFSET, y, 2 * OFFSET, height);
setRectangle(EAST, x + width, y, 2 * OFFSET, height);
setRectangle(NORTH_WEST, x - 2 * OFFSET, y - 2 * OFFSET, 2 * OFFSET, 2 * OFFSET);
setRectangle(NORTH_EAST, x + width, y - 2 * OFFSET, 2 * OFFSET, 2 * OFFSET);
setRectangle(SOUTH_WEST, x - 2 * OFFSET, y + height, 2 * OFFSET, 2 * OFFSET);
setRectangle(SOUTH_EAST, x + width, y + height, 2 * OFFSET, 2 * OFFSET);
}
private void setRectangle(String rectangleIdentifier, double x, double y, double w, double h) {
rectangleMap.get(rectangleIdentifier).setRect(x, y, w, h);
}
}
private class FigureEditorAwareWorldMapPane extends WorldMapPane implements FigureEditorAware {
private LayerCanvas.Overlay greyOverlay;
private FigureEditorAwareWorldMapPane(WorldMapPaneDataModel dataModel, SelectionOverlay overlay) {
super(dataModel, overlay);
addZoomListener(RegionSelectableWorldMapPane.this::handleZoom);
greyOverlay = (canvas, rendering) -> {
final Graphics2D graphics = rendering.getGraphics();
graphics.setPaint(new Color(200, 200, 200, 180));
graphics.fillRect(0, 0, worldMapPane.getWidth(), worldMapPane.getHeight());
};
}
@Override
public FigureEditor getFigureEditor() {
initFigureEditor(RegionSelectableWorldMapPane.this.figureEditor, null);
return figureEditor;
}
@Override
protected Action[] getOverlayActions() {
final Action[] overlayActions = super.getOverlayActions();
final Action[] actions = new Action[overlayActions.length + 1];
System.arraycopy(overlayActions, 0, actions, 0, overlayActions.length);
actions[actions.length - 1] = new ResetAction();
return actions;
}
@Override
public void zoomToProduct(Product product) {
if (product != null) {
super.zoomToProduct(product);
}
Rectangle2D modelBounds = getFirstFigure().getBounds();
modelBounds.setFrame(modelBounds.getX() - 2, modelBounds.getY() - 2,
modelBounds.getWidth() + 4, modelBounds.getHeight() + 4);
getLayerCanvas().getViewport().zoom(modelBounds);
handleZoom();
}
@Override
public void setEnabled(boolean enabled) {
if (enabled == isEnabled()) {
return;
}
super.setEnabled(enabled);
if (enabled) {
worldMapPane.getLayerCanvas().addMouseMotionListener(cursorChanger);
worldMapPane.getLayerCanvas().removeOverlay(greyOverlay);
worldMapPane.setPanSupport(panSupport);
} else {
worldMapPane.getLayerCanvas().removeMouseMotionListener(cursorChanger);
worldMapPane.getLayerCanvas().addOverlay(greyOverlay);
worldMapPane.setPanSupport(new NullPanSupport());
}
}
private class NullPanSupport implements PanSupport {
@Override
public void panStarted(MouseEvent event) {
}
@Override
public void performPan(MouseEvent event) {
}
@Override
public void panStopped(MouseEvent event) {
}
}
}
private void handleZoom() {
final FigureCollection figureCollection = getFigureEditor().getFigureCollection();
if (figureCollection.getFigureCount() == 0) {
return;
}
final Rectangle2D modelBounds = figureCollection.getFigure(0).getBounds();
final AffineTransform modelToViewTransform = worldMapPane.getLayerCanvas().getViewport().getModelToViewTransform();
final Shape transformedShape = modelToViewTransform.createTransformedShape(modelBounds);
movableRectangle.setRect(transformedShape.getBounds2D());
selectionRectangle.setRect(movableRectangle);
cursorChanger.updateRectanglesForDragCursor();
}
private class SelectionOverlay extends BoundaryOverlay {
SelectionOverlay(WorldMapPaneDataModel dataModel) {
super(dataModel);
}
@Override
protected void handleSelectedProduct(Rendering rendering, Product selectedProduct) {
DefaultFigureEditor editor = getFigureEditor();
initFigureEditor(editor, selectedProduct);
editor.drawFigureCollection(rendering);
}
}
private void initGeometries(Product selectedProduct) {
final GeoPos upperLeftGeoPos;
final GeoPos lowerRightGeoPos;
if (selectedProduct != null) {
PixelPos upperLeftPixel = new PixelPos(0.5f, 0.5f);
PixelPos lowerRightPixel = new PixelPos(
selectedProduct.getSceneRasterWidth() - 0.5f, selectedProduct.getSceneRasterHeight() - 0.5f);
GeoCoding geoCoding = selectedProduct.getSceneGeoCoding();
upperLeftGeoPos = geoCoding.getGeoPos(upperLeftPixel, null);
lowerRightGeoPos = geoCoding.getGeoPos(lowerRightPixel, null);
} else {
PropertySet propertySet = bindingContext.getPropertySet();
final Double northBound = propertySet.getValue(NORTH_BOUND);
final Double eastBound = propertySet.getValue(EAST_BOUND);
final Double southBound = propertySet.getValue(SOUTH_BOUND);
final Double westBound = propertySet.getValue(WEST_BOUND);
upperLeftGeoPos = new GeoPos(northBound.floatValue(), westBound.floatValue());
lowerRightGeoPos = new GeoPos(southBound.floatValue(), eastBound.floatValue());
}
Viewport viewport = worldMapPane.getLayerCanvas().getViewport();
AffineTransform modelToViewTransform = viewport.getModelToViewTransform();
Point2D.Double lowerRight = modelToView(lowerRightGeoPos, modelToViewTransform);
Point2D.Double upperLeft = modelToView(upperLeftGeoPos, modelToViewTransform);
Rectangle2D.Double rectangularShape = new Rectangle2D.Double(upperLeft.x, upperLeft.y,
lowerRight.x - upperLeft.x,
lowerRight.y - upperLeft.y);
selectionRectangle = createRectangle(rectangularShape);
movableRectangle = createRectangle(rectangularShape);
defaultRectangle = createRectangle(rectangularShape);
cursorChanger.updateRectanglesForDragCursor();
defaultShape = viewport.getViewToModelTransform().createTransformedShape(rectangularShape);
}
private Rectangle2D.Double createRectangle(Rectangle2D.Double rectangularShape) {
return new Rectangle2D.Double(rectangularShape.getX(), rectangularShape.getY(),
rectangularShape.getWidth(), rectangularShape.getHeight());
}
private Point2D.Double modelToView(GeoPos geoPos, AffineTransform modelToView) {
Point2D.Double result = new Point2D.Double();
modelToView.transform(new Point2D.Double(geoPos.getLon(), geoPos.getLat()), result);
return result;
}
private class RegionSelectionInteractor extends ViewportInteractor {
private static final int NO_LONGITUDE_BORDER = -3;
private static final int NO_LATITUDE_BORDER = -2;
private static final int BORDER_UNKNOWN = -1;
private static final int NORTH_BORDER = 0;
private static final int EAST_BORDER = 1;
private static final int SOUTH_BORDER = 2;
private static final int WEST_BORDER = 3;
private Point point;
private int rectangleLongitude;
private int rectangleLatitude;
private RegionSelectionInteractor() {
PropertySet propertySet = bindingContext.getPropertySet();
propertySet.getProperty(NORTH_BOUND).addPropertyChangeListener(new BoundsChangeListener(NORTH_BOUND));
propertySet.getProperty(SOUTH_BOUND).addPropertyChangeListener(new BoundsChangeListener(SOUTH_BOUND));
propertySet.getProperty(WEST_BOUND).addPropertyChangeListener(new BoundsChangeListener(WEST_BOUND));
propertySet.getProperty(EAST_BOUND).addPropertyChangeListener(new BoundsChangeListener(EAST_BOUND));
}
@Override
public void mousePressed(MouseEvent event) {
point = event.getPoint();
determineDraggedRectangleBorders(event);
}
private void determineDraggedRectangleBorders(MouseEvent e) {
double x = e.getX();
double y = e.getY();
double x1 = selectionRectangle.getX();
double y1 = selectionRectangle.getY();
double x2 = x1 + selectionRectangle.getWidth();
double y2 = y1 + selectionRectangle.getHeight();
double dx1 = Math.abs(x1 - x);
double dy1 = Math.abs(y1 - y);
double dx2 = Math.abs(x2 - x);
double dy2 = Math.abs(y2 - y);
rectangleLongitude = BORDER_UNKNOWN;
if (dx1 <= OFFSET) {
rectangleLongitude = WEST_BORDER;
} else if (dx2 <= OFFSET) {
rectangleLongitude = EAST_BORDER;
} else if (x >= x1 && x < x2) {
rectangleLongitude = NO_LONGITUDE_BORDER;
}
rectangleLatitude = BORDER_UNKNOWN;
if (dy1 <= OFFSET) {
rectangleLatitude = NORTH_BORDER;
} else if (dy2 <= OFFSET) {
rectangleLatitude = SOUTH_BORDER;
} else if (y > y1 && y < y2) {
rectangleLatitude = NO_LATITUDE_BORDER;
}
}
@Override
public void mouseDragged(MouseEvent event) {
double dx = event.getX() - point.getX();
double dy = point.getY() - event.getY();
double xOfUpdatedRectangle = selectionRectangle.getX();
double yOfUpdatedRectangle = selectionRectangle.getY();
double widthOfUpdatedRectangle = selectionRectangle.getWidth();
double heightOfUpdatedRectangle = selectionRectangle.getHeight();
if (rectangleLongitude == NO_LONGITUDE_BORDER && rectangleLatitude == NO_LATITUDE_BORDER) {
xOfUpdatedRectangle = selectionRectangle.getX() + dx;
yOfUpdatedRectangle = selectionRectangle.getY() - dy;
}
if (rectangleLongitude == WEST_BORDER) {
xOfUpdatedRectangle += dx;
widthOfUpdatedRectangle -= dx;
} else if (rectangleLongitude == EAST_BORDER) {
widthOfUpdatedRectangle += dx;
}
if (rectangleLatitude == NORTH_BORDER) {
yOfUpdatedRectangle -= dy;
heightOfUpdatedRectangle += dy;
} else if (rectangleLatitude == SOUTH_BORDER) {
heightOfUpdatedRectangle -= dy;
}
if (widthOfUpdatedRectangle > 2 && heightOfUpdatedRectangle > 2 &&
!(selectionRectangle.getX() == xOfUpdatedRectangle
&& selectionRectangle.getY() == yOfUpdatedRectangle
&& selectionRectangle.getWidth() == widthOfUpdatedRectangle
&& selectionRectangle.getHeight() == heightOfUpdatedRectangle)) {
setMovableRectangleInImageCoordinates(xOfUpdatedRectangle, yOfUpdatedRectangle,
widthOfUpdatedRectangle, heightOfUpdatedRectangle);
Shape newFigureShape = getViewToModelTransform(event).createTransformedShape(movableRectangle);
final Rectangle2D modelRectangle = newFigureShape.getBounds2D();
adaptToModelRectangle(modelRectangle);
}
}
@Override
public void mouseReleased(MouseEvent event) {
selectionRectangle.setRect(movableRectangle);
}
private void reset() {
selectionRectangle.setRect(defaultRectangle);
movableRectangle.setRect(defaultRectangle);
cursorChanger.updateRectanglesForDragCursor();
updateProperties(defaultShape.getBounds2D());
updateFigure(defaultShape.getBounds2D());
worldMapPane.zoomAll();
}
private void updateProperties(Rectangle2D modelRectangle) {
if (!updatingModelBounds.getAndSet(true)) {
try {
PropertySet propertySet = bindingContext.getPropertySet();
propertySet.getProperty(NORTH_BOUND).setValue(modelRectangle.getMaxY());
propertySet.getProperty(SOUTH_BOUND).setValue(modelRectangle.getMinY());
propertySet.getProperty(WEST_BOUND).setValue(modelRectangle.getMinX());
propertySet.getProperty(EAST_BOUND).setValue(modelRectangle.getMaxX());
} catch (ValidationException e) {
// should never come here
throw new IllegalStateException(e);
} finally {
updatingModelBounds.set(false);
}
}
}
private void updateFigure(Rectangle2D modelRectangle) {
DefaultFigureEditor figureEditor = getFigureEditor();
DefaultFigureStyle defaultFigureStyle = createFigureStyle((DefaultFigureStyle) figureEditor.getDefaultPolygonStyle());
final ShapeFigure polygonFigure = figureEditor.getFigureFactory().createPolygonFigure(modelRectangle, defaultFigureStyle);
if (polygonFigure != null) {
figureEditor.getFigureCollection().removeAllFigures();
figureEditor.getFigureCollection().addFigure(polygonFigure);
}
}
private void setMovableRectangleInImageCoordinates(double x, double y, double width, double height) {
movableRectangle.setRect(x, y, width, height);
}
private void adaptToModelRectangle(Rectangle2D modelRectangle) {
correctBoundsIfNecessary(modelRectangle);
if (modelRectangle.getWidth() != 0 && modelRectangle.getHeight() != 0 &&
!modelRectangle.equals(getFirstFigure().getBounds())) {
updateFigure(modelRectangle);
updateProperties(modelRectangle);
}
}
private class BoundsChangeListener implements PropertyChangeListener {
private final String property;
private BoundsChangeListener(String property) {
this.property = property;
}
@Override
public void propertyChange(PropertyChangeEvent evt) {
if (updatingModelBounds.get()) {
return;
}
final PropertySet propertySet = bindingContext.getPropertySet();
final Object westValue = propertySet.getProperty(WEST_BOUND).getValue();
final Object southValue = propertySet.getProperty(SOUTH_BOUND).getValue();
final Object eastValue = propertySet.getProperty(EAST_BOUND).getValue();
final Object northValue = propertySet.getProperty(NORTH_BOUND).getValue();
if (westValue == null || southValue == null || eastValue == null || northValue == null) {
return;
}
final Rectangle2D modelRectangle = getFirstFigure().getBounds();
double x = (property.equals(WEST_BOUND) ?
Double.parseDouble(westValue.toString()) :
modelRectangle.getX());
double y = (property.equals(SOUTH_BOUND) ?
Double.parseDouble(southValue.toString()) :
modelRectangle.getY());
double width = (property.equals(EAST_BOUND) || property.equals(WEST_BOUND) ?
Math.abs(Double.parseDouble(eastValue.toString()) - x) :
modelRectangle.getWidth());
double height = (property.equals(NORTH_BOUND) || property.equals(SOUTH_BOUND) ?
Math.abs(Double.parseDouble(northValue.toString()) - y) :
modelRectangle.getHeight());
modelRectangle.setRect(x, y, width, height);
adaptToModelRectangle(modelRectangle);
updateRectangles();
}
}
}
private class RegionSelectionDecoratingPanSupport extends WorldMapPane.DefaultPanSupport {
private Point p0;
private RegionSelectionDecoratingPanSupport(LayerCanvas layerCanvas) {
super(layerCanvas);
}
@Override
public void panStarted(MouseEvent event) {
super.panStarted(event);
p0 = event.getPoint();
final Rectangle2D.Double intersectionRectangle = createIntersectionRectangle();
if (intersectionRectangle.contains(event.getPoint())) {
regionSelectionInteractor.mousePressed(event);
}
}
@Override
public void performPan(MouseEvent event) {
final Rectangle2D.Double intersectionRectangle = createIntersectionRectangle();
if (intersectionRectangle.contains(p0)) {
regionSelectionInteractor.mouseDragged(event);
} else {
super.performPan(event);
}
}
@Override
public void panStopped(MouseEvent event) {
super.panStopped(event);
updateRectangles();
}
private Rectangle2D.Double createIntersectionRectangle() {
return new Rectangle2D.Double(selectionRectangle.getX() - OFFSET,
selectionRectangle.getY() - OFFSET,
selectionRectangle.getWidth() + 2 * OFFSET,
selectionRectangle.getHeight() + 2 * OFFSET);
}
}
private class ResetAction extends AbstractAction {
private ResetAction() {
putValue(LARGE_ICON_KEY, UIUtils.loadImageIcon("icons/Undo24.gif"));
}
@Override
public void actionPerformed(ActionEvent e) {
if (isEnabled()) {
regionSelectionInteractor.reset();
}
}
}
}
| 34,831 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DemSelector.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/DemSelector.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;
import org.esa.snap.core.dataop.dem.ElevationModelDescriptor;
import org.esa.snap.core.dataop.dem.ElevationModelRegistry;
import org.esa.snap.core.param.ParamChangeEvent;
import org.esa.snap.core.param.ParamChangeListener;
import org.esa.snap.core.param.ParamParseException;
import org.esa.snap.core.param.ParamValidateException;
import org.esa.snap.core.param.Parameter;
import org.esa.snap.core.param.editors.RadioButtonEditor;
import javax.swing.AbstractButton;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JPanel;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
public class DemSelector extends JPanel {
private Parameter _paramProductDem;
private Parameter _paramExternalDem;
private Parameter _paramDem;
public DemSelector() {
this(null);
}
public DemSelector(ParamChangeListener paramChangeListener) {
createParameter(paramChangeListener);
createUI();
updateUIState();
}
public boolean isUsingProductDem() {
return (Boolean) _paramProductDem.getValue();
}
public void setUsingProductDem(final boolean usingProductDem) throws ParamValidateException {
_paramProductDem.setValue(usingProductDem);
}
public boolean isUsingExternalDem() {
return (Boolean) _paramExternalDem.getValue();
}
public void setUsingExternalDem(final boolean usingExternalDem) throws ParamValidateException {
_paramExternalDem.setValue(usingExternalDem);
}
public String getDemName() {
return _paramDem.getValueAsText();
}
public void setDemName(String demName) throws ParamValidateException, ParamParseException {
_paramDem.setValueAsText(demName);
}
private void createUI() {
this.setLayout(new GridBagLayout());
this.setBorder(BorderFactory.createTitledBorder("Digital Elevation Model (DEM)")); /*I18N*/
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
final ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add((AbstractButton) _paramProductDem.getEditor().getComponent());
buttonGroup.add((AbstractButton) _paramExternalDem.getEditor().getComponent());
GridBagUtils.setAttributes(gbc, "insets.top=3, fill=HORIZONTAL");
gbc.gridy++;
GridBagUtils.addToPanel(this, _paramProductDem.getEditor().getComponent(), gbc);
gbc.gridy++;
GridBagUtils.addToPanel(this, _paramExternalDem.getEditor().getComponent(), gbc, "weightx=1");
GridBagUtils.addToPanel(this, _paramDem.getEditor().getComponent(), gbc, "weightx=999");
}
private void updateUIState() {
_paramDem.setUIEnabled(isUsingExternalDem());
}
private void createParameter(final ParamChangeListener delegate) {
ParamChangeListener paramChangeListener = new ParamChangeListener() {
public void parameterValueChanged(final ParamChangeEvent event) {
updateUIState();
if (delegate != null) {
delegate.parameterValueChanged(event);
}
}
};
_paramProductDem = new Parameter("useProductDem", Boolean.FALSE);
_paramProductDem.getProperties().setLabel("Use internal elevation"); /*I18N*/
_paramProductDem.getProperties().setEditorClass(RadioButtonEditor.class);
_paramProductDem.addParamChangeListener(paramChangeListener);
_paramExternalDem = new Parameter("useExternalDem", Boolean.TRUE);
_paramExternalDem.getProperties().setLabel("Use external DEM"); /*I18N*/
_paramExternalDem.getProperties().setEditorClass(RadioButtonEditor.class);
_paramExternalDem.addParamChangeListener(paramChangeListener);
final ElevationModelDescriptor[] descriptors = ElevationModelRegistry.getInstance().getAllDescriptors();
final String[] demValueSet = new String[descriptors.length];
for (int i = 0; i < descriptors.length; i++) {
demValueSet[i] = descriptors[i].getName();
}
_paramDem = new Parameter("dem", "");
_paramDem.getProperties().setLabel("Elevation Model:"); /*I18N*/
_paramDem.getProperties().setValueSetBound(true);
if (demValueSet.length != 0) {
_paramDem.setValue(demValueSet[0], null);
_paramDem.getProperties().setValueSet(demValueSet);
}
_paramDem.addParamChangeListener(paramChangeListener);
}
}
| 5,275 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AbstractDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/AbstractDialog.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;
import org.esa.snap.ui.help.HelpDisplayer;
import org.openide.util.HelpCtx;
import org.openide.util.NbBundle;
import javax.swing.AbstractButton;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The {@code AbstractDialog} is the base class for {@link ModalDialog} and {@link ModelessDialog},
* two helper classes used to quickly construct modal and modeless dialogs. The dialogs created with this
* class have a unique border and font and a standard button row for the typical buttons like "OK", "Cancel" etc.
* <p>
* <p>Instances of a modal dialog are created with a parent component, a title, the actual dialog content component, and
* a bit-combination of the standard buttons to be used.
* <p>
* <p>A limited way of input validation is provided by the {@code verifyUserInput} method which can be overridden
* in order to return {@code false} if a user input is invalid. In this case the {@link #onOK()},
* {@link #onYes()} and {@link #onNo()} methods are NOT called.
*
* @author Norman Fomferra
*/
@NbBundle.Messages({
"CTL_AbstractDlg_NoHelpThemeAvailable=Sorry, no help theme available.",
"CTL_AbstractDlg_NoHelpIDShowingStandard=Sorry, help for id '%s' not available.\nShowing standard help."
})
public abstract class AbstractDialog {
public static final int ID_OK = 0x0001;
public static final int ID_YES = 0x0002;
public static final int ID_NO = 0x0004;
public static final int ID_APPLY = 0x0008;
public static final int ID_CLOSE = 0x0010;
public static final int ID_CANCEL = 0x0020;
public static final int ID_RESET = 0x0040;
public static final int ID_HELP = 0x0080;
public static final int ID_OTHER = 0xAAAAAAAA;
private final JDialog dialog;
private final Window parent;
private final int buttonMask;
private int buttonId;
private Component content;
private boolean shown;
private Map<Integer, AbstractButton> buttonMap;
private JPanel buttonRow;
// Java help support
private String helpId;
protected AbstractDialog(JDialog dialog, int buttonMask, Object[] otherButtons, String helpID) {
this.parent = (Window) dialog.getParent();
this.dialog = dialog;
this.buttonMask = buttonMask;
this.buttonMap = new HashMap<>(5);
setComponentName(dialog);
setButtonID(0);
initUI(otherButtons);
setHelpID(helpID);
}
/**
* Gets the underlying Swing dialog passed to the constructor.
*
* @return the underlying Swing dialog.
*/
public JDialog getJDialog() {
return dialog;
}
/**
* Gets the owner of the dialog.
*
* @return The owner of the dialog.
*/
public Window getParent() {
return parent;
}
/**
* @return The dialog's title.
*/
public String getTitle() {
return dialog.getTitle();
}
/**
* @param title The dialog's title.
*/
public void setTitle(String title) {
dialog.setTitle(title);
}
/**
* Gets the button mask passed to the constructor.
*
* @return The button mask.
*/
public int getButtonMask() {
return buttonMask;
}
/**
* Gets the identifier for the most recently pressed button.
*
* @return The identifier for the most recently pressed button.
*/
public int getButtonID() {
return buttonId;
}
/**
* Sets the identifier for the most recently pressed button.
*
* @param buttonID The identifier for the most recently pressed button.
*/
protected void setButtonID(final int buttonID) {
buttonId = buttonID;
}
/**
* Gets the help identifier for the dialog.
*
* @return The help identifier.
*/
public String getHelpID() {
return helpId;
}
/**
* Sets the help identifier for the dialog.
*
* @param helpID The help identifier.
*/
public void setHelpID(String helpID) {
helpId = helpID;
updateHelpID();
}
public JPanel getButtonPanel() {
return buttonRow;
}
/**
* Gets the dialog's content component.
*
* @return The dialog's content component.
*/
public Component getContent() {
return content;
}
/**
* Sets the dialog's content component.
*
* @param content The dialog's content component.
*/
public void setContent(Component content) {
if (this.content != null) {
dialog.getContentPane().remove(this.content);
}
this.content = content;
dialog.getContentPane().add(this.content, BorderLayout.CENTER);
dialog.validate();
updateHelpID();
}
/**
* Sets the dialog's content.
*
* @param content The dialog's content.
*/
public void setContent(Object content) {
Component component;
if (content instanceof Component) {
component = (Component) content;
} else {
component = new JLabel(content.toString());
}
setContent(component);
}
/**
* Gets the button for the given identifier.
*
* @param buttonID The button identifier.
* @return The button, or {@code null}.
*/
public AbstractButton getButton(int buttonID) {
return buttonMap.get(buttonID);
}
/**
* Shows the dialog. Overrides shall call {@code super.show()} at the end.
*
* @return the identifier of the last button pressed or zero if this is a modeless dialog.
*/
public int show() {
setButtonID(0);
if (!shown) {
dialog.pack();
center();
}
dialog.setVisible(true);
shown = true;
return getButtonID();
}
/**
* Hides the dialog. Overrides shall call {@code super.hide()} at the end. This method does nothing else than hiding the underlying Swing dialog.
*
* @see #getJDialog()
*/
public void hide() {
dialog.setVisible(false);
}
/**
* This method is called, when the user clicks the close button of the dialog's top window bar.
* It can also be called directly.
* Override to implement the dialog's default close behaviour.
*/
public abstract void close();
/**
* Centers the dialog within its parent window.
*/
public void center() {
UIUtils.centerComponent(dialog, parent);
}
/**
* Shows an error dialog on top of this dialog.
*
* @param errorMessage The message.
*/
public void showErrorDialog(String errorMessage) {
showErrorDialog(errorMessage, getJDialog().getTitle());
}
public void showErrorDialog(String message, String title) {
showMessageDialog(getJDialog(), message, title, JOptionPane.ERROR_MESSAGE);
}
public static void showErrorDialog(Component component, String message, String dialogTitle) {
showMessageDialog(component, message, dialogTitle, JOptionPane.ERROR_MESSAGE);
}
/**
* Shows an information dialog on top of this dialog.
*
* @param infoMessage The message.
*/
public void showInformationDialog(String infoMessage) {
showInformationDialog(infoMessage, getJDialog().getTitle());
}
public void showInformationDialog(String infoMessage, String title) {
showMessageDialog(getJDialog(), infoMessage, title, JOptionPane.INFORMATION_MESSAGE);
}
public static void showInformationDialog(Component component, String message, String dialogTitle) {
showMessageDialog(component, message, dialogTitle, JOptionPane.INFORMATION_MESSAGE);
}
/**
* Shows a warning dialog on top of this dialog.
*
* @param warningMessage The message.
*/
public void showWarningDialog(String warningMessage) {
showWarningDialog(warningMessage, getJDialog().getTitle());
}
public void showWarningDialog(String warningMessage, String title) {
showMessageDialog(getJDialog(), warningMessage, title, JOptionPane.WARNING_MESSAGE);
}
public static void showWarningDialog(Component component, String message, String dialogTitle) {
showMessageDialog(component, message, dialogTitle, JOptionPane.WARNING_MESSAGE);
}
/**
* Called if the "OK" button has been clicked.
* The default implementation calls {@link #hide()}.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onOK() {
hide();
}
/**
* Called if the "Yes" button has been clicked.
* The default implementation calls {@link #hide()}.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onYes() {
hide();
}
/**
* Called if the "No" button has been clicked.
* The default implementation calls {@link #hide()}.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onNo() {
hide();
}
/**
* Called if the "Cancel" button has been clicked.
* The default implementation calls {@link #hide()}.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onCancel() {
hide();
}
/**
* Called if the "Apply" button has been clicked.
* The default implementation does nothing.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onApply() {
}
/**
* Called if the "Close" button has been clicked.
* The default implementation calls {@link #hide()}.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onClose() {
hide();
}
/**
* Called if the reset button has been clicked.
* The default implementation does nothing.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onReset() {
}
/**
* Called if the help button has been clicked.
* Clients should override this method to implement a different behaviour.
*/
protected void onHelp() {
if (helpId == null) {
showWarningDialog(String.format(Bundle.CTL_AbstractDlg_NoHelpIDShowingStandard(), helpId));
}
HelpDisplayer.show(helpId);
}
/**
* Called if a non-standard button has been clicked.
* The default implementation calls {@link #hide()}.
* Clients should override this method to implement meaningful behaviour.
*/
protected void onOther() {
hide();
}
/**
* Called in order to perform input validation.
*
* @return {@code true} if and only if the validation was successful.
*/
protected boolean verifyUserInput() {
return true;
}
/**
* Called by the constructor in order to initialise the user interface.
* The default implementation does nothing.
*
* @param buttons The container into which new buttons shall be collected.
*/
protected void collectButtons(List<AbstractButton> buttons) {
}
private void initUI(Object[] otherItems) {
buttonRow = new JPanel();
buttonRow.setLayout(new BoxLayout(buttonRow, BoxLayout.X_AXIS));
int insetSize = UIDefaults.INSET_SIZE;
JPanel contentPane = new JPanel(new BorderLayout(0, insetSize + insetSize / 2));
contentPane.setBorder(UIDefaults.DIALOG_BORDER);
contentPane.add(buttonRow, BorderLayout.SOUTH);
dialog.setResizable(true);
dialog.setContentPane(contentPane);
ArrayList<AbstractButton> buttons = new ArrayList<>();
collectButtons(buttons);
if (otherItems != null) {
for (Object otherItem : otherItems) {
if (otherItem instanceof String) {
String text = (String) otherItem;
JButton otherButton = new JButton(text);
otherButton.setName(getQualifiedPropertyName(text));
otherButton.addActionListener(e -> {
setButtonID(ID_OTHER);
if (verifyUserInput()) {
onOther();
}
});
buttons.add(otherButton);
} else if (otherItem instanceof AbstractButton) {
AbstractButton otherButton = (AbstractButton) otherItem;
otherButton.addActionListener(e -> {
setButtonID(ID_OTHER);
if (verifyUserInput()) {
onOther();
}
});
buttons.add(otherButton);
}
}
}
if ((buttonMask & ID_OK) != 0) {
JButton button = new JButton("OK");
button.setMnemonic('O');
button.setName(getQualifiedPropertyName("ok"));
button.addActionListener(e -> {
setButtonID(ID_OK);
if (verifyUserInput()) {
onOK();
}
});
buttons.add(button);
button.setDefaultCapable(true);
getJDialog().getRootPane().setDefaultButton(button);
registerButton(ID_OK, button);
}
if ((buttonMask & ID_YES) != 0) {
JButton button = new JButton("Yes");
button.setMnemonic('Y');
button.setName(getQualifiedPropertyName("yes"));
button.addActionListener(e -> {
setButtonID(ID_YES);
if (verifyUserInput()) {
onYes();
}
});
buttons.add(button);
button.setDefaultCapable(true);
getJDialog().getRootPane().setDefaultButton(button);
registerButton(ID_YES, button);
}
if ((buttonMask & ID_NO) != 0) {
JButton button = new JButton("No");
button.setMnemonic('N');
button.setName(getQualifiedPropertyName("no"));
button.addActionListener(e -> {
setButtonID(ID_NO);
if (verifyUserInput()) {
onNo();
}
});
buttons.add(button);
registerButton(ID_NO, button);
}
if ((buttonMask & ID_CANCEL) != 0) {
JButton button = new JButton("Cancel");
button.setMnemonic('C');
button.setName(getQualifiedPropertyName("cancel"));
button.addActionListener(e -> close());
buttons.add(button);
button.setVerifyInputWhenFocusTarget(false);
registerButton(ID_CANCEL, button);
}
if ((buttonMask & ID_APPLY) != 0) {
JButton button = new JButton("Apply");
button.setMnemonic('A');
button.setName(getQualifiedPropertyName("apply"));
button.addActionListener(e -> {
setButtonID(ID_APPLY);
if (verifyUserInput()) {
onApply();
}
});
buttons.add(button);
button.setDefaultCapable(true);
getJDialog().getRootPane().setDefaultButton(button);
registerButton(ID_APPLY, button);
}
if ((buttonMask & ID_CLOSE) != 0) {
JButton button = new JButton("Close");
button.setMnemonic('C');
button.setName(getQualifiedPropertyName("close"));
button.addActionListener(e -> {
setButtonID(ID_CLOSE);
onClose();
});
button.setToolTipText("Close dialog window");
buttons.add(button);
button.setVerifyInputWhenFocusTarget(false);
registerButton(ID_CLOSE, button);
}
if ((buttonMask & ID_RESET) != 0) {
JButton button = new JButton("Reset");
button.setName(getQualifiedPropertyName("reset"));
button.setMnemonic('R');
button.addActionListener(e -> {
setButtonID(ID_RESET);
onReset();
});
buttons.add(button);
registerButton(ID_RESET, button);
}
if ((buttonMask & ID_HELP) != 0) {
JButton button = new JButton("Help");
button.setName(getQualifiedPropertyName("help"));
button.setMnemonic('H');
button.addActionListener(e -> {
setButtonID(ID_HELP);
onHelp();
});
button.setToolTipText("Show help on this topic.");
buttons.add(button);
registerButton(ID_HELP, button);
}
buttonRow.add(Box.createHorizontalGlue());
for (int i = 0; i < buttons.size(); i++) {
if (i != 0) {
buttonRow.add(Box.createRigidArea(new Dimension(4, 0)));
}
buttonRow.add(buttons.get(i));
}
dialog.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
close();
}
});
}
protected String getQualifiedPropertyName(String name) {
return getClass().getSimpleName() + "." + name;
}
protected void registerButton(int buttonID, AbstractButton button) {
buttonMap.put(buttonID, button);
}
private void updateHelpID() {
if (helpId == null) {
return;
}
if (getJDialog().getContentPane() != null) {
Container contentPane = getJDialog().getContentPane();
if (contentPane instanceof JComponent) {
HelpCtx.setHelpIDString((JComponent) contentPane, helpId);
}
}
}
private static void showMessageDialog(Component dialog, String message, String dialogTitle, int messageType) {
JOptionPane.showMessageDialog(dialog, message, dialogTitle, messageType);
}
private void setComponentName(JDialog dialog) {
if (this.dialog.getName() == null && dialog.getTitle() != null) {
dialog.setName(dialog.getTitle().toLowerCase().replaceAll(" ", "_"));
}
}
}
| 19,596 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PopupMenuFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/PopupMenuFactory.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;
import javax.swing.JPopupMenu;
import java.awt.Component;
import java.awt.event.MouseEvent;
/**
* A factory for pop-up menues.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public interface PopupMenuFactory {
/**
* Creates the popup menu for the given component. This method is called by the <code>PopupMenuHandler</code>
* registered on the given component.
*
* @param component the source component
*
* @see PopupMenuFactory
* @see PopupMenuHandler
*/
JPopupMenu createPopupMenu(Component component);
/**
* Creates the popup menu for the given mouse event. This method is called by the <code>PopupMenuHandler</code>
* registered on the event fired component.
*
* @param event the fired mouse event
*
* @see PopupMenuFactory
* @see PopupMenuHandler
*/
JPopupMenu createPopupMenu(MouseEvent event);
/**
* Creates the popup menu for the given key event.
* This method is called by the <code>PopupMenuHandler</code> registered
* on the event fired component.
*
* @param event the fired key event
* @see PopupMenuFactory
* @see PopupMenuHandler
*/
// JPopupMenu createPopupMenu(KeyEvent event);
}
| 2,009 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
SimpleDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/SimpleDialog.java | package org.esa.snap.ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class SimpleDialog extends JDialog {
public SimpleDialog(String title, String message, Component component) {
JButton okayButton = new JButton("Okay");
okayButton.setPreferredSize(okayButton.getPreferredSize());
okayButton.setMinimumSize(okayButton.getPreferredSize());
okayButton.setMaximumSize(okayButton.getPreferredSize());
okayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
dispose();
}
});
JLabel jLabel = new JLabel(message);
JPanel jPanel = new JPanel(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.NONE;
gbc.anchor = GridBagConstraints.CENTER;
gbc.insets = new Insets(10,10,10,10);
jPanel.add(jLabel, gbc);
gbc.insets.bottom = 10;
gbc.gridy = 1;
jPanel.add(okayButton, gbc);
add(jPanel);
setModalityType(ModalityType.APPLICATION_MODAL);
setTitle(title);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setLocationRelativeTo(component);
pack();
setPreferredSize(getPreferredSize());
setMinimumSize(getPreferredSize());
setMaximumSize(getPreferredSize());
setSize(getPreferredSize());
}
} | 1,563 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMapPane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/WorldMapPane.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;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.swing.LayerCanvas;
import com.bc.ceres.glayer.swing.WakefulComponent;
import com.bc.ceres.grender.Viewport;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.util.GeoUtils;
import org.esa.snap.tango.TangoIcons;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import org.openide.util.ImageUtilities;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JPanel;
import javax.swing.event.MouseInputAdapter;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.GeneralPath;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* This class displays a world map specified by the {@link WorldMapPaneDataModel}.
*
* @author Marco Peters
* @version $Revision$ $Date$
*/
public class WorldMapPane extends JPanel {
private LayerCanvas layerCanvas;
private Layer worldMapLayer;
private final WorldMapPaneDataModel dataModel;
private boolean navControlShown;
private WakefulComponent navControlWrapper;
private PanSupport panSupport;
private MouseHandler mouseHandler;
private Set<ZoomListener> zoomListeners;
public WorldMapPane(WorldMapPaneDataModel dataModel) {
this(dataModel, null);
}
public WorldMapPane(WorldMapPaneDataModel dataModel, LayerCanvas.Overlay overlay) {
this.dataModel = dataModel;
layerCanvas = new LayerCanvas();
this.panSupport = new DefaultPanSupport(layerCanvas);
this.zoomListeners = new HashSet<>();
getLayerCanvas().getModel().getViewport().setModelYAxisDown(false);
if (overlay == null) {
getLayerCanvas().addOverlay(new BoundaryOverlayImpl(dataModel));
} else {
getLayerCanvas().addOverlay(overlay);
}
final Layer rootLayer = getLayerCanvas().getLayer();
final Dimension dimension = new Dimension(400, 200);
final Viewport viewport = getLayerCanvas().getViewport();
viewport.setViewBounds(new Rectangle(dimension));
setPreferredSize(dimension);
setSize(dimension);
setLayout(new BorderLayout());
add(getLayerCanvas(), BorderLayout.CENTER);
dataModel.addModelChangeListener(new ModelChangeListener());
worldMapLayer = dataModel.getWorldMapLayer(new WorldMapLayerContext(rootLayer));
installLayerCanvasNavigation(getLayerCanvas());
getLayerCanvas().getLayer().getChildren().add(worldMapLayer);
zoomAll();
setNavControlVisible(true);
addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
AffineTransform transform = getLayerCanvas().getViewport().getModelToViewTransform();
Rectangle2D maxVisibleModelBounds = getLayerCanvas().getMaxVisibleModelBounds();
double minX = maxVisibleModelBounds.getMinX();
double minY = maxVisibleModelBounds.getMinY();
double maxX = maxVisibleModelBounds.getMaxX();
double maxY = maxVisibleModelBounds.getMaxY();
final Point2D upperLeft = transform.transform(new Point2D.Double(minX, minY), null);
final Point2D lowerRight = transform.transform(new Point2D.Double(maxX, maxY), null);
/*
* We need to give the borders a minimum width/height of 1 because otherwise the intersection
* operation would not work
*/
Rectangle2D northBorder = new Rectangle2D.Double(upperLeft.getX(), upperLeft.getY(),
lowerRight.getX() - upperLeft.getX(), 1);
Rectangle2D southBorder = new Rectangle2D.Double(upperLeft.getX(), lowerRight.getY(),
lowerRight.getX() - upperLeft.getX(), 1);
Rectangle2D westBorder = new Rectangle2D.Double(upperLeft.getX(), lowerRight.getY(), 1,
upperLeft.getY() - lowerRight.getY());
Rectangle2D eastBorder = new Rectangle2D.Double(lowerRight.getX(), lowerRight.getY(), 1,
upperLeft.getY() - lowerRight.getY());
Rectangle layerCanvasBounds = getLayerCanvas().getBounds();
boolean isWorldMapFullyVisible = layerCanvasBounds.intersects(northBorder) ||
layerCanvasBounds.intersects(southBorder) ||
layerCanvasBounds.intersects(westBorder) ||
layerCanvasBounds.intersects(eastBorder);
if (isWorldMapFullyVisible) {
zoomAll();
}
}
});
}
@Override
public void doLayout() {
if (navControlShown && navControlWrapper != null) {
navControlWrapper.setLocation(getWidth() - navControlWrapper.getWidth() - 4, 4);
}
super.doLayout();
}
public Product getSelectedProduct() {
return dataModel.getSelectedProduct();
}
public Product[] getProducts() {
return dataModel.getProducts();
}
public float getScale() {
return (float) getLayerCanvas().getViewport().getZoomFactor();
}
public void zoomToProduct(Product product) {
if (product == null || product.getSceneGeoCoding() == null) {
return;
}
final GeneralPath[] generalPaths = getGeoBoundaryPaths(product);
Rectangle2D modelArea = new Rectangle2D.Double();
final Viewport viewport = getLayerCanvas().getViewport();
for (GeneralPath generalPath : generalPaths) {
final Rectangle2D rectangle2D = generalPath.getBounds2D();
if (modelArea.isEmpty()) {
if (!viewport.isModelYAxisDown()) {
modelArea.setFrame(rectangle2D.getX(), rectangle2D.getMaxY(),
rectangle2D.getWidth(), rectangle2D.getHeight());
}
modelArea = rectangle2D;
} else {
modelArea.add(rectangle2D);
}
}
Rectangle2D modelBounds = modelArea.getBounds2D();
modelBounds.setFrame(modelBounds.getX() - 2, modelBounds.getY() - 2,
modelBounds.getWidth() + 4, modelBounds.getHeight() + 4);
modelBounds = cropToMaxModelBounds(modelBounds);
viewport.zoom(modelBounds);
fireScrolled();
}
public void zoomAll() {
getLayerCanvas().getViewport().zoom(worldMapLayer.getModelBounds());
fireScrolled();
}
/**
* None API. Don't use this method!
*
* @param navControlShown true, if this canvas uses a navigation control.
*/
public void setNavControlVisible(boolean navControlShown) {
boolean oldValue = this.navControlShown;
if (oldValue != navControlShown) {
if (navControlShown) {
final Action[] overlayActions = getOverlayActions();
final ButtonOverlayControl navControl = new ButtonOverlayControl(overlayActions.length, overlayActions);
navControlWrapper = new WakefulComponent(navControl);
navControlWrapper.setMinAlpha(0.3f);
getLayerCanvas().add(navControlWrapper);
} else {
getLayerCanvas().remove(navControlWrapper);
navControlWrapper = null;
}
validate();
this.navControlShown = navControlShown;
}
}
public void setPanSupport(PanSupport panSupport) {
layerCanvas.removeMouseListener(mouseHandler);
layerCanvas.removeMouseMotionListener(mouseHandler);
this.panSupport = panSupport;
mouseHandler = new MouseHandler();
layerCanvas.addMouseListener(mouseHandler);
layerCanvas.addMouseMotionListener(mouseHandler);
}
public LayerCanvas getLayerCanvas() {
return layerCanvas;
}
static GeneralPath[] getGeoBoundaryPaths(Product product) {
final int step = Math.max(16, (product.getSceneRasterWidth() + product.getSceneRasterHeight()) / 250);
return GeoUtils.createGeoBoundaryPaths(product, null, step);
}
public boolean addZoomListener(ZoomListener zoomListener) {
return zoomListeners.add(zoomListener);
}
public boolean removeZoomListener(ZoomListener zoomListener) {
return zoomListeners.remove(zoomListener);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
navControlWrapper.setEnabled(enabled);
}
protected Action[] getOverlayActions() {
return new Action[]{new ZoomAllAction(), new ZoomToSelectedAction(), new ZoomInAction(), new ZoomOutAction()};
}
protected void fireScrolled() {
for (ZoomListener zoomListener : zoomListeners) {
zoomListener.zoomed();
}
}
private void updateUiState(PropertyChangeEvent evt) {
if (WorldMapPaneDataModel.PROPERTY_LAYER.equals(evt.getPropertyName())) {
exchangeWorldMapLayer();
}
if (WorldMapPaneDataModel.PROPERTY_PRODUCTS.equals(evt.getPropertyName())) {
repaint();
}
if (WorldMapPaneDataModel.PROPERTY_SELECTED_PRODUCT.equals(evt.getPropertyName()) ||
WorldMapPaneDataModel.PROPERTY_AUTO_ZOOM_ENABLED.equals(evt.getPropertyName())) {
final Product selectedProduct = dataModel.getSelectedProduct();
if (selectedProduct != null && dataModel.isAutoZoomEnabled()) {
zoomToProduct(selectedProduct);
} else {
repaint();
}
}
if (WorldMapPaneDataModel.PROPERTY_ADDITIONAL_GEO_BOUNDARIES.equals(evt.getPropertyName())) {
repaint();
}
}
private void exchangeWorldMapLayer() {
final List<Layer> children = getLayerCanvas().getLayer().getChildren();
for (Layer child : children) {
child.dispose();
}
children.clear();
final Layer rootLayer = getLayerCanvas().getLayer();
worldMapLayer = dataModel.getWorldMapLayer(new WorldMapLayerContext(rootLayer));
children.add(worldMapLayer);
zoomAll();
}
protected Rectangle2D cropToMaxModelBounds(Rectangle2D modelBounds) {
final Rectangle2D maxModelBounds = worldMapLayer.getModelBounds();
if (modelBounds.getWidth() >= maxModelBounds.getWidth() - 1 ||
modelBounds.getHeight() >= maxModelBounds.getHeight() - 1) {
modelBounds = maxModelBounds;
}
return modelBounds;
}
private void installLayerCanvasNavigation(LayerCanvas layerCanvas) {
mouseHandler = new MouseHandler();
layerCanvas.addMouseListener(mouseHandler);
layerCanvas.addMouseMotionListener(mouseHandler);
layerCanvas.addMouseWheelListener(mouseHandler);
}
private static boolean viewportIsInWorldMapBounds(double dx, double dy, LayerCanvas layerCanvas) {
AffineTransform transform = layerCanvas.getViewport().getModelToViewTransform();
double minX = layerCanvas.getMaxVisibleModelBounds().getMinX();
double minY = layerCanvas.getMaxVisibleModelBounds().getMinY();
double maxX = layerCanvas.getMaxVisibleModelBounds().getMaxX();
double maxY = layerCanvas.getMaxVisibleModelBounds().getMaxY();
final Point2D upperLeft = transform.transform(new Point2D.Double(minX, minY), null);
final Point2D lowerRight = transform.transform(new Point2D.Double(maxX, maxY), null);
/*
* We need to give the borders a minimum width/height of 1 because otherwise the intersection
* operation would not work
*/
Rectangle2D northBorder = new Rectangle2D.Double(upperLeft.getX() + dx, upperLeft.getY() + dy,
lowerRight.getX() + dx - upperLeft.getX() + dx, 1);
Rectangle2D southBorder = new Rectangle2D.Double(upperLeft.getX() + dx, lowerRight.getY() + dy,
lowerRight.getX() + dx - upperLeft.getX() + dx, 1);
Rectangle2D westBorder = new Rectangle2D.Double(upperLeft.getX() + dx, lowerRight.getY() + dy, 1,
upperLeft.getY() + dy - lowerRight.getY() + dy);
Rectangle2D eastBorder = new Rectangle2D.Double(lowerRight.getX() + dx, lowerRight.getY() + dy, 1,
upperLeft.getY() + dy - lowerRight.getY() + dy);
return (!layerCanvas.getBounds().intersects(northBorder) &&
!layerCanvas.getBounds().intersects(southBorder) &&
!layerCanvas.getBounds().intersects(westBorder) &&
!layerCanvas.getBounds().intersects(eastBorder));
}
private class ModelChangeListener implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
updateUiState(evt);
}
}
private class MouseHandler extends MouseInputAdapter {
@Override
public void mousePressed(MouseEvent e) {
panSupport.panStarted(e);
}
@Override
public void mouseDragged(MouseEvent e) {
panSupport.performPan(e);
}
@Override
public void mouseReleased(MouseEvent e) {
panSupport.panStopped(e);
}
@Override
public void mouseWheelMoved(MouseWheelEvent e) {
if (!isEnabled()) {
return;
}
double oldFactor = layerCanvas.getViewport().getZoomFactor();
final int wheelRotation = e.getWheelRotation();
final double newZoomFactor = layerCanvas.getViewport().getZoomFactor() * Math.pow(1.1, wheelRotation);
final Rectangle viewBounds = layerCanvas.getViewport().getViewBounds();
final Rectangle2D modelBounds = worldMapLayer.getModelBounds();
final double minZoomFactor = Math.min(viewBounds.getWidth() / modelBounds.getWidth(),
viewBounds.getHeight() / modelBounds.getHeight());
layerCanvas.getViewport().setZoomFactor(Math.max(newZoomFactor, minZoomFactor));
if (layerCanvas.getViewport().getZoomFactor() > oldFactor
|| viewportIsInWorldMapBounds(0, 0, layerCanvas)) {
fireScrolled();
return;
}
layerCanvas.getViewport().setZoomFactor(oldFactor);
}
}
private static class WorldMapLayerContext implements LayerContext {
private final Layer rootLayer;
private WorldMapLayerContext(Layer rootLayer) {
this.rootLayer = rootLayer;
}
@Override
public Object getCoordinateReferenceSystem() {
return DefaultGeographicCRS.WGS84;
}
@Override
public Layer getRootLayer() {
return rootLayer;
}
}
private class ZoomInAction extends AbstractAction {
private ZoomInAction() {
putValue(LARGE_ICON_KEY, UIUtils.loadImageIcon("icons/ZoomIn24.gif"));
putValue(TOOL_TIP_TEXT_KEY,"Zoom in");
}
@Override
public void actionPerformed(ActionEvent e) {
if (isEnabled()) {
double zoomFactor = layerCanvas.getViewport().getZoomFactor();
layerCanvas.getViewport().setZoomFactor(zoomFactor*1.2);
fireScrolled();
}
}
}
private class ZoomOutAction extends AbstractAction {
private ZoomOutAction() {
putValue(LARGE_ICON_KEY, UIUtils.loadImageIcon("icons/ZoomOut24.gif"));
putValue(TOOL_TIP_TEXT_KEY,"Zoom out");
}
@Override
public void actionPerformed(ActionEvent e) {
if (isEnabled()) {
double zoomFactor = layerCanvas.getViewport().getZoomFactor();
layerCanvas.getViewport().setZoomFactor(zoomFactor*0.8);
fireScrolled();
}
}
}
private class ZoomAllAction extends AbstractAction {
private ZoomAllAction() {
putValue(LARGE_ICON_KEY, TangoIcons.actions_view_fullscreen(TangoIcons.Res.R22));
putValue(TOOL_TIP_TEXT_KEY,"Show entire world map");
}
@Override
public void actionPerformed(ActionEvent e) {
if (isEnabled()) {
zoomAll();
}
}
}
private class ZoomToSelectedAction extends AbstractAction {
private ZoomToSelectedAction() {
putValue(LARGE_ICON_KEY, ImageUtilities.loadImageIcon("org/esa/snap/rcp/icons/ZoomTo24.gif", false));
putValue(TOOL_TIP_TEXT_KEY,"Zoom to selected product");
}
@Override
public void actionPerformed(ActionEvent e) {
if (isEnabled()) {
final Product selectedProduct = getSelectedProduct();
zoomToProduct(selectedProduct);
}
}
}
public interface ZoomListener {
void zoomed();
}
public interface PanSupport {
void panStarted(MouseEvent event);
void performPan(MouseEvent event);
void panStopped(MouseEvent event);
}
protected static class DefaultPanSupport implements PanSupport {
private Point p0;
private final LayerCanvas layerCanvas;
protected DefaultPanSupport(LayerCanvas layerCanvas) {
this.layerCanvas = layerCanvas;
}
@Override
public void panStarted(MouseEvent event) {
p0 = event.getPoint();
}
@Override
public void performPan(MouseEvent event) {
final Point p = event.getPoint();
final double dx = p.x - p0.x;
final double dy = p.y - p0.y;
if (viewportIsInWorldMapBounds(dx, dy, layerCanvas)) {
layerCanvas.getViewport().moveViewDelta(dx, dy);
}
p0 = p;
}
@Override
public void panStopped(MouseEvent event) {
}
}
}
| 19,760 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
FileChooserFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/FileChooserFactory.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;
import javax.swing.JFileChooser;
import java.io.File;
import java.lang.reflect.Constructor;
/**
* A factory which is used to create instances of {@link javax.swing.JFileChooser}.
*/
public class FileChooserFactory {
private Class<? extends JFileChooser> fileChooserClass;
private Class<? extends JFileChooser> dirChooserClass;
public Class<? extends JFileChooser> getFileChooserClass() {
return fileChooserClass;
}
public void setFileChooserClass(Class<? extends JFileChooser> fileChooserClass) {
this.fileChooserClass = fileChooserClass;
}
public Class<? extends JFileChooser> getDirChooserClass() {
return dirChooserClass;
}
public void setDirChooserClass(Class<? extends JFileChooser> dirChooserClass) {
this.dirChooserClass = dirChooserClass;
}
public static FileChooserFactory getInstance() {
return Holder.instance;
}
public JFileChooser createFileChooser(File currentDirectory) {
JFileChooser fileChooser = createChooser(fileChooserClass, currentDirectory);
fileChooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
return fileChooser;
}
public JFileChooser createDirChooser(File currentDirectory) {
JFileChooser dirChooser = createChooser(dirChooserClass, currentDirectory);
dirChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
return dirChooser;
}
private JFileChooser createChooser(Class<?> chooserClass, File currentDirectory) {
JFileChooser fileChooser;
try {
Constructor<?> constructor = chooserClass.getConstructor(File.class);
fileChooser = (JFileChooser) constructor.newInstance(currentDirectory);
} catch (Throwable e) {
fileChooser = new JFileChooser(currentDirectory);
}
return fileChooser;
}
private FileChooserFactory() {
fileChooserClass = SnapFileChooser.class;
dirChooserClass = SnapFileChooser.class;
}
// Initialization on demand holder idiom
private static class Holder {
private static final FileChooserFactory instance = new FileChooserFactory();
}
}
| 2,948 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DecimalFormatter.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/DecimalFormatter.java | package org.esa.snap.ui;
import javax.swing.JFormattedTextField;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.util.Locale;
/**
* A formatter to be used for decimal number in a {@link JFormattedTextField}
*
* @see JFormattedTextField.AbstractFormatter
* @author Marco Peters
*/
public class DecimalFormatter extends JFormattedTextField.AbstractFormatter {
private final DecimalFormat format;
public DecimalFormatter(String pattern) {
final DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.ENGLISH);
format = new DecimalFormat(pattern, decimalFormatSymbols);
format.setParseIntegerOnly(false);
format.setParseBigDecimal(false);
format.setDecimalSeparatorAlwaysShown(true);
}
@Override
public Object stringToValue(String text) throws ParseException {
return format.parse(text).doubleValue();
}
@Override
public String valueToString(Object value) throws ParseException {
if (value == null) {
return "";
}
return format.format(value);
}
}
| 1,163 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
NewBandDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/NewBandDialog.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;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductData;
import org.esa.snap.core.datamodel.ProductNodeNameValidator;
import org.esa.snap.core.param.ParamProperties;
import org.esa.snap.core.param.Parameter;
import org.esa.snap.core.util.Guardian;
import org.esa.snap.core.util.StringUtils;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.text.JTextComponent;
import java.awt.GridBagConstraints;
import java.awt.Window;
//@todo 1 se/** - add (more) class documentation
public class NewBandDialog extends ModalDialog {
private Parameter _paramName;
private Parameter _paramDesc;
private Parameter _paramUnit;
private Parameter _paramDataType;
private Product _currentProduct;
private static int _numNewBands = 0;
public NewBandDialog(final Window parent, Product product) {
super(parent, "New Band", ModalDialog.ID_OK_CANCEL, null); /* I18N */
Guardian.assertNotNull("product", product);
_currentProduct = product;
createParameter();
createUI();
}
public String getNewBandsName() {
return _paramName.getValueAsText();
}
public String getNewBandsDesc() {
return _paramDesc.getValueAsText();
}
public String getNewBandsUnit() {
return _paramUnit.getValueAsText();
}
public int getNewBandsDataType() {
return ProductData.getType(_paramDataType.getValueAsText());
}
@Override
protected boolean verifyUserInput() {
String name = _paramName.getValueAsText();
if (name == null || name.length() == 0) {
showWarningDialog("The field '" + _paramName.getProperties().getLabel() + "' must not be empty"); /*I18N*/
return false;
}
if (StringUtils.contains(_currentProduct.getBandNames(), name)) {
showErrorDialog("A band with the name '" + name + "' already exists.\n"
+ "Please choose a another one."); /*I18N*/
return false;
}
return super.verifyUserInput();
}
private void createParameter() {
_numNewBands++;
ParamProperties paramProps;
paramProps = new ParamProperties(String.class, "new_band_" + _numNewBands);
paramProps.setLabel("Name"); /* I18N */
paramProps.setDescription("The name for the new band."); /*I18N*/
paramProps.setNullValueAllowed(false);
paramProps.setValidatorClass(ProductNodeNameValidator.class);
_paramName = new Parameter("bandName", paramProps);
paramProps = new ParamProperties(String.class, "");
paramProps.setLabel("Description"); /* I18N */
paramProps.setDescription("The description for the new band."); /*I18N*/
paramProps.setNullValueAllowed(true);
_paramDesc = new Parameter("bandDesc", paramProps);
paramProps = new ParamProperties(String.class, "");
paramProps.setLabel("Unit"); /* I18N */
paramProps.setDescription("The physical unit for the new band."); /*I18N*/
paramProps.setNullValueAllowed(true);
_paramUnit = new Parameter("bandUnit", paramProps);
paramProps = new ParamProperties(String.class, ProductData.TYPESTRING_FLOAT32,
new String[]{ProductData.TYPESTRING_FLOAT32});
paramProps.setLabel("Data type"); /* I18N */
paramProps.setDescription("The data type for the new band."); /*I18N*/
paramProps.setValueSetBound(true);
_paramDataType = new Parameter("bandDataType", paramProps);
}
private void createUI() {
final JPanel dialogPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
int line = 0;
GridBagUtils.addToPanel(dialogPane, _paramName.getEditor().getLabelComponent(), gbc,
"fill=BOTH, weightx=1, insets.top=3");
GridBagUtils.addToPanel(dialogPane, _paramName.getEditor().getComponent(), gbc);
GridBagUtils.addToPanel(dialogPane, _paramDesc.getEditor().getLabelComponent(), gbc, "gridy=" + ++line);
GridBagUtils.addToPanel(dialogPane, _paramDesc.getEditor().getComponent(), gbc);
GridBagUtils.addToPanel(dialogPane, _paramUnit.getEditor().getLabelComponent(), gbc, "gridy=" + ++line);
GridBagUtils.addToPanel(dialogPane, _paramUnit.getEditor().getComponent(), gbc);
GridBagUtils.addToPanel(dialogPane, _paramDataType.getEditor().getLabelComponent(), gbc, "gridy=" + ++line);
GridBagUtils.addToPanel(dialogPane, _paramDataType.getEditor().getComponent(), gbc);
_paramDataType.setUIEnabled(false);
GridBagUtils.addToPanel(dialogPane, createInfoPanel(), gbc, "gridy=" + ++line + ", insets.top=10, gridwidth=2");
setContent(dialogPane);
final JComponent editorComponent = _paramName.getEditor().getEditorComponent();
if (editorComponent instanceof JTextComponent) {
final JTextComponent tc = (JTextComponent) editorComponent;
tc.selectAll();
tc.requestFocus();
}
}
private JPanel createInfoPanel() {
final JLabel parentProductLabel = new JLabel(_currentProduct.getDisplayName());
final JLabel widthValueLabel = new JLabel("" + _currentProduct.getSceneRasterWidth() + " pixel");
final JLabel heightValueLabel = new JLabel("" + _currentProduct.getSceneRasterHeight() + " pixel");
final JLabel centerValueLatLabel = new JLabel("##°");
final JLabel centerValueLonLabel = new JLabel("##°");
final GeoCoding geoCoding = _currentProduct.getSceneGeoCoding();
if (geoCoding != null) {
final float centerX = 0.5f * _currentProduct.getSceneRasterWidth();
final float centerY = 0.5f * _currentProduct.getSceneRasterHeight();
final GeoPos pos = geoCoding.getGeoPos(new PixelPos(centerX + 0.5f, centerY + 0.5f), null);
centerValueLatLabel.setText(pos.getLatString());
centerValueLonLabel.setText(pos.getLonString());
}
final JPanel infoPanel = GridBagUtils.createDefaultEmptyBorderPanel();
infoPanel.setBorder(UIUtils.createGroupBorder("Band Info"));
int line = 0;
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
GridBagUtils.addToPanel(infoPanel, new JLabel("Parent Product:"), gbc, "weightx=0, gridy=" + ++line);
GridBagUtils.addToPanel(infoPanel, parentProductLabel, gbc, "weightx=1");
GridBagUtils.addToPanel(infoPanel, new JLabel("Raster Width:"), gbc, "weightx=0, gridy=" + ++line);
GridBagUtils.addToPanel(infoPanel, widthValueLabel, gbc, "weightx=1");
GridBagUtils.addToPanel(infoPanel, new JLabel("Raster Height:"), gbc, "weightx=0, gridy=" + ++line);
GridBagUtils.addToPanel(infoPanel, heightValueLabel, gbc, "weightx=1");
GridBagUtils.addToPanel(infoPanel, new JLabel("Center Latitude:"), gbc, "weightx=0, gridy=" + ++line);
GridBagUtils.addToPanel(infoPanel, centerValueLatLabel, gbc, "weightx=1");
GridBagUtils.addToPanel(infoPanel, new JLabel("Center Longitude:"), gbc, "weightx=0, gridy=" + ++line);
GridBagUtils.addToPanel(infoPanel, centerValueLonLabel, gbc, "weightx=1");
return infoPanel;
}
}
| 8,294 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
PixelPositionListener.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/PixelPositionListener.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;
import com.bc.ceres.glayer.support.ImageLayer;
import java.awt.event.MouseEvent;
/**
* A listener interrested in pixel position changes within a source image. You can add
* <code>PixelPositionListener</code>s to instances of the <code>ImageDisplay</code> UI component.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public interface PixelPositionListener {
/**
* Informs a client that the pixel position within the image has changed.
*
* @param baseImageLayer the image layer
* @param pixelX the x position within the image in pixel co-ordinates on the given level
* @param pixelY the y position within the image in pixel co-ordinates on the given level
* @param currentLevel the current level at which the image is displayed
* @param pixelPosValid if <code>true</code>, pixel position is valid
*/
void pixelPosChanged(ImageLayer baseImageLayer, int pixelX, int pixelY, int currentLevel, boolean pixelPosValid, MouseEvent e);
/**
* Informs a client that the pixel positions are no longer available.
*/
void pixelPosNotAvailable();
}
| 1,887 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMapPaneDataModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/WorldMapPaneDataModel.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;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.glayer.Layer;
import com.bc.ceres.glayer.LayerContext;
import com.bc.ceres.glayer.LayerType;
import com.bc.ceres.glayer.LayerTypeRegistry;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.Product;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Arrays;
public class WorldMapPaneDataModel {
public static final String PROPERTY_LAYER = "layer";
public static final String PROPERTY_SELECTED_PRODUCT = "selectedProduct";
public static final String PROPERTY_PRODUCTS = "products";
public static final String PROPERTY_ADDITIONAL_GEO_BOUNDARIES = "additionalGeoBoundaries";
public static final String PROPERTY_AUTO_ZOOM_ENABLED = "autoZoomEnabled";
private PropertyChangeSupport changeSupport;
private static final LayerType layerType = LayerTypeRegistry.getLayerType("org.esa.snap.worldmap.BlueMarbleLayerType");
private Layer worldMapLayer;
private Product selectedProduct;
private boolean autoZoomEnabled;
private ArrayList<Product> productList;
private ArrayList<GeoPos[]> additionalGeoBoundaryList;
public WorldMapPaneDataModel() {
productList = new ArrayList<Product>();
additionalGeoBoundaryList = new ArrayList<GeoPos[]>();
autoZoomEnabled = false;
}
public Layer getWorldMapLayer(LayerContext context) {
if (worldMapLayer == null) {
worldMapLayer = layerType.createLayer(context, new PropertyContainer());
}
return worldMapLayer;
}
public Product getSelectedProduct() {
return selectedProduct;
}
public void setSelectedProduct(Product product) {
Product oldSelectedProduct = selectedProduct;
if (oldSelectedProduct != product) {
selectedProduct = product;
firePropertyChange(PROPERTY_SELECTED_PRODUCT, oldSelectedProduct, selectedProduct);
}
}
public Product[] getProducts() {
return productList.toArray(new Product[productList.size()]);
}
public void setProducts(Product[] products) {
final Product[] oldProducts = getProducts();
productList.clear();
if (products != null) {
productList.addAll(Arrays.asList(products));
}
firePropertyChange(PROPERTY_PRODUCTS, oldProducts, getProducts());
}
public GeoPos[][] getAdditionalGeoBoundaries() {
return additionalGeoBoundaryList.toArray(new GeoPos[additionalGeoBoundaryList.size()][]);
}
public void setAdditionalGeoBoundaries(GeoPos[][] geoBoundarys) {
final GeoPos[][] oldGeoBoundarys = getAdditionalGeoBoundaries();
additionalGeoBoundaryList.clear();
if (geoBoundarys != null) {
additionalGeoBoundaryList.addAll(Arrays.asList(geoBoundarys));
}
firePropertyChange(PROPERTY_ADDITIONAL_GEO_BOUNDARIES, oldGeoBoundarys, additionalGeoBoundaryList);
}
public void addModelChangeListener(PropertyChangeListener listener) {
if (changeSupport == null) {
changeSupport = new PropertyChangeSupport(this);
}
changeSupport.addPropertyChangeListener(listener);
}
public void removeModelChangeListener(PropertyChangeListener listener) {
if (changeSupport != null) {
changeSupport.removePropertyChangeListener(listener);
}
}
public void addProduct(Product product) {
if (!productList.contains(product)) {
final Product[] oldProducts = getProducts();
if (productList.add(product)) {
firePropertyChange(PROPERTY_PRODUCTS, oldProducts, getProducts());
}
}
}
public void removeProduct(Product product) {
if (productList.contains(product)) {
final Product[] oldProducts = getProducts();
if (productList.remove(product)) {
firePropertyChange(PROPERTY_PRODUCTS, oldProducts, getProducts());
}
}
}
public boolean isAutoZoomEnabled() {
return autoZoomEnabled;
}
public void setAutoZoomEnabled(boolean autoZoomEnabled) {
final boolean oldAutoZommEnabled = isAutoZoomEnabled();
if (oldAutoZommEnabled != autoZoomEnabled) {
this.autoZoomEnabled = autoZoomEnabled;
firePropertyChange(PROPERTY_AUTO_ZOOM_ENABLED, oldAutoZommEnabled, autoZoomEnabled);
}
}
private void firePropertyChange(String propertyName, Object oldValue, Object newValue) {
if (changeSupport != null) {
changeSupport.firePropertyChange(propertyName, oldValue, newValue);
}
}
}
| 5,498 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
Disposable.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/Disposable.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;
public interface Disposable {
/**
* Releases all of the resources used by this view, its subcomponents, and all of its owned children.
*/
void dispose();
}
| 922 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BoundsInputPanel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/BoundsInputPanel.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;
import com.bc.ceres.swing.TableLayout;
import com.bc.ceres.swing.binding.BindingContext;
import com.bc.ceres.swing.binding.BindingProblem;
import com.bc.ceres.swing.binding.BindingProblemListener;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.cs.CoordinateSystem;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.Insets;
import java.util.HashMap;
import java.util.Map;
/**
* Component which provides a panel where lat/lon bounds may be entered and bound to a given
* {@link com.bc.ceres.swing.binding.BindingContext}.
*
* @author Marco Peters
* @author Thomas Storm
*/
public class BoundsInputPanel {
public static final String PROPERTY_WEST_BOUND = "westBound";
public static final String PROPERTY_NORTH_BOUND = "northBound";
public static final String PROPERTY_EAST_BOUND = "eastBound";
public static final String PROPERTY_SOUTH_BOUND = "southBound";
public static final String PROPERTY_PIXEL_SIZE_X = "pixelSizeX";
public static final String PROPERTY_PIXEL_SIZE_Y = "pixelSizeY";
static final DecimalFormatter DECIMAL_FORMATTER = new DecimalFormatter("0.0#######");
private final BindingContext bindingContext;
private final String enablePropertyKey;
private JLabel pixelXUnit;
private JLabel pixelYUnit;
private JFormattedTextField pixelSizeXField;
private JFormattedTextField pixelSizeYField;
private final Map<String, Double> unitMap;
private final String degreeSymbol = "°";
/**
* Default constructor.
*
* @param bindingContext The binding context, in which the properties given by the constants
* {@code PROPERTY_WEST_BOUND}, {@code PROPERTY_NORTH_BOUND},
* {@code PROPERTY_EAST_BOUND}, and {@code PROPERTY_SOUTH_BOUND} are bound
* accordingly.
* @param enablePropertyKey The key for the property which specifies whether the sub-components of this component
* are enabled.
*/
public BoundsInputPanel(BindingContext bindingContext, String enablePropertyKey) {
this.bindingContext = bindingContext;
this.enablePropertyKey = enablePropertyKey;
unitMap = new HashMap<>();
unitMap.put("°", 0.05);
unitMap.put("m", 1000.0);
unitMap.put("km", 1.0);
}
/**
* Creates the UI component. The enable state of the UI is controlled via the parameter {@code disableUIProperty}.
* If it matches the value of the property provided in the constructor, the UI will be disabled.
*
* @param disableUIProperty Controls the enable state of the UI.
* @return The UI component.
*/
public JPanel createBoundsInputPanel(boolean disableUIProperty) {
final TableLayout layout = new TableLayout(9);
layout.setTableAnchor(TableLayout.Anchor.WEST);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setTableWeightX(1.0);
layout.setTableWeightY(1.0);
layout.setTablePadding(3, 3);
layout.setColumnWeightX(0, 0.0);
layout.setColumnWeightX(1, 1.0);
layout.setColumnWeightX(2, 0.0);
layout.setColumnWeightX(3, 0.0);
layout.setColumnWeightX(4, 1.0);
layout.setColumnWeightX(5, 0.0);
layout.setColumnWeightX(6, 0.0);
layout.setColumnWeightX(7, 1.0);
layout.setColumnWeightX(8, 0.0);
layout.setColumnPadding(2, new Insets(3, 0, 3, 12));
layout.setColumnPadding(5, new Insets(3, 0, 3, 12));
final JPanel panel = new JPanel(layout);
pixelXUnit = new JLabel(degreeSymbol);
pixelYUnit = new JLabel(degreeSymbol);
panel.add(new JLabel("West:"));
final JFormattedTextField westLonField = new JFormattedTextField(DECIMAL_FORMATTER);
westLonField.setHorizontalAlignment(JTextField.RIGHT);
bindingContext.bind(PROPERTY_WEST_BOUND, westLonField);
bindingContext.bindEnabledState(PROPERTY_WEST_BOUND, false, enablePropertyKey, disableUIProperty);
panel.add(westLonField);
panel.add(new JLabel(degreeSymbol));
panel.add(new JLabel("East:"));
final JFormattedTextField eastLonField = new JFormattedTextField(DECIMAL_FORMATTER);
eastLonField.setHorizontalAlignment(JTextField.RIGHT);
bindingContext.bind(PROPERTY_EAST_BOUND, eastLonField);
bindingContext.bindEnabledState(PROPERTY_EAST_BOUND, false, enablePropertyKey, disableUIProperty);
panel.add(eastLonField);
panel.add(new JLabel(degreeSymbol));
panel.add(new JLabel("Pixel size X:"));
pixelSizeXField = new JFormattedTextField(DECIMAL_FORMATTER);
pixelSizeXField.setHorizontalAlignment(JTextField.RIGHT);
pixelSizeXField.setValue(unitMap.get(degreeSymbol));
bindingContext.bind(PROPERTY_PIXEL_SIZE_X, pixelSizeXField);
bindingContext.bindEnabledState(PROPERTY_PIXEL_SIZE_X, false, enablePropertyKey, disableUIProperty);
panel.add(pixelSizeXField);
panel.add(pixelXUnit);
panel.add(new JLabel("North:"));
final JFormattedTextField northLatField = new JFormattedTextField(DECIMAL_FORMATTER);
northLatField.setHorizontalAlignment(JTextField.RIGHT);
bindingContext.bind(PROPERTY_NORTH_BOUND, northLatField);
bindingContext.bindEnabledState(PROPERTY_NORTH_BOUND, false, enablePropertyKey, disableUIProperty);
panel.add(northLatField);
panel.add(new JLabel(degreeSymbol));
panel.add(new JLabel("South:"));
final JFormattedTextField southLatField = new JFormattedTextField(DECIMAL_FORMATTER);
southLatField.setHorizontalAlignment(JTextField.RIGHT);
bindingContext.bind(PROPERTY_SOUTH_BOUND, southLatField);
bindingContext.bindEnabledState(PROPERTY_SOUTH_BOUND, false, enablePropertyKey, disableUIProperty);
panel.add(southLatField);
panel.add(new JLabel(degreeSymbol));
panel.add(new JLabel("Pixel size Y:"));
pixelSizeYField = new JFormattedTextField(DECIMAL_FORMATTER);
pixelSizeYField.setHorizontalAlignment(JTextField.RIGHT);
pixelSizeYField.setValue(unitMap.get(degreeSymbol));
bindingContext.bind(PROPERTY_PIXEL_SIZE_Y, pixelSizeYField);
bindingContext.bindEnabledState(PROPERTY_PIXEL_SIZE_Y, false, enablePropertyKey, disableUIProperty);
panel.add(pixelSizeYField);
panel.add(pixelYUnit);
bindingContext.addProblemListener(new BindingProblemListener() {
@Override
public void problemReported(BindingProblem problem, BindingProblem ignored) {
final String propertyName = problem.getBinding().getPropertyName();
final boolean invalidBoundSet = propertyName.equals(PROPERTY_NORTH_BOUND) ||
propertyName.equals(PROPERTY_EAST_BOUND) ||
propertyName.equals(PROPERTY_SOUTH_BOUND) ||
propertyName.equals(PROPERTY_WEST_BOUND);
if (invalidBoundSet) {
resetTextField(problem);
}
}
private void resetTextField(BindingProblem problem) {
problem.getBinding().getComponentAdapter().adjustComponents();
}
@Override
public void problemCleared(BindingProblem ignored) {
// do nothing
}
});
return panel;
}
public void updatePixelUnit(CoordinateReferenceSystem crs) {
final CoordinateSystem coordinateSystem = crs.getCoordinateSystem();
final String unitX = coordinateSystem.getAxis(0).getUnit().toString();
if (!unitX.equals(pixelXUnit.getText())) {
pixelXUnit.setText(unitX);
pixelSizeXField.setValue(unitMap.get("deg".equals(unitX) ? degreeSymbol : unitX));
}
final String unitY = coordinateSystem.getAxis(1).getUnit().toString();
if (!unitY.equals(pixelYUnit.getText())) {
pixelYUnit.setText(unitY);
pixelSizeYField.setValue(unitMap.get("deg".equals(unitY) ? degreeSymbol : unitY));
}
}
}
| 9,039 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RenderedImageIcon.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/RenderedImageIcon.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;
import javax.swing.Icon;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.RenderedImage;
/**
* An adapter class which supplies a <code>RenderedImage</code> with the <code>Icon</code> interface.
*/
public class RenderedImageIcon implements Icon {
private RenderedImage _image;
/**
* Constructs a new <code>RenderedImageIcon</code> for the given <code>RenderedImage</code>.
*
* @param image the image to be wrapped
*/
public RenderedImageIcon(RenderedImage image) {
_image = image;
}
/**
* Returns the wrapped <code>RenderedImage</code>.
*/
public RenderedImage getImage() {
return _image;
}
/**
* Returns the icon's width.
*
* @return an int specifying the fixed width of the icon.
*/
public int getIconWidth() {
return _image.getWidth();
}
/**
* Returns the icon's height.
*
* @return an int specifying the fixed height of the icon.
*/
public int getIconHeight() {
return _image.getHeight();
}
/**
* Draw the icon at the specified location. Icon implementations may use the Component argument to get properties
* useful for painting, e.g. the foreground or background color.
*/
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2D = (Graphics2D) g;
g2D.drawRenderedImage(_image, AffineTransform.getTranslateInstance(x, y));
}
}
| 2,301 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
AppContext.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/AppContext.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;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductManager;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.ui.product.ProductSceneView;
import java.awt.Window;
public interface AppContext {
String getApplicationName();
Window getApplicationWindow();
Product getSelectedProduct();
void handleError(String message, Throwable t);
PropertyMap getPreferences();
ProductManager getProductManager();
ProductSceneView getSelectedProductSceneView();
}
| 1,279 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ImageInfoEditorModel.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/ImageInfoEditorModel.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;
import org.esa.snap.core.datamodel.ImageInfo;
import org.esa.snap.core.datamodel.Scaling;
import org.esa.snap.core.datamodel.Stx;
import javax.swing.event.ChangeListener;
import java.awt.Color;
/**
* Unstable interface. Do not use.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
* @since BEAM 4.5.1
*/
public interface ImageInfoEditorModel {
ImageInfo getImageInfo();
void setDisplayProperties(String name, String unit, Stx stx, Scaling scaling);
boolean isColorEditable();
int getSliderCount();
double getSliderSample(int index);
void setSliderSample(int index, double sample);
Color getSliderColor(int index);
void setSliderColor(int index, Color color);
void createSliderAfter(int index);
void removeSlider(int removeIndex);
Color[] createColorPalette();
boolean isGammaUsed();
double getGamma();
void setGamma(double gamma);
byte[] getGammaCurve();
String getParameterName();
String getParameterUnit();
Scaling getSampleScaling();
void setSampleScaling(Scaling scaling);
Stx getSampleStx();
double getMinSample();
double getMaxSample();
boolean isHistogramAvailable();
int[] getHistogramBins();
double getMinHistogramViewSample();
void setMinHistogramViewSample(double minViewSample);
double getMaxHistogramViewSample();
void setMaxHistogramViewSample(double maxViewSample);
double getHistogramViewGain();
void setHistogramViewGain(double gain);
void addChangeListener(ChangeListener l);
void removeChangeListener(ChangeListener l);
void fireStateChanged();
}
| 2,394 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
NewProductDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/NewProductDialog.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;
import org.esa.snap.core.dataio.ProductSubsetBuilder;
import org.esa.snap.core.dataio.ProductSubsetDef;
import org.esa.snap.core.datamodel.GeoCoding;
import org.esa.snap.core.datamodel.GeoPos;
import org.esa.snap.core.datamodel.PixelPos;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.ProductNodeList;
import org.esa.snap.core.datamodel.ProductNodeNameValidator;
import org.esa.snap.core.datamodel.TiePointGeoCoding;
import org.esa.snap.core.datamodel.TiePointGrid;
import org.esa.snap.core.param.ParamChangeEvent;
import org.esa.snap.core.param.ParamChangeListener;
import org.esa.snap.core.param.Parameter;
import org.esa.snap.core.util.Guardian;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.ui.product.ProductSubsetDialog;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.text.JTextComponent;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
//@todo 1 se/** - add (more) class documentation
public class NewProductDialog extends ModalDialog {
private static final String DEFAULT_NUMBER_TEXT = "####";
private static final String DEFAULT_LATLON_TEXT = "##°";
private static final String COPY_ALL_COMMAND = "all";
private static final String COPY_GEOCODING_COMMAND = "geo";
private static final String COPY_SUBSET_COMMAND = "sub";
private static int numNewProducts = 0;
private Parameter paramNewName;
private Parameter paramNewDesc;
private Parameter paramSourceProduct;
private final ProductNodeList sourceProducts;
private final Window parent;
private String prefix;
private Exception exception;
private boolean sourceProductOwner;
private ProductSubsetDef subsetDef;
private Product editProduct; // currently not used, but possibly later for product editing
private Product resultProduct;
private JButton subsetButton;
private JRadioButton copyAllRButton;
private JRadioButton geocodingRButton;
private JRadioButton subsetRButton;
private JLabel labelWidthInfo;
private JLabel labelHeightInfo;
private JLabel labelCenterLatInfo;
private JLabel labelCenterLonInfo;
private int selectedProductIndex;
public NewProductDialog(Window parent,
ProductNodeList<Product> sourceProducts,
final int selectedSourceIndex,
boolean sourceProductOwner) {
this(parent, sourceProducts, selectedSourceIndex, sourceProductOwner, "subset");
}
public NewProductDialog(Window parent,
ProductNodeList<Product> sourceProducts,
final int selectedSourceIndex, boolean sourceProductOwner,
String prefix) {
super(parent, "New Product", ModalDialog.ID_OK_CANCEL, null); /* I18N */
Guardian.assertNotNull("sourceProducts", sourceProducts);
Guardian.assertGreaterThan("sourceProducts.size()", sourceProducts.size(), 0);
this.sourceProducts = sourceProducts;
selectedProductIndex = selectedSourceIndex;
this.parent = parent;
this.prefix = prefix;
this.sourceProductOwner = sourceProductOwner;
}
@Override
public int show() {
createParameter();
createUI();
updateUI();
return super.show();
}
public void setSubsetDef(ProductSubsetDef subsetDef) {
this.subsetDef = subsetDef;
}
// public void setProductToEdit(Product product) {
// _editProduct = product;
// }
public boolean isSourceProductOwner() {
return sourceProductOwner;
}
public Product getSourceProduct() {
String displayName = paramSourceProduct.getValueAsText();
return (Product) sourceProducts.getByDisplayName(displayName);
}
public Product getResultProduct() {
return resultProduct;
}
@Override
protected void onCancel() {
super.onCancel();
resultProduct = null;
}
@Override
protected void onOK() {
super.onOK();
String prodName = paramNewName.getValueAsText();
String prodDesc = paramNewDesc.getValueAsText();
Product sourceProduct = getSourceProduct();
resultProduct = null;
try {
if (geocodingRButton.isSelected()) {
ProductSubsetDef def = new ProductSubsetDef();
def.addNodeName("latitude");
def.addNodeName("longitude");
def.addNodeName(Product.HISTORY_ROOT_NAME);
resultProduct = ProductSubsetBuilder.createProductSubset(sourceProduct, sourceProductOwner, def,
prodName, prodDesc);
// @todo 1 nf/** - check: do we really need the following code or is it done in the ProductSubsetBuilder?
TiePointGrid latGrid = resultProduct.getTiePointGrid("latitude");
TiePointGrid lonGrid = resultProduct.getTiePointGrid("longitude");
if (latGrid != null && lonGrid != null) {
resultProduct.setSceneGeoCoding(
new TiePointGeoCoding(latGrid, lonGrid, sourceProduct.getSceneGeoCoding().getGeoCRS()));
}
} else if (subsetDef != null && subsetRButton.isSelected()) {
resultProduct = ProductSubsetBuilder.createProductSubset(sourceProduct, sourceProductOwner,
subsetDef, prodName, prodDesc);
} else {
resultProduct = ProductSubsetBuilder.createProductSubset(sourceProduct, sourceProductOwner, null,
prodName, prodDesc);
}
} catch (Exception e) {
exception = e;
}
}
public Exception getException() {
return exception;
}
@Override
protected boolean verifyUserInput() {
boolean b = super.verifyUserInput();
String name = paramNewName.getValueAsText();
boolean bName = name != null && name.length() > 0;
boolean subset = true;
if (subsetRButton.isSelected() && subsetDef == null) {
subset = false;
showErrorDialog("Please define a valid spatial or spectral subset."); /*I18N*/
}
return b && bName && subset;
}
private void createParameter() {
numNewProducts++;
String prodName;
String prodDesc;
String[] valueSet;
boolean enableSourceProduct;
if (editProduct == null) {
valueSet = sourceProducts.getDisplayNames();
Product product = (Product) sourceProducts.getAt(selectedProductIndex);
prodName = createNewProductName(valueSet.length > 0 ? product.getName() : "");
prodDesc = "";
enableSourceProduct = true;
} else {
prodName = editProduct.getName();
prodDesc = editProduct.getDescription();
valueSet = new String[]{prodName};
enableSourceProduct = false;
}
paramNewName = new Parameter("productName", prodName);
paramNewName.getProperties().setLabel("Name"); /* I18N */
paramNewName.getProperties().setNullValueAllowed(false);
paramNewName.getProperties().setValidatorClass(ProductNodeNameValidator.class);
paramNewDesc = new Parameter("productDesc", prodDesc);
paramNewDesc.getProperties().setLabel("Description"); /* I18N */
paramNewDesc.getProperties().setNullValueAllowed(false);
paramSourceProduct = new Parameter("sourceProduct", valueSet[selectedProductIndex]);
paramSourceProduct.getProperties().setValueSet(valueSet);
paramSourceProduct.getProperties().setLabel("Derive from Product"); /* I18N */
paramSourceProduct.getProperties().setValueSetBound(true);
paramSourceProduct.setUIEnabled(enableSourceProduct);
paramSourceProduct.addParamChangeListener(new ParamChangeListener() {
public void parameterValueChanged(ParamChangeEvent event) {
subsetDef = null;
updateUI();
setNewProductName();
}
});
}
private void createUI() {
createButtonsAndLabels();
int line = 0;
JPanel dialogPane = GridBagUtils.createPanel();
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramNewName.getEditor().getLabelComponent(), gbc,
"fill=BOTH, weightx=0, insets.top=3");
GridBagUtils.addToPanel(dialogPane, paramNewName.getEditor().getComponent(), gbc, "weightx=1, gridwidth=3");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramNewDesc.getEditor().getLabelComponent(), gbc,
"weightx=0, gridwidth=1");
GridBagUtils.addToPanel(dialogPane, paramNewDesc.getEditor().getComponent(), gbc, "weightx=1, gridwidth=3");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramSourceProduct.getEditor().getLabelComponent(), gbc,
"fill=NONE, gridwidth=4, insets.top=15");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, paramSourceProduct.getEditor().getComponent(), gbc,
"fill=HORIZONTAL, insets.top=3");
gbc.gridy = ++line;
final JPanel radioPanel = new JPanel(new BorderLayout());
radioPanel.add(copyAllRButton, BorderLayout.WEST);
radioPanel.add(geocodingRButton);
GridBagUtils.addToPanel(dialogPane, radioPanel, gbc, "fill=NONE, gridwidth=2");
GridBagUtils.addToPanel(dialogPane, subsetRButton, gbc, "gridwidth=1, weightx=300, anchor=EAST");
GridBagUtils.addToPanel(dialogPane, subsetButton, gbc, "fill=NONE, weightx=1, anchor=EAST");
gbc.gridy = ++line;
GridBagUtils.addToPanel(dialogPane, createInfoPanel(), gbc,
"fill=BOTH, anchor=WEST, insets.top=10, gridwidth=4");
setContent(dialogPane);
final JComponent editorComponent = paramNewName.getEditor().getEditorComponent();
if (editorComponent instanceof JTextComponent) {
JTextComponent tf = (JTextComponent) editorComponent;
tf.selectAll();
tf.requestFocus();
}
}
private JPanel createInfoPanel() {
final JPanel infoPanel = GridBagUtils.createDefaultEmptyBorderPanel();
infoPanel.setBorder(UIUtils.createGroupBorder("Output Product Information"));
final GridBagConstraints gbc2 = GridBagUtils.createDefaultConstraints();
GridBagUtils.addToPanel(infoPanel, new JLabel("Scene Width:"), gbc2);
GridBagUtils.addToPanel(infoPanel, labelWidthInfo, gbc2);
GridBagUtils.addToPanel(infoPanel, new JLabel("pixel"), gbc2, "weightx=1");
GridBagUtils.addToPanel(infoPanel, new JLabel("Scene Height:"), gbc2, "gridy=1, weightx=0");
GridBagUtils.addToPanel(infoPanel, labelHeightInfo, gbc2);
GridBagUtils.addToPanel(infoPanel, new JLabel("pixel"), gbc2, "weightx=1");
GridBagUtils.addToPanel(infoPanel, new JLabel("Center Latitude:"), gbc2, "gridy=2, weightx=0");
GridBagUtils.addToPanel(infoPanel, labelCenterLatInfo, gbc2, "weightx=1, gridwidth=2");
GridBagUtils.addToPanel(infoPanel, new JLabel("Center Longitude:"), gbc2, "gridy=3, weightx=0, gridwidth=1");
GridBagUtils.addToPanel(infoPanel, labelCenterLonInfo, gbc2, "weightx=1, gridwidth=2");
return infoPanel;
}
private void createButtonsAndLabels() {
copyAllRButton = new JRadioButton("Copy");
geocodingRButton = new JRadioButton("Use Geocoding Only");
subsetRButton = new JRadioButton("Use Subset");
ButtonGroup buttonGroup = new ButtonGroup();
buttonGroup.add(copyAllRButton);
buttonGroup.add(geocodingRButton);
buttonGroup.add(subsetRButton);
copyAllRButton.setActionCommand(COPY_ALL_COMMAND);
geocodingRButton.setActionCommand(COPY_GEOCODING_COMMAND);
subsetRButton.setActionCommand(COPY_SUBSET_COMMAND);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
updateUI();
}
};
copyAllRButton.addActionListener(listener);
geocodingRButton.addActionListener(listener);
subsetRButton.addActionListener(listener);
if (subsetDef != null) {
subsetRButton.setSelected(true);
} else {
geocodingRButton.setSelected(true);
}
subsetButton = new JButton("Subset...");
subsetButton.addActionListener(createSubsetButtonListener());
labelWidthInfo = new JLabel(DEFAULT_NUMBER_TEXT);
labelHeightInfo = new JLabel(DEFAULT_NUMBER_TEXT);
labelCenterLatInfo = new JLabel(DEFAULT_LATLON_TEXT);
labelCenterLonInfo = new JLabel(DEFAULT_LATLON_TEXT);
}
private void updateUI() {
Product product = getSourceProduct();
if (subsetDef == null) {
subsetButton.setText("Define subset ...");
if (product != null) {
final int width = product.getSceneRasterWidth();
final int height = product.getSceneRasterHeight();
labelWidthInfo.setText("" + width);
labelHeightInfo.setText("" + height);
final GeoCoding geoCoding = product.getSceneGeoCoding();
if (geoCoding != null) {
final GeoPos pos = geoCoding.getGeoPos(new PixelPos(0.5f * width + 0.5f, 0.5f * height + 0.5f),
null);
labelCenterLatInfo.setText(pos.getLatString());
labelCenterLonInfo.setText(pos.getLonString());
} else {
labelCenterLatInfo.setText(DEFAULT_LATLON_TEXT);
labelCenterLonInfo.setText(DEFAULT_LATLON_TEXT);
}
} else {
labelWidthInfo.setText(DEFAULT_NUMBER_TEXT);
labelHeightInfo.setText(DEFAULT_NUMBER_TEXT);
labelCenterLatInfo.setText(DEFAULT_LATLON_TEXT);
labelCenterLonInfo.setText(DEFAULT_LATLON_TEXT);
}
} else {
subsetButton.setText("Edit Subset...");
final Rectangle region = subsetDef.getRegion();
final int subSamplingX = subsetDef.getSubSamplingX();
final int subSamplingY = subsetDef.getSubSamplingY();
labelWidthInfo.setText("" + ((region.width - 1) / subSamplingX + 1));
labelHeightInfo.setText("" + ((region.height - 1) / subSamplingY + 1));
if (product == null) {
labelCenterLatInfo.setText(DEFAULT_LATLON_TEXT);
labelCenterLonInfo.setText(DEFAULT_LATLON_TEXT);
} else {
final GeoCoding geoCoding = product.getSceneGeoCoding();
if (geoCoding == null) {
labelCenterLatInfo.setText(DEFAULT_LATLON_TEXT);
labelCenterLonInfo.setText(DEFAULT_LATLON_TEXT);
} else {
final float centerX = 0.5f * region.width + region.x;
final float centerY = 0.5f * region.height + region.y;
final PixelPos centerPoint = new PixelPos(centerX + 0.5f, centerY + 0.5f);
final GeoPos pos = geoCoding.getGeoPos(centerPoint, null);
labelCenterLatInfo.setText(pos.getLatString());
labelCenterLonInfo.setText(pos.getLonString());
}
}
}
final boolean geocodingAvailable = product != null && product.getSceneGeoCoding() != null;
geocodingRButton.setEnabled(geocodingAvailable);
if (geocodingRButton.isSelected() && !geocodingAvailable) {
subsetRButton.setSelected(true);
}
subsetButton.setEnabled(subsetRButton.isSelected());
}
private ActionListener createSubsetButtonListener() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
Product product = getSourceProduct();
if (product == null) {
return;
}
ProductSubsetDialog dialog = new ProductSubsetDialog(parent, product, subsetDef);
if (dialog.show() == ProductSubsetDialog.ID_OK) {
if (dialog.getProductSubsetDef().isEntireProductSelected()) {
subsetDef = null;
} else {
subsetDef = dialog.getProductSubsetDef();
}
}
updateUI();
}
};
}
private boolean hasPrefix() {
return prefix != null && prefix.length() > 1;
}
private void setNewProductName() {
final String newProductName = createNewProductName(getSourceProduct().getName());
paramNewName.setValue(newProductName, null);
}
private String createNewProductName(String sourceProductName) {
String newNameBase = "";
if (sourceProductName != null && sourceProductName.length() > 0) {
newNameBase = FileUtils.exchangeExtension(sourceProductName, "");
}
String newNamePrefix = "product";
if (hasPrefix()) {
newNamePrefix = prefix;
}
String newProductName;
if (newNameBase.length() > 0) {
newProductName = newNamePrefix + "_" + numNewProducts + "_" + newNameBase;
} else {
newProductName = newNamePrefix + "_" + numNewProducts;
}
return newProductName;
}
}
| 19,005 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
BasicView.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/BasicView.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;
import com.bc.ceres.swing.selection.SelectionContext;
import javax.swing.JPanel;
/**
* The base class for application view panes. It provides support for a context menu and command handling.
*
* @see PopupMenuFactory
*/
public abstract class BasicView extends JPanel implements PopupMenuFactory, Disposable {
/**
* Creates a new <code>BasicView</code> with a double buffer and a flow layout.
*/
public BasicView() {
}
/**
* Releases all of the resources used by this view, its subcomponents, and all of its owned children.
*/
public void dispose() {
}
/**
* Gets the current selection context, if any.
*
* @return The current selection context, or {@code null} if none exists.
* @since BEAM 4.7
*/
public SelectionContext getSelectionContext() {
return null;
}
}
| 1,608 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
WorldMapImageLoader.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/WorldMapImageLoader.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;
import com.bc.ceres.binding.PropertyContainer;
import com.bc.ceres.glayer.CollectionLayer;
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.grender.support.BufferedImageRendering;
import org.geotools.referencing.crs.DefaultGeographicCRS;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
/**
* This utility class is responsible for loading the world map image.
*
* @author Marco Peters
* @version $Revision$ $Date$
*/
public class WorldMapImageLoader {
private static BufferedImage worldMapImage;
private static boolean highResolution = false;
private static final Dimension HI_RES_DIMENSION = new Dimension(4320, 2160);
private static final Dimension LOW_RES_DIMENSION = new Dimension(2160, 1080);
private WorldMapImageLoader() {
}
/**
* Reads the world map image from disk if not yet loaded, otherwise
* it is just returning the image.
* <p>
* If the world map image cannot be read an image with an error message is returned.
*
* @param highRes specifies if the high-resolution image shall be returned,
*
* @return the world map image
*/
public static BufferedImage getWorldMapImage(boolean highRes) {
if (worldMapImage == null || isHighRes() != highRes) {
setHighRes(highRes);
LayerType layerType = LayerTypeRegistry.getLayerType("org.esa.snap.worldmap.BlueMarbleLayerType");
if (layerType == null) {
worldMapImage = createErrorImage();
} else {
final CollectionLayer rootLayer = new CollectionLayer();
Layer worldMapLayer = layerType.createLayer(new WorldMapLayerContext(rootLayer), new PropertyContainer());
Dimension dimension = highRes ? HI_RES_DIMENSION : LOW_RES_DIMENSION;
final BufferedImageRendering biRendering = new BufferedImageRendering(dimension.width,
dimension.height);
biRendering.getViewport().setModelYAxisDown(false);
biRendering.getViewport().zoom(worldMapLayer.getModelBounds());
worldMapLayer.render(biRendering);
worldMapImage = biRendering.getImage();
}
}
return worldMapImage;
}
private static BufferedImage createErrorImage() {
final BufferedImage errorImage = new BufferedImage(LOW_RES_DIMENSION.width, LOW_RES_DIMENSION.height,
BufferedImage.TYPE_3BYTE_BGR);
final Graphics graphics = errorImage.getGraphics();
graphics.setColor(Color.WHITE);
final Font font = graphics.getFont().deriveFont(75.0f);
if (graphics instanceof Graphics2D) {
final Graphics2D g2d = (Graphics2D) graphics;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
}
graphics.setFont(font);
final String msg = "Failed to load worldmap image.";
final Rectangle2D stringBounds = graphics.getFontMetrics().getStringBounds(msg, graphics);
final int xPos = (int) (errorImage.getWidth() * 0.5f - stringBounds.getWidth() * 0.5f);
final int yPos = (int) (errorImage.getWidth() * 0.1f);
graphics.drawString(msg, xPos, yPos);
return errorImage;
}
private static boolean isHighRes() {
return highResolution;
}
private static void setHighRes(boolean highRes) {
highResolution = highRes;
}
private static class WorldMapLayerContext implements LayerContext {
private final Layer rootLayer;
private WorldMapLayerContext(Layer rootLayer) {
this.rootLayer = rootLayer;
}
@Override
public Object getCoordinateReferenceSystem() {
return DefaultGeographicCRS.WGS84;
}
@Override
public Layer getRootLayer() {
return rootLayer;
}
}
}
| 5,066 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
GridLayout2.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/GridLayout2.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;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
/**
* A grid layout which allows components of differrent sizes.
*/
public class GridLayout2 extends GridLayout {
public GridLayout2() {
this(1, 0, 0, 0);
}
public GridLayout2(int rows, int cols) {
this(rows, cols, 0, 0);
}
public GridLayout2(int rows, int cols, int hgap, int vgap) {
super(rows, cols, hgap, vgap);
}
@Override
public Dimension preferredLayoutSize(Container parent) {
//System.err.println("preferredLayoutSize");
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int nrows = getRows();
int ncols = getColumns();
if (nrows > 0) {
ncols = (ncomponents + nrows - 1) / nrows;
} else {
nrows = (ncomponents + ncols - 1) / ncols;
}
int[] w = new int[ncols];
int[] h = new int[nrows];
for (int i = 0; i < ncomponents; i++) {
int r = i / ncols;
int c = i % ncols;
Component comp = parent.getComponent(i);
Dimension d = comp.getPreferredSize();
if (w[c] < d.width) {
w[c] = d.width;
}
if (h[r] < d.height) {
h[r] = d.height;
}
}
int nw = 0;
for (int j = 0; j < ncols; j++) {
nw += w[j];
}
int nh = 0;
for (int i = 0; i < nrows; i++) {
nh += h[i];
}
return new Dimension(insets.left + insets.right + nw + (ncols - 1) * getHgap(),
insets.top + insets.bottom + nh + (nrows - 1) * getVgap());
}
}
@Override
public Dimension minimumLayoutSize(Container parent) {
//System.err.println("minimumLayoutSize");
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int nrows = getRows();
int ncols = getColumns();
if (nrows > 0) {
ncols = (ncomponents + nrows - 1) / nrows;
} else {
nrows = (ncomponents + ncols - 1) / ncols;
}
int[] w = new int[ncols];
int[] h = new int[nrows];
for (int i = 0; i < ncomponents; i++) {
int r = i / ncols;
int c = i % ncols;
Component comp = parent.getComponent(i);
Dimension d = comp.getMinimumSize();
if (w[c] < d.width) {
w[c] = d.width;
}
if (h[r] < d.height) {
h[r] = d.height;
}
}
int nw = 0;
for (int j = 0; j < ncols; j++) {
nw += w[j];
}
int nh = 0;
for (int i = 0; i < nrows; i++) {
nh += h[i];
}
return new Dimension(insets.left + insets.right + nw + (ncols - 1) * getHgap(),
insets.top + insets.bottom + nh + (nrows - 1) * getVgap());
}
}
@Override
public void layoutContainer(Container parent) {
//System.err.println("layoutContainer");
synchronized (parent.getTreeLock()) {
Insets insets = parent.getInsets();
int ncomponents = parent.getComponentCount();
int nrows = getRows();
int ncols = getColumns();
if (ncomponents == 0) {
return;
}
if (nrows > 0) {
ncols = (ncomponents + nrows - 1) / nrows;
} else {
nrows = (ncomponents + ncols - 1) / ncols;
}
int hgap = getHgap();
int vgap = getVgap();
// scaling factors
Dimension pd = preferredLayoutSize(parent);
double sw = (1.0 * parent.getWidth()) / pd.width;
double sh = (1.0 * parent.getHeight()) / pd.height;
// scale
int[] w = new int[ncols];
int[] h = new int[nrows];
for (int i = 0; i < ncomponents; i++) {
int r = i / ncols;
int c = i % ncols;
Component comp = parent.getComponent(i);
Dimension d = comp.getPreferredSize();
d.width = (int) (sw * d.width);
d.height = (int) (sh * d.height);
if (w[c] < d.width) {
w[c] = d.width;
}
if (h[r] < d.height) {
h[r] = d.height;
}
}
for (int c = 0, x = insets.left; c < ncols; c++) {
for (int r = 0, y = insets.top; r < nrows; r++) {
int i = r * ncols + c;
if (i < ncomponents) {
parent.getComponent(i).setBounds(x, y, w[c], h[r]);
}
y += h[r] + vgap;
}
x += w[c] + hgap;
}
}
}
}
| 6,130 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
DecimalTableCellRenderer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/DecimalTableCellRenderer.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;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import java.awt.Component;
import java.text.DecimalFormat;
/**
* TableCellRenderer which renders {@link Float float} and {@link Double double}
* values with the given {@link DecimalFormat format}.
* The cell value is right aligned.
*/
public class DecimalTableCellRenderer extends DefaultTableCellRenderer {
private DecimalFormat format;
/**
* Creates a new TableCellRenderer with the given format
*
* @param format the format in which the cell values shall be rendered.
*
* @see DecimalFormat
*/
public DecimalTableCellRenderer(DecimalFormat format) {
this.format = format;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if (comp instanceof JLabel) {
JLabel label = (JLabel) comp;
label.setHorizontalAlignment(JLabel.RIGHT);
if (value instanceof Float && !Float.isNaN((Float) value) ||
value instanceof Double && !Double.isNaN((Double) value)) {
label.setText(format.format(value));
} else {
label.setText("n/a");
}
}
return comp;
}
}
| 2,258 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UIUtils.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/UIUtils.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;
import org.esa.snap.core.param.ParamProperties;
import org.esa.snap.core.param.Parameter;
import org.esa.snap.core.util.ArrayUtils;
import org.esa.snap.core.util.Guardian;
import org.esa.snap.core.util.StringUtils;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFormattedTextField;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JSpinner;
import javax.swing.KeyStroke;
import javax.swing.SpinnerNumberModel;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.net.URL;
import java.text.DecimalFormat;
/**
* The <code>UIUtils</code> class provides methods frequently used in connection with graphical user interfaces.
*
* @author Norman Fomferra
* @version $Revision: 8407 $ $Date: 2010-02-14 12:58:02 +0100 (So, 14 Feb 2010) $
*/
public class UIUtils {
public static final String PROPERTY_SOURCE_PRODUCT = "SOURCE_PRODUCT";
public static final String IMAGE_RESOURCE_PATH = "/org/esa/snap/resources/images/";
public static final Color COLOR_DARK_RED = new Color(128, 0, 0);
public static final Color COLOR_DARK_BLUE = new Color(0, 0, 128);
public static final Color COLOR_DARK_GREEN = new Color(0, 128, 0);
/**
* Gets the image icon loaded from the given resource path.
* <p>Note that this method only works for images found in the classpath of the class loader which loaded this {@link UIUtils} class.
* If you are not sure, you should better use {@link #getImageURL(String, Class)}.</p>
*
* @param resourcePath the resource path
*
* @return an image icon loaded from the given resource path or <code>null</code> if it could not be found
*/
public static ImageIcon loadImageIcon(String resourcePath) {
return loadImageIcon(resourcePath, UIUtils.class);
}
/**
* Gets the image icon loaded from the given resource path.
*
* @param resourcePath the resource path
* @param callerClass the class which calls this method and therefore provides the class loader for the requested resource
*
* @return an image icon loaded from the given resource path or <code>null</code> if it could not be found
* @since 4.0
*/
public static ImageIcon loadImageIcon(String resourcePath, Class callerClass) {
if (StringUtils.isNotNullAndNotEmpty(resourcePath)) {
URL location = getImageURL(resourcePath, callerClass);
return (location != null) ? new ImageIcon(location) : null;
}
return null;
}
/**
* Gets the location of the given image resource path as an URL.
* <p>Note that this method only works for images found in the classpath of the class loader which loaded this {@link UIUtils} class.
* If you are not sure, you should better use {@link #getImageURL(String, Class)}.</p>
*
* @param resourcePath the resource path
*
* @return an URL representing the given resource path or <code>null</code> if it could not be found
*/
public static URL getImageURL(String resourcePath) {
return getImageURL(resourcePath, UIUtils.class);
}
/**
* Gets the location of the given image resource path as an URL.
*
* @param resourcePath the resource path
* @param callerClass the class which calls this method and therefore provides the class loader for the requested resource
*
* @return an URL representing the given resource path or <code>null</code> if it could not be found
* @since 4.0
*/
public static URL getImageURL(String resourcePath, Class callerClass) {
String absResourcePath = resourcePath;
if (!absResourcePath.startsWith("/")) {
absResourcePath = IMAGE_RESOURCE_PATH + resourcePath;
}
return callerClass.getResource(absResourcePath);
}
/**
* Returns the (main) screen's size in pixels.
*/
public static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
/**
* Returns the (main) screen's width in pixels.
*/
public static int getScreenWidth() {
return getScreenSize().width;
}
/**
* Returns the (main) screen's height in pixels.
*/
public static int getScreenHeight() {
return getScreenSize().height;
}
/**
* Centers the given component within the screen area.
* <p> The method performs the alignment by setting a newly computed location for the component. It does not alter
* the component's size.
*
* @param comp the component whose location is to be altered
*
* @throws IllegalArgumentException if the component is <code>null</code>
*/
public static void centerComponent(Component comp) {
centerComponent(comp, null);
}
/**
* Centers the given component over another component.
* <p> The method performs the alignment by setting a newly computed location for the component. It does not alter
* the component's size.
*
* @param comp the component whose location is to be altered
* @param alignComp the component used for the alignment of the first component, if <code>null</code> the component
* is ceneterd within the screen area
*
* @throws IllegalArgumentException if the component is <code>null</code>
*/
public static void centerComponent(Component comp, Component alignComp) {
if (comp == null) {
throw new IllegalArgumentException("comp must not be null");
}
Dimension compSize = comp.getSize();
Dimension screenSize = getScreenSize();
int x1, y1;
if (alignComp != null) {
Point alignCompOffs = alignComp.getLocation();
Dimension alignCompSize = alignComp.getSize();
x1 = alignCompOffs.x + (alignCompSize.width - compSize.width) / 2;
y1 = alignCompOffs.y + (alignCompSize.height - compSize.height) / 2;
} else {
x1 = (screenSize.width - compSize.width) / 2;
y1 = (screenSize.height - compSize.height) / 2;
}
int x2 = x1 + compSize.width;
int y2 = y1 + compSize.height;
if (x2 >= screenSize.width) {
x1 = screenSize.width - compSize.width - 1;
}
if (y2 >= screenSize.height) {
y1 = screenSize.height - compSize.height - 1;
}
if (x1 < 0) {
x1 = 0;
}
if (y1 < 0) {
y1 = 0;
}
comp.setLocation(x1, y1);
}
/**
* Prevent's instantiation.
*/
private UIUtils() {
}
/**
* Ensures that the popup menue is allways inside the application frame
*/
public static void showPopup(JPopupMenu popup, MouseEvent event) {
if (popup == null) {
return;
}
final Component component = event.getComponent();
final Point point = event.getPoint();
popup.show(component, point.x, point.y);
}
public static Window getRootWindow(Component component) {
Guardian.assertNotNull("component", component);
do {
Component parent = component.getParent();
if (parent == null && component instanceof Window) {
return (Window) component;
}
component = parent;
} while (component != null);
return null;
}
public static Border createGroupBorder(String title) {
return BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED),
title);
}
public static Frame getRootFrame(Component component) {
Guardian.assertNotNull("component", component);
final Window window = getRootWindow(component);
return (window instanceof Frame) ? (Frame) window : null;
}
public static JFrame getRootJFrame(Component component) {
Guardian.assertNotNull("component", component);
final Window window = getRootWindow(component);
return (window instanceof JFrame) ? (JFrame) window : null;
}
public static Cursor setRootFrameWaitCursor(Component component) {
return setRootFrameCursor(component, Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
}
public static Cursor setRootFrameDefaultCursor(Component component) {
return setRootFrameCursor(component, Cursor.getDefaultCursor());
}
public static Cursor setRootFrameCursor(Component component, Cursor newCursor) {
Guardian.assertNotNull("component", component);
Frame frame = getRootFrame(component);
if (frame == null && component instanceof Frame) {
frame = (Frame) component;
}
Cursor oldCursor = null;
if (frame != null) {
oldCursor = frame.getCursor();
if (newCursor != null) {
frame.setCursor(newCursor);
} else {
frame.setCursor(Cursor.getDefaultCursor());
}
}
return oldCursor;
}
public static JMenu findMenu(JMenuBar menuBar, String name, boolean deepSearch) {
int n = menuBar.getMenuCount();
for (int i = 0; i < n; i++) {
JMenu menu = menuBar.getMenu(i);
if (name.equals(menu.getName())) {
return menu;
}
}
if (deepSearch) {
for (int i = 0; i < n; i++) {
JMenu menu = menuBar.getMenu(i);
JMenu subMenu = findSubMenu(menu.getPopupMenu(), name);
if (subMenu != null) {
return subMenu;
}
}
}
return null;
}
public static int findMenuPosition(JMenuBar menuBar, String name) {
int n = menuBar.getMenuCount();
for (int i = 0; i < n; i++) {
JMenu menu = menuBar.getMenu(i);
if (name.equals(menu.getName())) {
return i;
}
}
return -1;
}
public static int findMenuItemPosition(JPopupMenu popupMenu, String name) {
int n = popupMenu.getComponentCount();
for (int i = 0; i < n; i++) {
Component c = popupMenu.getComponent(i);
if (c instanceof JMenuItem) {
JMenuItem menuItem = (JMenuItem) c;
if (name.equals(menuItem.getName())) {
return i;
}
}
}
return -1;
}
public static JMenu findSubMenu(JPopupMenu popupMenu, String name) {
int n = popupMenu.getComponentCount();
for (int i = 0; i < n; i++) {
Component c = popupMenu.getComponent(i);
if (c instanceof JMenu) {
JMenu subMenu = (JMenu) c;
if (name.equals(subMenu.getName())) {
return subMenu;
}
subMenu = findSubMenu(subMenu.getPopupMenu(), name);
if (subMenu != null) {
return subMenu;
}
}
}
return null;
}
public static String getUniqueFrameTitle(final JInternalFrame[] frames, final String titleBase) {
if (frames.length == 0) {
return titleBase;
}
String[] titles = new String[frames.length];
for (int i = 0; i < frames.length; i++) {
JInternalFrame frame = frames[i];
titles[i] = frame.getTitle();
}
if (!ArrayUtils.isMemberOf(titleBase, titles)) {
return titleBase;
}
for (int i = 0; i < frames.length; i++) {
final String title = titleBase + " (" + (i + 2) + ")";
if (!ArrayUtils.isMemberOf(title, titles)) {
return title;
}
}
return titleBase + " (" + (frames.length + 1) + ")";
}
public static JSpinner createSpinner(final Parameter param, final Number spinnerStep, final String formatPattern) {
final Number v = (Number) param.getValue();
final ParamProperties properties = param.getProperties();
final Comparable min = (Comparable) properties.getMinValue();
final Comparable max = (Comparable) properties.getMaxValue();
final Double bigStep = spinnerStep.doubleValue() * 10;
final JSpinner spinner = createSpinner(v, min, max, spinnerStep, bigStep, formatPattern);
spinner.setName(properties.getLabel());
spinner.addChangeListener(e -> param.setValue(spinner.getValue(), ex -> true));
param.addParamChangeListener(event -> spinner.setValue(param.getValue()));
param.getEditor().getEditorComponent().addPropertyChangeListener("enabled",
evt -> spinner.setEnabled(((Boolean) evt.getNewValue()).booleanValue()));
properties.addPropertyChangeListener(evt -> {
if (ParamProperties.MAXVALUE_KEY.equals(evt.getPropertyName())) {
((SpinnerNumberModel) spinner.getModel()).setMaximum((Comparable) properties.getMaxValue());
}
if (ParamProperties.MINVALUE_KEY.equals(evt.getPropertyName())) {
((SpinnerNumberModel) spinner.getModel()).setMinimum((Comparable) properties.getMinValue());
}
});
final JSpinner.NumberEditor editor = ((JSpinner.NumberEditor) spinner.getEditor());
final JFormattedTextField textField = editor.getTextField();
textField.addFocusListener(new FocusListener() {
public void focusGained(FocusEvent e) {
textField.selectAll();
}
public void focusLost(FocusEvent e) {
}
});
return spinner;
}
public static JSpinner createDoubleSpinner(final double value, final double rangeMinimum,
final double rangeMaximum,
final double stepSize, final double bigStepSize,
final String formatPattern) {
final SpinnerNumberModel numberModel = new SpinnerNumberModel(value, rangeMinimum, rangeMaximum, stepSize);
final JSpinner spinner = new JSpinner(numberModel);
final JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.NumberEditor) {
JSpinner.NumberEditor numberEditor = (JSpinner.NumberEditor) editor;
final DecimalFormat format = numberEditor.getFormat();
format.applyPattern(formatPattern);
numberEditor.getTextField().setColumns(8);
}
final Double sss = stepSize;
final Double bss = bigStepSize;
final String bigDec = "dec++";
final String bigInc = "inc++";
final InputMap inputMap = spinner.getInputMap();
final ActionMap actionMap = spinner.getActionMap();
// big increase with "PAGE_UP" key
inputMap.put(KeyStroke.getKeyStroke("PAGE_UP"), bigInc);
actionMap.put(bigInc, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
numberModel.setStepSize(bss);
numberModel.setValue(numberModel.getNextValue());
numberModel.setStepSize(sss);
}
});
// big decrease with "PAGE_UP" key
inputMap.put(KeyStroke.getKeyStroke("PAGE_DOWN"), bigDec);
actionMap.put(bigDec, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
numberModel.setStepSize(bss);
numberModel.setValue(numberModel.getPreviousValue());
numberModel.setStepSize(sss);
}
});
return spinner;
}
public static JSpinner createSpinner(final Number value, final Comparable rangeMinimum, final Comparable rangeMaximum,
final Number stepSize, final Number bigStepSize, final String formatPattern) {
final SpinnerNumberModel numberModel = new SpinnerNumberModel(value, rangeMinimum, rangeMaximum, stepSize);
final JSpinner spinner = new JSpinner(numberModel);
final JComponent editor = spinner.getEditor();
if (editor instanceof JSpinner.NumberEditor) {
JSpinner.NumberEditor numberEditor = (JSpinner.NumberEditor) editor;
final DecimalFormat format = numberEditor.getFormat();
format.applyPattern(formatPattern);
numberEditor.getTextField().setColumns(8);
}
spinner.setValue(value);
final String bigDec = "dec++";
final String bigInc = "inc++";
final InputMap inputMap = spinner.getInputMap();
final ActionMap actionMap = spinner.getActionMap();
// big increase with "PAGE_UP" key
inputMap.put(KeyStroke.getKeyStroke("PAGE_UP"), bigInc);
actionMap.put(bigInc, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
numberModel.setStepSize(bigStepSize);
numberModel.setValue(numberModel.getNextValue());
numberModel.setStepSize(stepSize);
}
});
// big decrease with "PAGE_UP" key
inputMap.put(KeyStroke.getKeyStroke("PAGE_DOWN"), bigDec);
actionMap.put(bigDec, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
numberModel.setStepSize(bigStepSize);
numberModel.setValue(numberModel.getPreviousValue());
numberModel.setStepSize(stepSize);
}
});
return spinner;
}
}
| 19,033 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ButtonOverlayControl.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/ButtonOverlayControl.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;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.event.MouseInputAdapter;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Insets;
import java.awt.LinearGradientPaint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
/**
* A navigation control which appears as a screen overlay.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class ButtonOverlayControl extends JComponent {
private static final int BUTTON_SPACING = 3;
private static final int BUTTON_AREA_INSET = 5;
private static final int ARC_SIZE = BUTTON_AREA_INSET * 2;
private final Dimension buttonDimension;
private Rectangle2D.Double buttonArea;
private List<ButtonDef> buttonDefList;
private int numCols;
public ButtonOverlayControl(Action... actions) {
this(2, actions);
}
public ButtonOverlayControl(int numCols, Action... actions) {
this.numCols = numCols;
buttonDimension = new Dimension(24, 24);
buttonDefList = new ArrayList<>();
for (Action action : actions) {
String toolTipText = (String) action.getValue(TOOL_TIP_TEXT_KEY);
buttonDefList.add(new ButtonDef(action, buttonDimension, numCols, toolTipText));
}
Dimension preferredSize = computePreferredSize();
setPreferredSize(preferredSize);
setBounds(0, 0, preferredSize.width, preferredSize.height);
updateGeom(getPaintArea());
final MouseHandler mouseHandler = new MouseHandler();
addMouseListener(mouseHandler);
addMouseMotionListener(mouseHandler);
}
@Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
return computePreferredSize();
}
@Override
public final void setBounds(int x, int y, int width, int height) {
super.setBounds(x, y, width, height);
updateGeom(getPaintArea());
}
@Override
protected void paintComponent(Graphics g) {
final Rectangle bounds = getPaintArea();
if (bounds.isEmpty()) {
return;
}
final Graphics2D graphics2D = (Graphics2D) g;
graphics2D.setStroke(new BasicStroke(0.6f));
graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawBackground(bounds, graphics2D);
for (int i = 0; i < buttonDefList.size(); i++) {
drawButton(graphics2D, i);
}
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
for (ButtonDef buttonDef : buttonDefList) {
buttonDef.getAction().setEnabled(enabled);
}
}
private void drawBackground(Rectangle bounds, Graphics2D graphics2D) {
final Shape backgroundShape = new RoundRectangle2D.Double(bounds.x, bounds.y,
bounds.width, bounds.height,
ARC_SIZE, ARC_SIZE);
graphics2D.setColor(Color.BLACK);
graphics2D.draw(backgroundShape);
graphics2D.setColor(new Color(255, 255, 255, 64));
graphics2D.fill(backgroundShape);
}
private void drawButton(Graphics2D graphics2D, int buttonIndex) {
ButtonDef buttonDef = buttonDefList.get(buttonIndex);
Shape shape = buttonDef.getShape();
drawGradientShape(graphics2D, shape, buttonDef.isHighlighted());
Image image = buttonDef.getImage();
Point imageOffset = buttonDef.getImageOffset();
graphics2D.drawImage(image, imageOffset.x, imageOffset.y, null);
}
private void drawGradientShape(Graphics2D graphics2D, Shape shape, boolean highlighted) {
graphics2D.setColor(Color.BLACK);
graphics2D.draw(shape);
final Point startPos = shape.getBounds().getLocation();
final Point endPos = (Point) startPos.clone();
endPos.y = startPos.y + shape.getBounds().height;
final LinearGradientPaint paint;
if (highlighted) {
paint = new LinearGradientPaint(startPos, endPos,
new float[]{0.0f, 0.5f, 0.6f, 0.8f, 1.0f},
new Color[]{
new Color(255, 255, 255, 64),
new Color(255, 255, 255, 255),
new Color(255, 255, 255, 255),
new Color(255, 255, 255, 160),
new Color(0, 0, 0, 160)
});
} else {
paint = new LinearGradientPaint(startPos, endPos,
new float[]{0.0f, 0.5f, 0.6f, 0.8f, 1.0f},
new Color[]{
new Color(255, 255, 255, 0),
new Color(255, 255, 255, 64),
new Color(255, 255, 255, 64),
new Color(255, 255, 255, 30),
new Color(0, 0, 0, 40)
});
}
graphics2D.setPaint(paint);
graphics2D.fill(shape);
}
private Point computeButtonLocation(int buttonIndex) {
final int xIndex = buttonIndex % numCols;
final int yIndex = buttonIndex / numCols;
int xLocation = (int) buttonArea.x + xIndex * (buttonDimension.width + BUTTON_SPACING);
int yLocation = (int) buttonArea.y + yIndex * (buttonDimension.height + BUTTON_SPACING);
return new Point(xLocation, yLocation);
}
private Dimension computePreferredSize() {
int numButtons = buttonDefList.size();
int buttonCols = numButtons <= 1 ? 1 : numCols;
int buttonRows = numButtons <= 1 ? 1 : (numButtons + 1) / buttonCols;
int width = BUTTON_AREA_INSET;
int height = BUTTON_AREA_INSET;
width += buttonCols * (buttonDimension.width);
height += buttonRows * (buttonDimension.height);
width += (buttonCols - 1) * (BUTTON_SPACING);
height += (buttonRows - 1) * (BUTTON_SPACING);
width += BUTTON_AREA_INSET;
height += BUTTON_AREA_INSET;
return new Dimension(width, height);
}
private void updateGeom(Rectangle bounds) {
buttonArea = new Rectangle2D.Double(bounds.x + BUTTON_AREA_INSET - 1,
bounds.y + BUTTON_AREA_INSET - 1,
bounds.width - BUTTON_AREA_INSET * 2 + 2,
bounds.height - BUTTON_AREA_INSET * 2 + 2);
for (int i = 0; i < buttonDefList.size(); i++) {
ButtonDef buttonDef = buttonDefList.get(i);
buttonDef.setShapeLocation(computeButtonLocation(i));
}
}
private Rectangle getPaintArea() {
final Insets insets = getInsets();
int x = insets.left + 1;
int y = insets.top + 1;
int w = getWidth() - (insets.left + insets.right) - 2;
int h = getHeight() - (insets.top + insets.bottom) - 2;
return new Rectangle(x, y, w, h);
}
private ButtonDef getButtonDef(int x, int y) {
for (ButtonDef buttonDef : buttonDefList) {
if (buttonDef.getShape().contains(x, y)) {
return buttonDef;
}
}
return null;
}
private class MouseHandler extends MouseInputAdapter {
@Override
public void mouseClicked(MouseEvent e) {
ButtonDef buttonDef = getButtonDef(e.getX(), e.getY());
if (buttonDef != null) {
final Action action = buttonDef.getAction();
action.actionPerformed(new ActionEvent(e.getSource(), e.getID(), e.paramString()));
e.consume();
}
}
@Override
public void mouseMoved(MouseEvent e) {
for (ButtonDef buttonDef : buttonDefList) {
if (buttonDef.getShape().contains(e.getX(), e.getY())) {
buttonDef.setHighlighted(true);
String toolTipText = buttonDef.getToolTipText();
setToolTipText(toolTipText);
} else {
buttonDef.setHighlighted(false);
}
}
repaint();
}
}
private static class ButtonDef {
private final Action action;
private final int numCols;
private final Image image;
private RoundRectangle2D.Double shape;
private boolean highlighted;
private String toolTipText;
private ButtonDef(Action action, Dimension buttonDimension, int numCols, String toolTipText) {
this.action = action;
this.numCols = numCols;
this.toolTipText = toolTipText;
Image rawImage = iconToImage((Icon) this.action.getValue(Action.LARGE_ICON_KEY));
image = rawImage.getScaledInstance(buttonDimension.width,
buttonDimension.height,
Image.SCALE_SMOOTH);
shape = new RoundRectangle2D.Double();
shape.arcwidth = 4;
shape.archeight = 4;
shape.setFrame(new Point(), buttonDimension);
}
public Action getAction() {
return action;
}
public Image getImage() {
return image;
}
public Point getImageOffset() {
final Rectangle bounds = shape.getBounds();
final int xOffset = bounds.x + (bounds.width - image.getWidth(null)) / numCols;
final int yOffset = bounds.y + (bounds.height - image.getHeight(null)) / numCols;
return new Point(xOffset, yOffset);
}
public Shape getShape() {
return (Shape) shape.clone();
}
public void setShapeLocation(Point point) {
shape.setFrame(point, shape.getBounds().getSize());
}
public void setShapeDimension(Dimension dimension) {
shape.setFrame(shape.getBounds().getLocation(), dimension);
}
private static Image iconToImage(Icon icon) {
if (icon instanceof ImageIcon) {
return ((ImageIcon) icon).getImage();
} else {
int w = icon.getIconWidth();
int h = icon.getIconHeight();
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gd.getDefaultConfiguration();
BufferedImage image = gc.createCompatibleImage(w, h);
Graphics2D g = image.createGraphics();
icon.paintIcon(null, g, 0, 0);
g.dispose();
return image;
}
}
private String getToolTipText(){ return this.toolTipText; }
public void setHighlighted(boolean highlighted) {
this.highlighted = highlighted;
}
public boolean isHighlighted() {
return highlighted;
}
}
}
| 12,887 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
UserInputHistory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/UserInputHistory.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;
import org.esa.snap.core.util.Guardian;
import java.util.LinkedList;
import java.util.List;
import java.util.prefs.Preferences;
/**
* <code>UserInputHistory</code> is a fixed-size array for {@code String} entries edited by a user. If a new entry is added
* and the history is full, the list of registered entries is shifted so that the oldest entry is beeing
* skipped.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class UserInputHistory {
private String propertyKey;
private int maxNumEntries;
private List<String> entriesList;
public UserInputHistory(int maxNumEntries, String propertyKey) {
Guardian.assertNotNullOrEmpty("propertyKey", propertyKey);
this.propertyKey = propertyKey;
setMaxNumEntries(maxNumEntries);
}
public int getNumEntries() {
if (entriesList != null) {
return entriesList.size();
}
return 0;
}
public int getMaxNumEntries() {
return maxNumEntries;
}
public String getPropertyKey() {
return propertyKey;
}
public String[] getEntries() {
if (entriesList != null) {
return entriesList.toArray(new String[entriesList.size()]);
}
return null;
}
public void initBy(final Preferences preferences) {
int maxNumEntries = preferences.getInt(getLengthKey(), getMaxNumEntries());
setMaxNumEntries(maxNumEntries);
for (int i = maxNumEntries - 1; i >= 0; i--) {
String entry = preferences.get(getNumKey(i), null);
if (entry != null && isValidItem(entry)) {
push(entry);
}
}
}
protected boolean isValidItem(String item) {
return true;
}
public void push(String entry) {
if (entry != null && isValidItem(entry)) {
if (entriesList == null) {
entriesList = new LinkedList<String>();
}
for (String anEntry : entriesList) {
if (anEntry.equals(entry)) {
entriesList.remove(anEntry);
break;
}
}
if (entriesList.size() == maxNumEntries) {
entriesList.remove(entriesList.size() - 1);
}
entriesList.add(0, entry);
}
}
public void copyInto(Preferences preferences) {
preferences.putInt(getLengthKey(), maxNumEntries);
for (int i = 0; i < 100; i++) {
preferences.put(getNumKey(i), "");
}
final String[] entries = getEntries();
if (entries != null) {
for (int i = 0; i < entries.length; i++) {
preferences.put(getNumKey(i), entries[i]);
}
}
}
private String getLengthKey() {
return propertyKey + ".length";
}
private String getNumKey(int index) {
return propertyKey + "." + index;
}
public void setMaxNumEntries(int maxNumEntries) {
this.maxNumEntries = maxNumEntries > 0 ? maxNumEntries : 16;
if (entriesList != null) {
while (this.maxNumEntries < entriesList.size()) {
entriesList.remove(entriesList.size() - 1);
}
}
}
}
| 4,007 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ProjectionParamsDialog.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/ProjectionParamsDialog.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;
import org.esa.snap.core.dataop.maptransf.MapTransformUI;
import org.esa.snap.core.util.Guardian;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagConstraints;
import java.awt.Window;
public class ProjectionParamsDialog extends ModalDialog {
private final MapTransformUI _transformUI;
public ProjectionParamsDialog(Window parent, MapTransformUI transformUI) {
super(parent, "Projection Parameters", ID_OK_CANCEL | ID_RESET /*| ID_HELP*/, "mapProjection"); /* I18N */
Guardian.assertNotNull("transformUI", transformUI);
_transformUI = transformUI;
createUI();
}
public MapTransformUI getTransformUI() {
return _transformUI;
}
@Override
protected boolean verifyUserInput() {
return _transformUI.verifyUserInput();
}
@Override
protected void onReset() {
_transformUI.resetToDefaults();
}
///////////////////////////////////////////////////////////////////////////
/////// END OF PUBLIC
///////////////////////////////////////////////////////////////////////////
/**
* Creates the user interface from the UI component passed in tby the transform
*/
private void createUI() {
JPanel dialogPane = GridBagUtils.createPanel();
dialogPane.setBorder(new EmptyBorder(2, 2, 2, 2));
final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints();
GridBagUtils.addToPanel(dialogPane,
getTransformUI().getUIComponent(),
gbc, "gridwidth=1,insets.top=0");
setContent(dialogPane);
}
}
| 2,409 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
RGBImageProfilePane.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/RGBImageProfilePane.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;
import com.bc.ceres.swing.TableLayout;
import org.esa.snap.core.datamodel.Product;
import org.esa.snap.core.datamodel.RGBImageProfile;
import org.esa.snap.core.datamodel.RGBImageProfileManager;
import org.esa.snap.core.dataop.barithm.BandArithmetic;
import org.esa.snap.core.jexp.ParseException;
import org.esa.snap.core.util.ArrayUtils;
import org.esa.snap.core.util.Debug;
import org.esa.snap.core.util.PropertyMap;
import org.esa.snap.core.util.StringUtils;
import org.esa.snap.core.util.io.FileUtils;
import org.esa.snap.core.util.io.SnapFileFilter;
import org.esa.snap.core.util.math.Range;
import org.esa.snap.ui.product.ProductExpressionPane;
import org.esa.snap.ui.tool.ToolButtonFactory;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.*;
public class RGBImageProfilePane extends JPanel {
private static final boolean SHOW_ALPHA = false;
private static final String[] COLOR_COMP_NAMES = new String[]{
"Red", /*I18N*/
"Green", /*I18N*/
"Blue", /*I18N*/
"Alpha", /*I18N*/
};
public static final Font EXPRESSION_FONT = new Font("Courier", Font.PLAIN, 12);
private static final Color okMsgColor = new Color(0, 128, 0);
private static final Color warnMsgColor = new Color(128, 0, 0);
private PropertyMap preferences;
private Product product;
private final Product[] openedProducts;
private JComboBox<ProfileItem> profileBox;
private final JComboBox[] rgbaExprBoxes;
private final RangeComponents[] rangeComponents;
private DefaultComboBoxModel<ProfileItem> profileModel;
private AbstractAction saveAsAction;
private AbstractAction deleteAction;
private boolean settingRgbaExpressions;
private File lastDir;
protected JCheckBox storeInProductCheck;
private JLabel referencedRastersAreCompatibleLabel;
public RGBImageProfilePane(PropertyMap preferences) {
this(preferences, null, null, null);
}
public RGBImageProfilePane(PropertyMap preferences, Product product,
final Product[] openedProducts, final int[] defaultBandIndices) {
this.preferences = preferences;
this.product = product;
this.openedProducts = openedProducts;
AbstractAction openAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
performOpen();
}
};
openAction.putValue(Action.LARGE_ICON_KEY, UIUtils.loadImageIcon("icons/Open24.gif"));
openAction.putValue(Action.SHORT_DESCRIPTION, "Open an external RGB profile");
saveAsAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
performSaveAs();
}
};
saveAsAction.putValue(Action.LARGE_ICON_KEY, UIUtils.loadImageIcon("icons/Save24.gif"));
saveAsAction.putValue(Action.SHORT_DESCRIPTION, "Save the RGB profile");
deleteAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
performDelete();
}
};
deleteAction.putValue(Action.LARGE_ICON_KEY,
UIUtils.loadImageIcon("icons/Remove24.gif")); // todo - use the nicer "cross" icon
deleteAction.putValue(Action.SHORT_DESCRIPTION, "Delete the selected RGB profile");
final JPanel storageButtonPanel = new JPanel(new GridLayout(1, 3, 2, 2));
storageButtonPanel.add(ToolButtonFactory.createButton(openAction, false));
storageButtonPanel.add(ToolButtonFactory.createButton(saveAsAction, false));
storageButtonPanel.add(ToolButtonFactory.createButton(deleteAction, false));
profileModel = new DefaultComboBoxModel<>();
profileBox = new JComboBox<>(profileModel);
profileBox.addItemListener(new ProfileSelectionHandler());
profileBox.setEditable(false);
profileBox.setName("profileBox");
setPreferredWidth(profileBox, 200);
storeInProductCheck = new JCheckBox();
storeInProductCheck.setText("Store RGB channels as virtual bands in current product");
storeInProductCheck.setSelected(false);
storeInProductCheck.setVisible(this.product != null);
storeInProductCheck.setName("storeInProductCheck");
final String[] bandNames;
if (this.product != null) {
bandNames = this.product.getBandNames();
// if multiple compatible products, the band names should be prefixed by the index of the product
// in order to avoid ambiguity
if (this.openedProducts.length > 1) {
for (int i = 0; i < bandNames.length; i++) {
bandNames[i] = BandArithmetic.getProductNodeNamePrefix(this.product) + bandNames[i];
}
}
} else {
bandNames = new String[0];
}
rgbaExprBoxes = new JComboBox[4];
for (int i = 0; i < rgbaExprBoxes.length; i++) {
rgbaExprBoxes[i] = createRgbaBox(bandNames);
rgbaExprBoxes[i].setName("rgbExprBox_" + i);
}
rangeComponents = new RangeComponents[3];
for (int i = 0; i < rangeComponents.length; i++) {
rangeComponents[i] = new RangeComponents();
}
JPanel profilePanel = new JPanel(new BorderLayout(2, 2));
profilePanel.add(new JLabel("Profile: "), BorderLayout.NORTH);
profilePanel.add(profileBox, BorderLayout.CENTER);
profilePanel.add(storageButtonPanel, BorderLayout.EAST);
JPanel colorComponentPanel = new JPanel(new GridBagLayout());
final GridBagConstraints c3 = new GridBagConstraints();
c3.anchor = GridBagConstraints.WEST;
c3.fill = GridBagConstraints.HORIZONTAL;
c3.insets = new Insets(2, 2, 2, 2);
final int n = SHOW_ALPHA ? 4 : 3;
for (int i = 0; i < n; i++) {
c3.gridy = 2 * i;
addColorComponentRow(colorComponentPanel, c3, i);
c3.gridy = 2 * i + 1;
addColorRangeComponentsRow(colorComponentPanel, c3, i);
}
referencedRastersAreCompatibleLabel = new JLabel();
TableLayout layout = new TableLayout(1);
layout.setTableFill(TableLayout.Fill.BOTH);
layout.setTableWeightX(1.0);
layout.setRowWeightY(3, 1.0);
layout.setTablePadding(10, 10);
setLayout(layout);
add(profilePanel);
add(colorComponentPanel);
layout.setCellFill(2, 0, TableLayout.Fill.NONE);
layout.setCellAnchor(2, 0, TableLayout.Anchor.NORTHEAST);
add(referencedRastersAreCompatibleLabel);
add(storeInProductCheck);
add(layout.createVerticalSpacer());
final RGBImageProfile[] registeredProfiles = RGBImageProfileManager.getInstance().getAllProfiles();
addProfiles(registeredProfiles);
if (this.product != null) {
final RGBImageProfile productProfile = RGBImageProfile.getCurrentProfile(this.product);
if (productProfile.isValid()) {
final RGBImageProfile similarProfile = findMatchingProfile(productProfile);
if (similarProfile != null) {
selectProfile(similarProfile);
} else {
addNewProfile(productProfile);
selectProfile(productProfile);
}
} else {
List<RGBImageProfile> selectableProfiles = new ArrayList<>();
for (int i = 0; i < profileModel.getSize(); i++) {
selectableProfiles.add(profileModel.getElementAt(i).getProfile());
}
RGBImageProfile[] selectableProfileArray = selectableProfiles.toArray(new RGBImageProfile[0]);
RGBImageProfile profile = findProfileForProductPattern(selectableProfileArray, product);
if (profile != null) {
selectProfile(profile);
}
}
}
setRgbaExpressionsFromSelectedProfile();
if (profileModel.getSelectedItem() == null) {
// default
if (defaultBandIndices != null && defaultBandIndices.length > 0) {
for (int i = 0; i < defaultBandIndices.length; ++i) {
rgbaExprBoxes[i].setSelectedIndex(defaultBandIndices[i]);
}
}
}
}
public Product getProduct() {
return product;
}
public void dispose() {
preferences = null;
product = null;
profileModel.removeAllElements();
profileModel = null;
profileBox = null;
saveAsAction = null;
deleteAction = null;
Arrays.fill(rgbaExprBoxes, null);
Arrays.fill(rangeComponents, null);
}
public boolean getStoreProfileInProduct() {
return storeInProductCheck.isSelected();
}
/**
* Gets the selected RGB-image profile if any.
*
* @return the selected profile, can be null
* @see #getRgbaExpressions()
*/
public RGBImageProfile getSelectedProfile() {
final ProfileItem profileItem = getSelectedProfileItem();
return profileItem != null ? profileItem.getProfile() : null;
}
/**
* Gets the selected RGBA expressions as array of 4 strings.
*
* @return the selected RGBA expressions, never null
*/
public String[] getRgbaExpressions() {
return new String[]{
getExpression(0),
getExpression(1),
getExpression(2),
getExpression(3),
};
}
public RGBImageProfile getRgbProfile() {
final String[] rgbaExpressions = getRgbaExpressions();
final Range[] ranges = new Range[3];
for (int i = 0; i < rangeComponents.length; i++) {
ranges[i] = rangeComponents[i].getRange();
}
String[] pattern = null;
String name = "";
final RGBImageProfile selectedProfile = getSelectedProfile();
if (selectedProfile != null) {
name = selectedProfile.getName();
pattern = selectedProfile.getPattern();
}
return new RGBImageProfile(name, rgbaExpressions, pattern, ranges);
}
public void addProfiles(RGBImageProfile[] profiles) {
for (RGBImageProfile profile : profiles) {
addNewProfile(profile);
}
setRgbaExpressionsFromSelectedProfile();
}
public RGBImageProfile findMatchingProfile(RGBImageProfile profile) {
// search in internal profiles first...
RGBImageProfile matchingProfile = findMatchingProfile(profile, true);
if (matchingProfile == null) {
// ...then in non-internal profiles
matchingProfile = findMatchingProfile(profile, false);
}
return matchingProfile;
}
public void selectProfile(RGBImageProfile profile) {
profileModel.setSelectedItem(new ProfileItem(profile));
}
public boolean showDialog(Window parent, String title, String helpId) {
ModalDialog modalDialog = new ModalDialog(parent, title, ModalDialog.ID_OK_CANCEL_HELP, helpId);
modalDialog.setContent(this);
final int status = modalDialog.show();
modalDialog.getJDialog().dispose();
return status == ModalDialog.ID_OK;
}
private String getExpression(int i) {
return ((JTextField) rgbaExprBoxes[i].getEditor().getEditorComponent()).getText().trim();
}
private void setExpression(int i, String expression) {
rgbaExprBoxes[i].setSelectedItem(expression);
}
private void performOpen() {
final SnapFileChooser snapFileChooser = new SnapFileChooser(getProfilesDir());
snapFileChooser.setFileFilter(
new SnapFileFilter("RGB-PROFILE", RGBImageProfile.FILENAME_EXTENSION, "RGB-Image Profile Files"));
final int status = snapFileChooser.showOpenDialog(this);
if (snapFileChooser.getSelectedFile() == null) {
return;
}
final File file = snapFileChooser.getSelectedFile();
lastDir = file.getParentFile();
if (status != SnapFileChooser.APPROVE_OPTION) {
return;
}
final RGBImageProfile profile;
try {
profile = RGBImageProfile.loadProfile(file);
String[] rgbaExpressions = profile.getRgbaExpressions();
// If profile was saved with a single product index reference, it may not match the current product index,
// so try to replace it. If it contains multiple indices, then keep them.
Set<Integer> productRefs = new HashSet<>();
for (String expression : rgbaExpressions) {
if (!StringUtils.isNullOrEmpty(expression)) {
if (expression.startsWith("$")) {
productRefs.add(Integer.parseInt(expression.substring(1, expression.indexOf('.'))));
} else {
productRefs.add(0);
}
}
}
boolean shouldReplace = productRefs.size() == 1 && !productRefs.contains(0);
for (int i = 0; i < rgbaExpressions.length; i++) {
if (shouldReplace) {
if (!StringUtils.isNullOrEmpty(rgbaExpressions[i])) {
rgbaExpressions[i] = rgbaExpressions[i].substring(rgbaExpressions[i].indexOf('.') + 1);
}
}
}
profile.setRgbaExpressions(rgbaExpressions);
} catch (IOException e) {
AbstractDialog.showErrorDialog(this,
String.format("Failed to open RGB-profile '%s':\n%s", file.getName(), e.getMessage()),
"Open RGB-Image Profile");
return;
}
if (profile == null) {
AbstractDialog.showErrorDialog(this,
String.format("Invalid RGB-Profile '%s'.", file.getName()),
"Open RGB-Image Profile");
return;
}
RGBImageProfileManager.getInstance().addProfile(profile);
if (product != null && !profile.isApplicableTo(product)) {
AbstractDialog.showErrorDialog(this,
String.format("The selected RGB-Profile '%s'\nis not applicable to the current product.",
profile.getName()),
"Open RGB-Image Profile");
return;
}
addNewProfile(profile);
}
private void performSaveAs() {
File file = promptForSaveFile();
if (file == null) {
return;
}
String[] rgbaExpressions = getRgbaExpressions();
Set<Integer> productRefs = new HashSet<>();
for (String expression : rgbaExpressions) {
if (!StringUtils.isNullOrEmpty(expression)) {
if (expression.startsWith("$")) {
productRefs.add(Integer.parseInt(expression.substring(1, expression.indexOf('.'))));
} else {
productRefs.add(0);
}
}
}
boolean shouldReplace = productRefs.size() == 1 && !productRefs.contains(0);
for (int i = 0; i < rgbaExpressions.length; i++) {
if (shouldReplace) {
rgbaExpressions[i] = rgbaExpressions[i].replace(BandArithmetic.getProductNodeNamePrefix(this.product), "");
}
}
final Range[] ranges = new Range[3];
for (int i = 0; i < 3; i++) {
ranges[i] = rangeComponents[i].getRange();
}
final RGBImageProfile profile = new RGBImageProfile(FileUtils.getFilenameWithoutExtension(file),
rgbaExpressions, null, ranges);
try {
profile.store(file);
} catch (IOException e) {
AbstractDialog.showErrorDialog(this,
"Failed to save RGB-profile '" + file.getName() + "':\n"
+ e.getMessage(),
"Open RGB-Image Profile");
return;
}
RGBImageProfileManager.getInstance().addProfile(profile);
addNewProfile(profile);
}
private File promptForSaveFile() {
final SnapFileChooser snapFileChooser = new SnapFileChooser(getProfilesDir());
snapFileChooser.setFileFilter(new SnapFileFilter("RGB-PROFILE", ".rgb", "RGB-Image Profile Files"));
File selectedFile;
while (true) {
final int status = snapFileChooser.showSaveDialog(this);
if (snapFileChooser.getSelectedFile() == null) {
selectedFile = null;
break;
}
selectedFile = snapFileChooser.getSelectedFile();
lastDir = selectedFile.getParentFile();
if (status != SnapFileChooser.APPROVE_OPTION) {
selectedFile = null;
break;
}
if (selectedFile.exists()) {
final int answer = JOptionPane.showConfirmDialog(RGBImageProfilePane.this,
"The file '" + selectedFile.getName()
+ "' already exists.\n" +
"So you really want to overwrite it?",
"Safe RGB-Profile As",
JOptionPane.YES_NO_CANCEL_OPTION);
if (answer == JOptionPane.CANCEL_OPTION) {
selectedFile = null;
break;
}
if (answer == JOptionPane.YES_OPTION) {
break;
}
} else {
break;
}
}
return selectedFile;
}
private void performDelete() {
final ProfileItem selectedProfileItem = getSelectedProfileItem();
if (selectedProfileItem != null && !selectedProfileItem.getProfile().isInternal()) {
profileModel.removeElement(selectedProfileItem);
}
}
private File getProfilesDir() {
if (lastDir != null) {
return lastDir;
} else {
return RGBImageProfileManager.getProfilesDir();
}
}
private void addNewProfile(RGBImageProfile profile) {
if (product != null && !profile.isApplicableTo(product)) {
return;
}
final ProfileItem profileItem = new ProfileItem(profile);
final int index = profileModel.getIndexOf(profileItem);
if (index == -1) {
profileModel.addElement(profileItem);
}
profileModel.setSelectedItem(profileItem);
}
private void setRgbaExpressionsFromSelectedProfile() {
settingRgbaExpressions = true;
try {
final ProfileItem profileItem = getSelectedProfileItem();
if (profileItem != null) {
final RGBImageProfile profile = profileItem.getProfile();
final String[] rgbaExpressions = profile.getRgbaExpressions();
for (int i = 0; i < rgbaExprBoxes.length; i++) {
setExpression(i, rgbaExpressions[i]);
}
final Range redMinMax = profile.getRedMinMax();
rangeComponents[0].set(redMinMax);
final Range greenMinMax = profile.getGreenMinMax();
rangeComponents[1].set(greenMinMax);
final Range blueMinMax = profile.getBlueMinMax();
rangeComponents[2].set(blueMinMax);
} else {
for (int i = 0; i < rgbaExprBoxes.length; i++) {
setExpression(i, "");
}
final Range invalidRange = new Range(Double.NaN, Double.NaN);
for (RangeComponents rangeComponent : rangeComponents) {
rangeComponent.set(invalidRange);
}
}
} finally {
settingRgbaExpressions = false;
}
updateUIState();
}
private ProfileItem getSelectedProfileItem() {
return (ProfileItem) profileBox.getSelectedItem();
}
private void addColorComponentRow(JPanel p3, final GridBagConstraints constraints, final int index) {
final JButton editorButton = new JButton("...");
editorButton.addActionListener(e -> invokeExpressionEditor(index));
final Dimension preferredSize = rgbaExprBoxes[index].getPreferredSize();
editorButton.setPreferredSize(new Dimension(preferredSize.height, preferredSize.height));
constraints.gridx = 0;
constraints.weightx = 0;
p3.add(new JLabel(getComponentName(index) + ": "), constraints);
constraints.gridx = 1;
constraints.weightx = 1;
p3.add(rgbaExprBoxes[index], constraints);
constraints.gridx = 2;
constraints.weightx = 0;
p3.add(editorButton, constraints);
}
private void addColorRangeComponentsRow(JPanel p3, final GridBagConstraints constraints, final int index) {
constraints.gridx = 0;
constraints.weightx = 0;
p3.add(new JLabel(), constraints);
final JPanel container = new JPanel();
final RangeComponents rangeComponent = rangeComponents[index];
final GridBagConstraints containerConstraints = new GridBagConstraints();
containerConstraints.gridy = 0;
containerConstraints.gridx = 0;
containerConstraints.weightx = 1;
container.add(rangeComponent.fixedRangeCheckBox, containerConstraints);
containerConstraints.gridx = 1;
container.add(rangeComponent.minText, containerConstraints);
containerConstraints.gridx = 2;
container.add(rangeComponent.minLabel, containerConstraints);
containerConstraints.gridx = 3;
container.add(rangeComponent.maxText, containerConstraints);
containerConstraints.gridx = 4;
container.add(rangeComponent.maxLabel, containerConstraints);
constraints.gridx = 1;
p3.add(container, constraints);
}
protected String getComponentName(final int index) {
return COLOR_COMP_NAMES[index];
}
private void invokeExpressionEditor(final int colorIndex) {
final Window window = SwingUtilities.getWindowAncestor(this);
final String title = "Edit " + getComponentName(colorIndex) + " Expression";
if (product != null) {
final ExpressionPane pane;
final Product[] products = getCompatibleProducts(product, openedProducts);
pane = ProductExpressionPane.createGeneralExpressionPane(products, product, preferences);
pane.setCode(getExpression(colorIndex));
int status = pane.showModalDialog(window, title);
if (status == ModalDialog.ID_OK) {
setExpression(colorIndex, pane.getCode());
}
} else {
final JTextArea textArea = new JTextArea(8, 48);
textArea.setFont(EXPRESSION_FONT);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
textArea.setText(getExpression(colorIndex));
final ModalDialog modalDialog = new ModalDialog(window, title, ModalDialog.ID_OK_CANCEL, "");
final JPanel panel = new JPanel(new BorderLayout(2, 2));
panel.add(new JLabel("Expression:"), BorderLayout.NORTH);
panel.add(new JScrollPane(textArea), BorderLayout.CENTER);
modalDialog.setContent(panel);
final int status = modalDialog.show();
if (status == ModalDialog.ID_OK) {
setExpression(colorIndex, textArea.getText());
}
}
}
private static Product[] getCompatibleProducts(final Product targetProduct, final Product[] productsList) {
final List<Product> compatibleProducts = new ArrayList<>(1);
compatibleProducts.add(targetProduct);
final float geolocationEps = 180;
Debug.trace("BandMathsDialog.geolocationEps = " + geolocationEps);
Debug.trace("BandMathsDialog.getCompatibleProducts:");
Debug.trace(" comparing: " + targetProduct.getName());
if (productsList != null) {
for (final Product product : productsList) {
if (targetProduct != product) {
Debug.trace(" with: " + product.getDisplayName());
final boolean isCompatibleProduct = targetProduct.isCompatibleProduct(product, geolocationEps);
Debug.trace(" result: " + isCompatibleProduct);
if (isCompatibleProduct) {
compatibleProducts.add(product);
}
}
}
}
return compatibleProducts.toArray(new Product[compatibleProducts.size()]);
}
private JComboBox createRgbaBox(String[] suggestions) {
final JComboBox<String> comboBox = new JComboBox<>(suggestions);
setPreferredWidth(comboBox, 320);
comboBox.setEditable(true);
final ComboBoxEditor editor = comboBox.getEditor();
final JTextField textField = (JTextField) editor.getEditorComponent();
textField.setFont(EXPRESSION_FONT);
textField.getDocument().addDocumentListener(new DocumentListener() {
public void insertUpdate(DocumentEvent e) {
onRgbaExpressionChanged();
}
public void removeUpdate(DocumentEvent e) {
onRgbaExpressionChanged();
}
public void changedUpdate(DocumentEvent e) {
onRgbaExpressionChanged();
}
});
return comboBox;
}
private void onRgbaExpressionChanged() {
if (settingRgbaExpressions) {
return;
}
final ProfileItem profileItem = getSelectedProfileItem();
if (profileItem != null) {
if (isSelectedProfileModified()) {
profileBox.revalidate();
profileBox.repaint();
}
}
final RGBImageProfile selectedProfile = getSelectedProfile();
final String[] rgbaExpressions;
if (selectedProfile != null) {
rgbaExpressions = selectedProfile.getRgbaExpressions();
} else {
rgbaExpressions = getRgbaExpressions();
}
final int defaultProductIndex = ArrayUtils.getElementIndex(product, openedProducts);
try {
if (!BandArithmetic.areRastersEqualInSize(openedProducts,
defaultProductIndex, rgbaExpressions)) {
referencedRastersAreCompatibleLabel.setText("Referenced rasters are not of the same size");
referencedRastersAreCompatibleLabel.setForeground(warnMsgColor);
} else {
referencedRastersAreCompatibleLabel.setText("Expressions are valid");
referencedRastersAreCompatibleLabel.setForeground(okMsgColor);
}
} catch (ParseException e) {
referencedRastersAreCompatibleLabel.setText("Expressions are invalid");
referencedRastersAreCompatibleLabel.setForeground(warnMsgColor);
}
updateUIState();
}
private boolean isSelectedProfileModified() {
final ProfileItem profileItem = getSelectedProfileItem();
final String[] profileRgbaExpressions = profileItem.getProfile().getRgbaExpressions();
final String[] userRgbaExpressions = getRgbaExpressions();
for (int i = 0; i < profileRgbaExpressions.length; i++) {
final String userRgbaExpression = userRgbaExpressions[i];
final String profileRgbaExpression = profileRgbaExpressions[i];
if (!profileRgbaExpression.equals(userRgbaExpression)) {
return true;
}
}
return false;
}
private void updateUIState() {
final ProfileItem profileItem = getSelectedProfileItem();
if (profileItem != null) {
saveAsAction.setEnabled(true);
deleteAction.setEnabled(!profileItem.getProfile().isInternal());
} else {
saveAsAction.setEnabled(isAtLeastOneColorExpressionSet());
deleteAction.setEnabled(false);
}
}
private boolean isAtLeastOneColorExpressionSet() {
final JComboBox[] rgbaExprBoxes = this.rgbaExprBoxes;
for (int i = 0; i < 3; i++) {
JComboBox rgbaExprBox = rgbaExprBoxes[i];
final Object selectedItem = rgbaExprBox.getSelectedItem();
if (selectedItem != null && !selectedItem.toString().trim().equals("")) {
return true;
}
}
return false;
}
private void setPreferredWidth(final JComboBox comboBox, final int width) {
final Dimension preferredSize = comboBox.getPreferredSize();
comboBox.setPreferredSize(new Dimension(width, preferredSize.height));
}
public static RGBImageProfile findProfileForProductPattern(RGBImageProfile[] rgbImageProfiles, Product product) {
if (rgbImageProfiles.length == 0) {
return null;
}
String productType = product.getProductType();
String productName = product.getName();
String productDesc = product.getDescription();
RGBImageProfile bestProfile = rgbImageProfiles[0];
int bestMatchScore = 0;
for (RGBImageProfile rgbImageProfile : rgbImageProfiles) {
String[] pattern = rgbImageProfile.getPattern();
if (pattern == null) {
continue;
}
boolean productTypeMatches = matches(productType, pattern[0]);
boolean productNameMatches = matches(productName, pattern[1]);
boolean productDescMatches = matches(productDesc, pattern[2]);
int currentMatchScore = (productTypeMatches ? 100 : 0) + (productNameMatches ? 10 : 0) + (productDescMatches ? 1 : 0);
if (currentMatchScore > bestMatchScore) {
bestProfile = rgbImageProfile;
bestMatchScore = currentMatchScore;
}
}
return bestProfile;
}
private static boolean matches(String textValue, String pattern) {
return textValue != null
&& pattern != null
&& textValue.matches(pattern.replace("*", ".*").replace("?", "."));
}
private class ProfileItem {
private final RGBImageProfile profile;
public ProfileItem(RGBImageProfile profile) {
this.profile = profile;
}
public RGBImageProfile getProfile() {
return profile;
}
@Override
public int hashCode() {
return getProfile().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof ProfileItem) {
ProfileItem profileItem = (ProfileItem) obj;
return getProfile().equals(profileItem.getProfile());
}
return false;
}
@Override
public String toString() {
String name = profile.getName().replace('_', ' ');
if (getSelectedProfileItem().equals(this) && isSelectedProfileModified()) {
name += " (modified)";
}
return name;
}
}
private class ProfileSelectionHandler implements ItemListener {
public void itemStateChanged(ItemEvent e) {
setRgbaExpressionsFromSelectedProfile();
}
}
public RGBImageProfile findMatchingProfile(RGBImageProfile profile, boolean internal) {
final int size = profileModel.getSize();
for (int i = 0; i < size; i++) {
final ProfileItem item = profileModel.getElementAt(i);
final RGBImageProfile knownProfile = item.getProfile();
if (knownProfile.isInternal() == internal
&& Arrays.equals(profile.getRgbExpressions(), knownProfile.getRgbExpressions())) {
return knownProfile;
}
}
return null;
}
static class RangeComponents {
final JCheckBox fixedRangeCheckBox;
final JLabel minLabel;
final JTextField minText;
final JLabel maxLabel;
final JTextField maxText;
RangeComponents() {
fixedRangeCheckBox = new JCheckBox("fixed range");
fixedRangeCheckBox.addActionListener(e -> this.enableMinMax(fixedRangeCheckBox.isSelected()));
minText = new JTextField(12);
minLabel = new JLabel("min");
maxText = new JTextField(12);
maxLabel = new JLabel("max");
fixedRangeCheckBox.setSelected(false);
enableMinMax(false);
}
void enableMinMax(boolean enable) {
minLabel.setEnabled(enable);
minText.setEnabled(enable);
maxLabel.setEnabled(enable);
maxText.setEnabled(enable);
}
void set(Range range) {
final double min = range.getMin();
final double max = range.getMax();
boolean enable = false;
if (!Double.isNaN(min)) {
minText.setText(Double.toString(min));
enable = true;
} else {
minText.setText("");
}
if (!Double.isNaN(max)) {
maxText.setText(Double.toString(max));
enable = true;
} else {
maxText.setText("");
}
enableMinMax(enable);
fixedRangeCheckBox.setSelected(enable);
}
Range getRange() {
double min = Double.NaN;
double max = Double.NaN;
if (fixedRangeCheckBox.isSelected()) {
try {
final String minValueString = minText.getText();
if (StringUtils.isNotNullAndNotEmpty(minValueString)) {
min = Double.parseDouble(minValueString.trim());
}
final String maxValueString = maxText.getText();
if (StringUtils.isNotNullAndNotEmpty(maxValueString)) {
max = Double.parseDouble(maxValueString.trim());
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Invalid input - minimum and maximum must be floating point values");
}
}
return new Range(min, max);
}
}
}
| 35,630 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ToolButtonFactory.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/tool/ToolButtonFactory.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.tool;
import com.bc.ceres.swing.BrightBlueImageFilter;
import org.esa.snap.ui.UIUtils;
import javax.swing.AbstractButton;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JToggleButton;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.FilteredImageSource;
import java.util.EventObject;
/**
* The {@code ToolButtonFactory} can be used to create tool bar buttons which have a consistent look and feel.
*
* @author Norman Fomferra
* @version $Revision$ $Date$
*/
public class ToolButtonFactory {
public static final Color SELECTED_BORDER_COLOR = new Color(8, 36, 107);
private static final Color SELECTED_BACKGROUND_COLOR = new Color(130, 146, 185);
private static final Color ROLLOVER_BACKGROUND_COLOR = new Color(181, 190, 214);
private static final int BUTTON_MIN_SIZE = 16;
private static ImageIcon _separatorIcon;
public static AbstractButton createButton(Icon icon, boolean toggle) {
AbstractButton button = createButton(toggle);
button.setIcon(icon);
configure(button);
return button;
}
public static AbstractButton createButton(Action action, boolean toggle) {
AbstractButton button = createButton(toggle);
setButtonName(button, action);
button.setAction(action);
configure(button);
return button;
}
private static AbstractButton createButton(boolean toggle) {
if (toggle) {
return new JToggleButton();
} else {
return new JButton();
}
}
private static void configure(AbstractButton button) {
RolloverButtonEventListener l = new RolloverButtonEventListener();
button.addMouseListener(l);
button.addItemListener(l);
if (button.getAction() != null) {
if (button.getIcon() != null) {
button.putClientProperty("hideActionText", Boolean.TRUE);
}
Object largeIcon = button.getAction().getValue("_largeIcon");
if (largeIcon instanceof Icon) {
button.setIcon((Icon) largeIcon);
}
}
Icon icon = button.getIcon();
int minWidth = BUTTON_MIN_SIZE;
int minHeight = BUTTON_MIN_SIZE;
if (icon != null) {
button.setText(null);
minWidth = Math.max(icon.getIconWidth(), BUTTON_MIN_SIZE);
minHeight = Math.max(icon.getIconHeight(), BUTTON_MIN_SIZE);
if (icon instanceof ImageIcon) {
button.setRolloverIcon(createRolloverIcon((ImageIcon) icon));
}
} else {
button.setText("[?]");
}
final int space = 3;
Dimension prefSize = new Dimension(minWidth + space, minHeight + space);
Dimension minSize = new Dimension(minWidth, minHeight);
Dimension maxSize = new Dimension(minWidth + space, minHeight + space);
button.setPreferredSize(prefSize);
button.setMaximumSize(maxSize);
button.setMinimumSize(minSize);
}
public static JComponent createToolBarSeparator() {
if (_separatorIcon == null) {
_separatorIcon = UIUtils.loadImageIcon("icons/Separator24.gif");
}
return new JLabel(_separatorIcon);
}
public static ImageIcon createRolloverIcon(ImageIcon imageIcon) {
return new ImageIcon(createRolloverImage(imageIcon.getImage()));
}
private static Image createRolloverImage(Image image) {
return Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(),
new BrightBlueImageFilter()));
}
private static class RolloverButtonEventListener extends MouseAdapter implements ItemListener {
public RolloverButtonEventListener() {
}
public AbstractButton getButton(EventObject e) {
return (AbstractButton) e.getSource();
}
/**
* Invoked when a mouse button has been pressed on a component.
*/
@Override
public void mousePressed(MouseEvent e) {
setSelectedState(getButton(e));
}
/**
* Invoked when a mouse button has been released on a component.
*/
@Override
public void mouseReleased(MouseEvent e) {
setDefaultState(getButton(e));
}
/**
* Invoked when the mouse enters a component.
*/
@Override
public void mouseEntered(MouseEvent e) {
setRolloverStateState(getButton(e));
}
/**
* Invoked when the mouse exits a component.
*/
@Override
public void mouseExited(MouseEvent e) {
setDefaultState(getButton(e));
}
private void setDefaultState(AbstractButton b) {
if (b.isSelected()) {
setSelectedState(b);
} else {
setNormalState(b);
}
}
private void setNormalState(AbstractButton b) {
b.setBorderPainted(false);
// b.setForeground(getDefaultForeground());
b.setBackground(getDefaultBackground());
}
private void setSelectedState(AbstractButton b) {
if (b.isEnabled()) {
b.setBorderPainted(true);
b.setBackground(SELECTED_BACKGROUND_COLOR);
} else {
b.setBorderPainted(false);
b.setBackground(getDefaultBackground().darker());
}
}
private void setRolloverStateState(AbstractButton b) {
if (b.isEnabled()) {
b.setBorderPainted(true);
b.setBackground(ROLLOVER_BACKGROUND_COLOR);
}
}
/**
* Invoked when an item has been selected or deselected. The code written for this method performs the
* operations that need to occur when an item is selected (or deselected).
*/
public void itemStateChanged(ItemEvent e) {
setDefaultState((AbstractButton) e.getSource());
}
private Color getDefaultBackground() {
Color color = null;
String[] keys = new String[]{"Button.background", "Label.background", "Panel.background"};
for (String key : keys) {
color = UIManager.getLookAndFeel().getDefaults().getColor(key);
}
if (color == null) {
color = new Color(238, 238, 238);
}
return color;
}
}
private static void setButtonName(AbstractButton button, Action action) {
if (button.getName() == null) {
String name = null;
Object value = action.getValue(Action.ACTION_COMMAND_KEY);
if (value != null) {
name = value.toString();
} else {
value = action.getValue(Action.NAME);
if (value != null) {
name = value.toString();
}
}
if (name != null) {
button.setName(name);
}
}
}
}
| 8,223 | Java | .java | senbox-org/snap-desktop | 132 | 60 | 9 | 2014-10-30T11:53:56Z | 2024-05-07T21:09:33Z |
ColorTableCellRenderer.java | /FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-ui/src/main/java/org/esa/snap/ui/color/ColorTableCellRenderer.java | package org.esa.snap.ui.color;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;
import java.awt.Color;
import java.awt.Component;
/**
* A table cell renderer for color values.
*
* @author Norman Fomferra
* @since SNAP 2.0
*/
public class ColorTableCellRenderer implements TableCellRenderer {
private ColorLabel colorLabel;
public ColorTableCellRenderer() {
this(new ColorLabel());
}
public ColorTableCellRenderer(ColorLabel colorLabel) {
this.colorLabel = colorLabel;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
colorLabel.setHighlighted(isSelected);
colorLabel.setColor((Color) value);
return colorLabel;
}
}
| 818 | 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.