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
package-info.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-dem-ui/src/main/java/org/esa/snap/dem/docs/package-info.java
@HelpSetRegistration(helpSet = "help.hs", position = 5300) package org.esa.snap.dem.docs; import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
152
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WriterPlugInExportProductAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gdal-writer-ui/src/main/java/org/esa/snap/gdal/writer/ui/WriterPlugInExportProductAction.java
package org.esa.snap.gdal.writer.ui; import org.esa.lib.gdal.activator.GDALDriverInfo; import org.esa.snap.dataio.gdal.GDALLoader; import org.esa.snap.dataio.gdal.drivers.GDAL; import org.esa.snap.dataio.gdal.writer.plugins.AbstractDriverProductWriterPlugIn; import org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.core.dataio.ProductWriterPlugIn; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.StringUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.ExportProductAction; import org.esa.snap.rcp.actions.file.ProductFileChooser; import org.esa.snap.rcp.actions.file.ProductOpener; import org.esa.snap.rcp.actions.file.WriteProductOperation; import org.esa.snap.rcp.util.Dialogs; import org.netbeans.api.progress.ProgressUtils; import javax.swing.*; import javax.swing.filechooser.FileFilter; import java.awt.event.ActionEvent; import java.io.File; import java.lang.reflect.Method; import java.text.MessageFormat; import java.util.*; import java.util.prefs.Preferences; /** * @author Jean Coravu */ public class WriterPlugInExportProductAction extends ExportProductAction { private String enteredFileName; WriterPlugInExportProductAction() { super(); } @Override public boolean isEnabled() { return (SnapApp.getDefault().getAppContext().getSelectedProduct() != null); } @Override public void actionPerformed(ActionEvent event) { Product product = SnapApp.getDefault().getAppContext().getSelectedProduct(); setProduct(product); exportProduct(product); } private Boolean exportProduct(Product product) { List<ExportDriversFileFilter> filters = new ArrayList<>(); Iterator<ProductWriterPlugIn> it = ProductIOPlugInManager.getInstance().getAllWriterPlugIns(); while (it.hasNext()) { ProductWriterPlugIn productWriterPlugIn = it.next(); if (productWriterPlugIn instanceof AbstractDriverProductWriterPlugIn) { GDALDriverInfo writerDriver = ((AbstractDriverProductWriterPlugIn)productWriterPlugIn).getWriterDriver(); String description = writerDriver.getDriverDisplayName() + " (*" + writerDriver.getExtensionName() + ")"; filters.add(new ExportDriversFileFilter(description, writerDriver)); } } if (filters.size() > 1) { Comparator<ExportDriversFileFilter> comparator = (item1, item2) -> item1.getDescription().compareToIgnoreCase(item2.getDescription()); filters.sort(comparator); } ProductFileChooser fileChooser = buildFileChooserDialog(product, false, null); fileChooser.addPropertyChangeListener(JFileChooser.FILE_FILTER_CHANGED_PROPERTY, event -> { ExportDriversFileFilter selectedFileFilter = (ExportDriversFileFilter) fileChooser.getFileFilter(); String fileName = this.enteredFileName; if (StringUtils.isNullOrEmpty(fileName)) { fileName = selectedFileFilter.getDriverInfo().getDriverDisplayName(); } else { int index = fileName.lastIndexOf("."); if (index >= 0) { fileName = fileName.substring(0, index); } } fileName += selectedFileFilter.getDriverInfo().getExtensionName(); try { Method setFileNameMethod = fileChooser.getUI().getClass().getMethod("setFileName", String.class); setFileNameMethod.invoke(fileChooser.getUI(), fileName); } catch (Exception e) { throw new IllegalStateException(e); } }); fileChooser.addPropertyChangeListener(JFileChooser.SELECTED_FILE_CHANGED_PROPERTY, event -> { if (event.getOldValue() != null && event.getNewValue() == null) { try { Method getFileName = fileChooser.getUI().getClass().getMethod("getFileName"); this.enteredFileName = (String) getFileName.invoke(fileChooser.getUI()); } catch (Exception e) { throw new IllegalStateException(e); } } }); for (ExportDriversFileFilter filter : filters) { fileChooser.addChoosableFileFilter(filter); } int returnVal = fileChooser.showSaveDialog(SnapApp.getDefault().getMainFrame()); if (returnVal != JFileChooser.APPROVE_OPTION || fileChooser.getSelectedFile() == null) { return false; // cancelled } File newFile = fileChooser.getSelectedFile(); ExportDriversFileFilter selectedFileFilter = (ExportDriversFileFilter)fileChooser.getFileFilter(); if (!selectedFileFilter.accept(newFile)) { String message = MessageFormat.format("The extension of the selected file\n" + "''{0}''\n" + "does not match the selected file type.\n" + "Please set the file extension according to the selected file type.", newFile.getPath()); Dialogs.showWarning(getDisplayName(), message, null); return false; } if (!canWriteSelectedFile(newFile)) { return false; } Product exportProduct = fileChooser.getSubsetProduct() != null ? fileChooser.getSubsetProduct() : product; Band sourceBand = exportProduct.getBandAt(0); int gdalDataType = GDALLoader.getInstance().getGDALDataType(sourceBand.getDataType()); GDALDriverInfo driverInfo = selectedFileFilter.getDriverInfo(); if (!driverInfo.canExportProduct(gdalDataType)) { String gdalDataTypeName = GDAL.getDataTypeName(gdalDataType); String message = MessageFormat.format("The GDAL driver ''{0}'' does not support the data type ''{1}'' to create a new product." + "\nThe available types are ''{2}''." , driverInfo.getDriverDisplayName(), gdalDataTypeName, driverInfo.getCreationDataTypes()); Dialogs.showWarning(getDisplayName(), message, null); return false; } String formatName = selectedFileFilter.getDriverInfo().getWriterPluginFormatName(); return exportProduct(exportProduct, newFile, formatName); } private boolean canWriteSelectedFile(File newFile) { if (newFile.isFile() && !newFile.canWrite()) { Dialogs.showWarning(getDisplayName(), MessageFormat.format("The product\n" + "''{0}''\n" + "exists and cannot be overwritten, because it is read only.\n" + "Please choose another file or remove the write protection.", newFile.getPath()), null); return false; } return true; } private Boolean exportProduct(Product exportProduct, File newFile, String formatName) { SnapApp.getDefault().setStatusBarMessage(MessageFormat.format("Exporting product ''{0}'' to {1}...", exportProduct.getDisplayName(), newFile)); WriteProductOperation operation = new WriteProductOperation(exportProduct, newFile, formatName, false); ProgressUtils.runOffEventThreadWithProgressDialog(operation, getDisplayName(), operation.getProgressHandle(), true, 50, 1000); SnapApp.getDefault().setStatusBarMessage(""); return operation.getStatus(); } private ProductFileChooser buildFileChooserDialog(Product product, boolean useSubset, FileFilter filter) { Preferences preferences = SnapApp.getDefault().getPreferences(); ProductFileChooser fc = new ProductFileChooser(new File(preferences.get(ProductOpener.PREFERENCES_KEY_LAST_PRODUCT_DIR, "."))); fc.setDialogType(JFileChooser.SAVE_DIALOG); fc.setSubsetEnabled(useSubset); fc.setAdvancedEnabled(false); if (filter != null) { fc.addChoosableFileFilter(filter); } fc.setProductToExport(product); return fc; } }
8,305
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GDALMenuActionRegister.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gdal-writer-ui/src/main/java/org/esa/snap/gdal/writer/ui/GDALMenuActionRegister.java
package org.esa.snap.gdal.writer.ui; import org.esa.lib.gdal.activator.GDALInstallInfo; import org.esa.lib.gdal.activator.GDALWriterPlugInListener; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.modules.OnStart; import javax.swing.*; import java.io.IOException; import java.util.Arrays; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Jean Coravu */ @OnStart public class GDALMenuActionRegister implements Runnable, GDALWriterPlugInListener { private static final Logger logger = Logger.getLogger(GDALMenuActionRegister.class.getName()); public GDALMenuActionRegister() { } @Override public void run() { GDALInstallInfo.INSTANCE.setListener(this); } @Override public void writeDriversSuccessfullyInstalled() { try { String actionDisplayName = "GDAL"; AbstractAction action = new WriterPlugInExportProductAction(); action.putValue(Action.NAME, actionDisplayName); action.putValue("displayName", actionDisplayName); String menuPath = "Menu/File/Export"; String category = "GDAL"; registerAction(category, menuPath, action); } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } } private static void registerAction(String category, String menuPath, Action action) throws IOException { String actionName = (String)action.getValue(Action.NAME); // add update action String originalFile = "Actions/" + category + "/" + actionName + ".instance"; FileObject in = getFolderAt("Actions/" + category); FileObject obj = in.getFileObject(actionName, "instance"); if (obj == null) { obj = in.createData(actionName, "instance"); } obj.setAttribute("instanceCreate", action); obj.setAttribute("instanceClass", action.getClass().getName()); // add update menu in = getFolderAt(menuPath); obj = in.getFileObject(actionName, "shadow"); // create if missing if (obj == null) { obj = in.createData(actionName, "shadow"); obj.setAttribute("originalFile", originalFile); } } private static FileObject getFolderAt(String inputPath) throws IOException { String parts[] = inputPath.split("/"); FileObject existing = FileUtil.getConfigFile(inputPath); if (existing != null) return existing; FileObject base = FileUtil.getConfigFile(parts[0]); if (base == null) { return null; } for (int i = 1; i < parts.length; i++) { String path = joinPath("/", Arrays.copyOfRange(parts, 0, i+1)); FileObject next = FileUtil.getConfigFile(path); if (next == null) { next = base.createFolder(parts[i]); } base = next; } return FileUtil.getConfigFile(inputPath); } private static String joinPath(String separator, String parts[]) { StringBuilder str = new StringBuilder(); for (int i = 0; i < parts.length; i++) { if (i > 0) { str.append(separator); } str.append(parts[i].toString()); } return str.toString(); } }
3,392
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ExportDriversFileFilter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-gdal-writer-ui/src/main/java/org/esa/snap/gdal/writer/ui/ExportDriversFileFilter.java
package org.esa.snap.gdal.writer.ui; import org.esa.lib.gdal.activator.GDALDriverInfo; import org.esa.snap.core.util.StringUtils; import javax.swing.filechooser.FileFilter; import java.io.File; /** * @author Jean Coravu */ public class ExportDriversFileFilter extends FileFilter { private final String description; private final GDALDriverInfo driverInfo; public ExportDriversFileFilter(String description, GDALDriverInfo driverInfo) { this.description = description; this.driverInfo = driverInfo; } @Override public boolean accept(File fileToAccept) { if (fileToAccept.isDirectory()) { return true; } return StringUtils.endsWithIgnoreCase(fileToAccept.getName(), this.driverInfo.getExtensionName()); } @Override public String getDescription() { return this.description; } public GDALDriverInfo getDriverInfo() { return driverInfo; } }
961
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SnapAppTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-application/src/test/java/org/esa/snap/gui/SnapAppTest.java
package org.esa.snap.gui; import com.bc.ceres.core.ResourceLocator; import junit.framework.Test; import org.netbeans.junit.NbModuleSuite; import org.netbeans.junit.NbTestCase; import org.openide.modules.ModuleInfo; import org.openide.util.Lookup; import java.io.IOException; import java.nio.file.Path; import java.util.Collection; import java.util.Locale; import java.util.logging.Level; public class SnapAppTest extends NbTestCase { static { Locale.setDefault(Locale.ENGLISH); } public static Test suite() { return NbModuleSuite.createConfiguration(SnapAppTest.class). gui(true). failOnMessage(Level.WARNING). // works at least in RELEASE71 failOnException(Level.INFO). enableClasspathModules(false). clusters(".*"). suite(); // RELEASE71+, else use NbModuleSuite.create(NbModuleSuite.createConfiguration(...)) } public SnapAppTest(String n) { super(n); } public void testApplication() throws IOException { // pass if there are merely no warnings/exceptions /* Example of using Jelly Tools (additional test dependencies required) with gui(true): new ActionNoBlock("Help|About", null).performMenu(); new NbDialogOperator("About").closeByButton(); */ Collection<? extends ModuleInfo> modules = Lookup.getDefault().lookupAll(ModuleInfo.class); for (ModuleInfo module : modules) { System.out.println("module.getDisplayName() = " + module.getDisplayName()); } /* ClassLoader globalClassLoader = Lookup.getDefault().lookup(ClassLoader.class); System.out.println("globalClassLoader = " + globalClassLoader); Enumeration<URL> resources = globalClassLoader.getResources("/META-INF/MANIFEST.MF"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); System.out.println("url = " + url); } */ System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); Collection<Path> resources = ResourceLocator.getResources("META-INF/MANIFEST.MF"); for (Path path : resources) { System.out.println("path = " + path.toUri()); } System.out.println("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<"); } }
2,363
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MainTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-main/src/test/java/org/esa/snap/main/MainTest.java
package org.esa.snap.main; import org.junit.Test; import java.nio.file.Path; import java.nio.file.Paths; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; /** * Must be called from a NetBeans native platform executable. */ public class MainTest { @Test public void testMainWithArgs() throws Exception { assertNull(System.getProperty("snap.home")); String oldVal1 = System.setProperty("netbeans.home", "a/b/c/platform"); try { try { Main.main(new String[]{"--branding", "snap", "--locale", "en_GB"}); } catch (ClassNotFoundException e) { // ok } assertEquals(Paths.get("a/b/c"), Paths.get(System.getProperty("snap.home"))); } finally { if (oldVal1 != null) { System.setProperty("netbeans.home", oldVal1); } else { System.clearProperty("netbeans.home"); } System.clearProperty("snap.home"); } } }
1,054
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
Main.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-main/src/main/java/org/esa/snap/main/Main.java
package org.esa.snap.main; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.Properties; /** * Custom SNAP main class for the NetBeans Platform to be called from a NetBeans command-line executable. * <p> * To activate it, add * {@code -J-Dnetbeans.mainclass=org.esa.snap.main.Main} * to {@code default_options} parameter provided in the file {@code $INSTALL_DIR/etc/snap.config}. * <p> * The intention of this class is to initialise {@code snap.home} which will be set to the value of the * NetBeans Platform system property {@code netbeans.home}, which is expected to be already set by the * NetBeans Platform command-line. * <p> * See * <ul> * <li><a href="http://wiki.netbeans.org/DevFaqPlatformAppAuthStrategies">DevFaqPlatformAppAuthStrategies</a></li> * <li><a href="http://wiki.netbeans.org/FaqNetbeansConf">FaqNetbeansConf</a></li> * <li><a href="http://wiki.netbeans.org/FaqStartupParameters">FaqStartupParameters</a> in the NetBeans wiki.</li> * </ul> * * @author Norman Fomferra * @since SNAP 2 */ public class Main { private static final String NB_MAIN_CLASS = "org.netbeans.core.startup.Main"; /** * A custom main entry point called from a NetBeans Platform command-line. * * @param args NetBeans Platform command-line arguments */ public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { System.setProperty("snap.home", Paths.get(getPropertySafe("netbeans.home")).getParent().toString()); if (Boolean.getBoolean("snap.debug")) { dumpEnv(args); } runNetBeans(args, NB_MAIN_CLASS); } private static String getPropertySafe(String key) { String value = System.getProperty(key); if (value == null) { throw new IllegalStateException(String.format("Expecting system property '%s' to be set", key)); } return value; } private static void dumpEnv(String[] args) { System.out.println(); System.out.println("Class: " + Main.class.getName()); System.out.println(); System.out.println("Arguments:"); for (int i = 0; i < args.length; i++) { System.out.printf("args[%d] = \"%s\"%n", i, args[i]); } System.out.println(); System.out.println("System properties:"); Properties properties = System.getProperties(); ArrayList<String> propertyNameList = new ArrayList<>(properties.stringPropertyNames()); Collections.sort(propertyNameList); for (String name : propertyNameList) { String value = properties.getProperty(name); System.out.println(name + " = " + value); } System.out.flush(); System.out.println(); System.out.println("Stack trace (this is no error!): "); new Exception().printStackTrace(System.out); System.out.println(); System.out.flush(); } private static void runNetBeans(String[] args, String mainClassName) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); Class<?> nbMainClass = classLoader.loadClass(mainClassName); Method nbMainMethod = nbMainClass.getDeclaredMethod("main", String[].class); nbMainMethod.invoke(null, new Object[]{args}); } }
3,608
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LineSplitBySeparatorTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-smart-configurator-ui/src/test/java/org/esa/snap/smart/configurator/ui/LineSplitBySeparatorTest.java
package org.esa.snap.smart.configurator.ui; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author Nicolas Ducoin */ public class LineSplitBySeparatorTest { @Test public void testBlankSpaces() { String stringWithBlanks = "a blank \"Str ing\" with \" 's p a c e s'"; String multiLineString = LineSplitTextEditDialog.toMultiLine(stringWithBlanks, " "); String[] linesArray = multiLineString.split(System.lineSeparator()); assertEquals (5, linesArray.length); } @Test public void testCommas() { String stringWithBlanks = "a,blank,\"Str,ing\",with,\",,'s,p,a,c,e,s'"; String multiLineString = LineSplitTextEditDialog.toMultiLine(stringWithBlanks, ","); String[] linesArray = multiLineString.split(System.lineSeparator()); assertEquals (5, linesArray.length); } }
886
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LineSplitTextEditDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-smart-configurator-ui/src/main/java/org/esa/snap/smart/configurator/ui/LineSplitTextEditDialog.java
/* * Copyright (C) 2015 CS SI * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.smart.configurator.ui; import org.esa.snap.ui.ModalDialog; import javax.swing.JScrollPane; import java.awt.Window; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * Dialog to edit a line with multiple separators in a text area showing one line per peace of string. * It manages double quotes, meaning for the string "A B \"C D\"" with space as separator it shows in the dialog: * A * B * C D * * @author Nicolas Ducoin */ public class LineSplitTextEditDialog extends ModalDialog { private javax.swing.JTextArea textArea; private String separator; private String textWithSeparators; /** * Creates new form LineSplitTextEditDialog * * @param parent the parent window * @param textWithSeparators the text to be edited or displayed * @param separator the separator for this text, the text will get split using this * @param title the title of the dialog */ public LineSplitTextEditDialog( Window parent, String textWithSeparators, String separator, String title) { this(parent, textWithSeparators, separator, title, true); } /** * Creates new form LineSplitTextEditDialog * * @param parent the parent window * @param textWithSeparators the text to be edited or displayed * @param separator the separator for this text, the text will get split using this * @param title the title of the dialog * @param canEdit if false, the text won't be editable */ public LineSplitTextEditDialog( Window parent, String textWithSeparators, String separator, String title, boolean canEdit) { super(parent, title, ID_OK_CANCEL, null); this.textWithSeparators = textWithSeparators; this.separator = separator; initComponents(); String multiLineText = toMultiLine(textWithSeparators, separator); textArea.setText(multiLineText); if(!canEdit) { textArea.setEditable(false); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") private void initComponents() { JScrollPane textAreaScrollPane = new javax.swing.JScrollPane(); textArea = new javax.swing.JTextArea(); textArea.setColumns(20); textArea.setRows(10); textAreaScrollPane.setViewportView(textArea); setContent(textAreaScrollPane); } @Override protected void onOK() { String multiLineString = textArea.getText(); textWithSeparators = toMonoLine(multiLineString); super.onOK(); } /** * * @return the text with separator, it can be the text passed in the contructor (if cancel was pressed) * or a modified text, comming from the multi-line editing window */ public String getTextWithSeparators() { return textWithSeparators; } static String toMultiLine(String monoLineString, String separator) { StringBuilder stringBuilder = new StringBuilder(); Pattern regex = Pattern.compile("[^" + separator + "\"']+|\"[^\"]*\"|'[^']*'"); Matcher regexMatcher = regex.matcher(monoLineString); while (regexMatcher.find()) { stringBuilder.append(regexMatcher.group()); stringBuilder.append(System.lineSeparator()); } return stringBuilder.toString(); } String toMonoLine(String multiLineString) { StringBuilder builder = new StringBuilder(); String[] linesOfText = multiLineString.split(System.lineSeparator()); if(linesOfText.length > 0) { builder.append(linesOfText[0]); for (int i=1 ; i<linesOfText.length ; i++) { builder.append(separator); builder.append(linesOfText[i]); } } return builder.toString(); } }
4,816
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PerformancePanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-smart-configurator-ui/src/main/java/org/esa/snap/smart/configurator/ui/PerformancePanel.java
/* * Copyright (C) 2015 CS SI * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.smart.configurator.ui; import com.bc.ceres.core.ServiceRegistry; import com.bc.ceres.core.ServiceRegistryManager; import org.apache.commons.lang3.StringUtils; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.util.ServiceLoader; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.smart.configurator.Benchmark; import org.esa.snap.smart.configurator.BenchmarkOperatorProvider; import org.esa.snap.smart.configurator.BenchmarkSingleCalculus; import org.esa.snap.smart.configurator.ConfigurationOptimizer; import org.esa.snap.smart.configurator.JavaSystemInfos; import org.esa.snap.smart.configurator.PerformanceParameters; import org.esa.snap.smart.configurator.VMParameters; import org.esa.snap.ui.AppContext; import javax.media.jai.JAI; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.Color; import java.awt.Component; import java.awt.Cursor; import java.awt.Window; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Set; import java.util.TreeSet; import java.util.logging.Level; import java.util.prefs.BackingStoreException; import java.util.regex.Pattern; final class PerformancePanel extends javax.swing.JPanel { /** * Color for fields filed with values in place in the application */ private static final Color CURRENT_VALUES_COLOR = Color.BLACK; /** * Color for error fields * */ private static final Color ERROR_VALUES_COLOR = Color.RED; /** * Separator between values to be tested for the benchmark */ private static final String BENCHMARK_SEPARATOR=";"; private static final int nbCores = JavaSystemInfos.getInstance().getNbCPUs(); /** * Tool for optimizing and setting the performance parameters */ private final ConfigurationOptimizer confOptimizer; private final PerformanceOptionsPanelController controller; private static Path getUserDirPathFromString(String userDirString) { Path userDirPath = null; try { File userDirAsFile = new File(userDirString); userDirPath = FileUtils.getPathFromURI(userDirAsFile.toURI()); } catch (IOException e) { SystemUtils.LOG.log(Level.WARNING, "Cannot convert performance parameters to PATH: {0}", userDirString); } return userDirPath; } PerformancePanel(PerformanceOptionsPanelController controller) { this.controller = controller; confOptimizer = ConfigurationOptimizer.getInstance(); initComponents(); DocumentListener textFieldListener = new DocumentListener() { @Override public void insertUpdate(DocumentEvent e) { controller.changed(); } @Override public void removeUpdate(DocumentEvent e) { controller.changed(); } @Override public void changedUpdate(DocumentEvent e) { controller.changed(); } }; vmParametersTextField.getDocument().addDocumentListener(textFieldListener); cachePathTextField.getDocument().addDocumentListener(textFieldListener); nbThreadsTextField.getDocument().addDocumentListener(textFieldListener); tileSizeTextField.getDocument().addDocumentListener(textFieldListener); cacheSizeTextField.getDocument().addDocumentListener(textFieldListener); } /** * This method is called from within the constructor to initialize the form. */ private void initComponents() { PerformanceParameters actualParameters = confOptimizer.getActualPerformanceParameters(); java.awt.GridBagConstraints gridBagConstraints; systemParametersPanel = new javax.swing.JPanel(); cachePathLabel = new javax.swing.JLabel(); vmParametersTextField = new javax.swing.JTextField(); editVMParametersButton = new javax.swing.JButton(); cachePathTextField = new javax.swing.JTextField(); browseUserDirButton = new javax.swing.JButton(); vmParametersLabel = new javax.swing.JLabel(); sysResetButton = new javax.swing.JButton(); sysComputeButton = new javax.swing.JButton(); largeCacheInfoLabel = new javax.swing.JLabel(); vmParametersInfoLabel = new javax.swing.JLabel(); processingParametersPanel = new javax.swing.JPanel(); jPanel2 = new javax.swing.JPanel(); tileSizeLabel = new javax.swing.JLabel(); cacheSizeLabel = new javax.swing.JLabel(); nbThreadsLabel = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); tileSizeTextField = new javax.swing.JTextField(); cacheSizeTextField = new javax.swing.JTextField(); nbThreadsTextField = new javax.swing.JTextField(); jPanel4 = new javax.swing.JPanel(); benchmarkTileSizeTextField = new javax.swing.JTextField(); cacheSizeTextField = new javax.swing.JTextField(); benchmarkNbThreadsTextField = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); procGraphJComboBox = new javax.swing.JComboBox(getBenchmarkOperators()); procGraphJComboBox.setSelectedItem("StoredGraph"); jPanel3 = new javax.swing.JPanel(); processingParamsComputeButton = new javax.swing.JButton(); processingParamsResetButton = new javax.swing.JButton(); BoxLayout perfPanelLayout = new BoxLayout(this, BoxLayout.Y_AXIS); setLayout(perfPanelLayout); Box.createVerticalGlue(); systemParametersPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.systemParametersPanel.border.title"))); systemParametersPanel.setMinimumSize(new java.awt.Dimension(283, 115)); systemParametersPanel.setLayout(new java.awt.GridBagLayout()); org.openide.awt.Mnemonics.setLocalizedText(cachePathLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.jLabel2.text")); cachePathLabel.setMaximumSize(new java.awt.Dimension(100, 14)); cachePathLabel.setPreferredSize(new java.awt.Dimension(80, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); systemParametersPanel.add(cachePathLabel, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(vmParametersLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.jLabel3.text")); vmParametersLabel.setMaximumSize(new java.awt.Dimension(200, 14)); vmParametersLabel.setMinimumSize(new java.awt.Dimension(100, 14)); vmParametersLabel.setPreferredSize(new java.awt.Dimension(80, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); systemParametersPanel.add(vmParametersLabel, gridBagConstraints); vmParametersTextField.setText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.vmParametersTextField.text")); vmParametersTextField.setToolTipText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.vmParametersTextField.toolTipText")); if (!VMParameters.canSave()) { vmParametersTextField.setEditable(false); } vmParametersTextField.setColumns(50); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 2.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); systemParametersPanel.add(vmParametersTextField, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(editVMParametersButton, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.editVMParametersButton.text")); editVMParametersButton.addActionListener(this::editVMParametersButtonActionPerformed); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 2, 0, 10); systemParametersPanel.add(editVMParametersButton, gridBagConstraints); if(!VMParameters.canSave()) { vmParametersLabel.setEnabled(false); vmParametersTextField.setEnabled(false); editVMParametersButton.setEnabled(false); String vmParameterDisableToolTip = "VM parameters can't be saved from SNAP, please use the snap-conf-optimiser application as an administrator to change them"; vmParametersLabel.setToolTipText(vmParameterDisableToolTip); vmParametersTextField.setToolTipText(vmParameterDisableToolTip); editVMParametersButton.setToolTipText(vmParameterDisableToolTip); } cachePathTextField.setText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.userDirTextField.text")); cachePathTextField.setToolTipText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.userDirTextField.toolTipText")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 2.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); systemParametersPanel.add(cachePathTextField, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(cacheSizeLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.cacheSizeLabel.text")); cacheSizeLabel.setMaximumSize(new java.awt.Dimension(200, 14)); cacheSizeLabel.setMinimumSize(new java.awt.Dimension(100, 14)); cacheSizeLabel.setPreferredSize(new java.awt.Dimension(80, 14)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); systemParametersPanel.add(cacheSizeLabel, gridBagConstraints); cacheSizeTextField.setText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.cacheSizeTextField.text")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.gridwidth = java.awt.GridBagConstraints.RELATIVE; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 2.0; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 0); systemParametersPanel.add(cacheSizeTextField, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(browseUserDirButton, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.browseUserDirButton.text")); browseUserDirButton.addActionListener(evt -> browseCachePathButtonActionPerformed()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 2, 0, 10); systemParametersPanel.add(browseUserDirButton, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(sysResetButton, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.sysResetButton.text")); sysResetButton.addActionListener(evt -> sysResetButtonActionPerformed()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 4; gridBagConstraints.insets = new java.awt.Insets(10, 3, 0, 10); systemParametersPanel.add(sysResetButton, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(sysComputeButton, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.sysComputeButton.text")); sysComputeButton.addActionListener(evt -> sysComputeButtonActionPerformed()); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(10, 0, 0, 3); systemParametersPanel.add(sysComputeButton, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(largeCacheInfoLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.largeCacheInfoLabel.text")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; systemParametersPanel.add(largeCacheInfoLabel, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(vmParametersInfoLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.vmParametersInfoLabel.text")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; systemParametersPanel.add(vmParametersInfoLabel, gridBagConstraints); add(systemParametersPanel); Box.createVerticalGlue(); processingParametersPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.border.title"))); processingParametersPanel.setName(""); processingParametersPanel.setLayout(new java.awt.GridBagLayout()); jPanel2.setLayout(new java.awt.GridLayout(/*3*/2, 0, 0, 15)); org.openide.awt.Mnemonics.setLocalizedText(tileSizeLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.tileSizeLabel.text")); tileSizeLabel.setMaximumSize(new java.awt.Dimension(120, 14)); tileSizeLabel.setPreferredSize(new java.awt.Dimension(100, 14)); tileSizeLabel.setToolTipText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.tileSizeLabel.toolTipText")); jPanel2.add(tileSizeLabel); //org.openide.awt.Mnemonics.setLocalizedText(cacheSizeLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.cacheSizeLabel.text")); //cacheSizeLabel.setMaximumSize(new java.awt.Dimension(100, 14)); //cacheSizeLabel.setPreferredSize(new java.awt.Dimension(80, 14)); //jPanel2.add(cacheSizeLabel); org.openide.awt.Mnemonics.setLocalizedText(nbThreadsLabel, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.nbThreadsLabel.text")); nbThreadsLabel.setMaximumSize(new java.awt.Dimension(100, 14)); jPanel2.add(nbThreadsLabel); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.insets = new java.awt.Insets(10, 10, 0, 0); processingParametersPanel.add(jPanel2, gridBagConstraints); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.jPanel1.border.title"))); jPanel1.setMinimumSize(new java.awt.Dimension(100, 100)); jPanel1.setLayout(new java.awt.GridLayout(/*3*/2, 1, 0, 10)); tileSizeTextField.setText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.defaultTileSizeTextField.text")); tileSizeTextField.setMinimumSize(new java.awt.Dimension(100, 20)); tileSizeTextField.setPreferredSize(new java.awt.Dimension(100, 20)); jPanel1.add(tileSizeTextField); //cacheSizeTextField.setText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.cacheSizeTextField.text")); //cacheSizeTextField.setMinimumSize(new java.awt.Dimension(100, 20)); //cacheSizeTextField.setName(""); //cacheSizeTextField.setPreferredSize(new java.awt.Dimension(100, 20)); //jPanel1.add(cacheSizeTextField); nbThreadsTextField.setText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.nbThreadsTextField.text")); nbThreadsTextField.setPreferredSize(new java.awt.Dimension(100, 20)); jPanel1.add(nbThreadsTextField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 0; processingParametersPanel.add(jPanel1, gridBagConstraints); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.jPanel4.border.title"))); jPanel4.setMinimumSize(new java.awt.Dimension(190, 107)); jPanel4.setLayout(new java.awt.GridLayout(/*3*/2, 1, 0, 10)); String tileSizeBenchmarkValues = getTileSizeValuesForBenchmark(Integer.toString(actualParameters.getDefaultTileSize())); benchmarkTileSizeTextField.setText(tileSizeBenchmarkValues); benchmarkTileSizeTextField.setPreferredSize(new java.awt.Dimension(150, 20)); benchmarkTileSizeTextField.setToolTipText(org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.tileDimensionTextField.toolTipText")); jPanel4.add(benchmarkTileSizeTextField); //Move to SystemPanel //String cacheSizeBenchmarkValues = getDefaultCacheSizeValuesForBenchmark(actualParameters); //benchmarkCacheSizeTextField.setText(cacheSizeBenchmarkValues); //benchmarkCacheSizeTextField.setMinimumSize(new java.awt.Dimension(100, 20)); //benchmarkCacheSizeTextField.setName(""); //benchmarkCacheSizeTextField.setPreferredSize(new java.awt.Dimension(150, 20)); //jPanel4.add(benchmarkCacheSizeTextField); benchmarkNbThreadsTextField.setText(Integer.toString(actualParameters.getNbThreads()) + BENCHMARK_SEPARATOR); benchmarkNbThreadsTextField.setPreferredSize(new java.awt.Dimension(150, 20)); jPanel4.add(benchmarkNbThreadsTextField); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 2.0; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 10); processingParametersPanel.add(jPanel4, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(jLabel1, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.jLabel1.text")); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(5, 10, 0, 0); processingParametersPanel.add(jLabel1, gridBagConstraints); procGraphJComboBox.setMinimumSize(new java.awt.Dimension(180, 22)); nbThreadsTextField.setMinimumSize(new java.awt.Dimension(100, 20)); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.gridwidth = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(5, 0, 0, 10); processingParametersPanel.add(procGraphJComboBox, gridBagConstraints); org.openide.awt.Mnemonics.setLocalizedText(processingParamsComputeButton, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.text")); processingParamsComputeButton.setName(""); processingParamsComputeButton.addActionListener(this::processingParamsComputeButtonActionPerformed); jPanel3.add(processingParamsComputeButton); org.openide.awt.Mnemonics.setLocalizedText(processingParamsResetButton, org.openide.util.NbBundle.getMessage(PerformancePanel.class, "PerformancePanel.processingParamsResetButton.text")); processingParamsResetButton.addActionListener(this::processingParamsResetButtonActionPerformed); jPanel3.add(processingParamsResetButton); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 2; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.EAST; gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 5); processingParametersPanel.add(jPanel3, gridBagConstraints); add(processingParametersPanel); } private String getTileDimensionValuesForBenchmark(String tileDimension) { StringBuilder defaultTileSizeValues = new StringBuilder(); defaultTileSizeValues.append("128"); defaultTileSizeValues.append(BENCHMARK_SEPARATOR); defaultTileSizeValues.append("256"); defaultTileSizeValues.append(BENCHMARK_SEPARATOR); defaultTileSizeValues.append("512"); defaultTileSizeValues.append(BENCHMARK_SEPARATOR); //return defaultTileSizeValues.toString(); return JAI.getDefaultTileSize().width + "," + JAI.getDefaultTileSize().height; } private String getTileSizeValuesForBenchmark(String tileDimension) { StringBuilder defaultTileSizeValues = new StringBuilder(); defaultTileSizeValues.append("128"); defaultTileSizeValues.append(BENCHMARK_SEPARATOR); defaultTileSizeValues.append("256"); defaultTileSizeValues.append(BENCHMARK_SEPARATOR); defaultTileSizeValues.append("512"); defaultTileSizeValues.append(BENCHMARK_SEPARATOR); return defaultTileSizeValues.toString(); //return JAI.getDefaultTileSize().width + "," + JAI.getDefaultTileSize().height; } private String getDefaultCacheSizeValuesForBenchmark(PerformanceParameters actualParameters) { StringBuilder defaultCacheSizeValues = new StringBuilder(); int defaultCacheSize = actualParameters.getCacheSize(); long xmx = actualParameters.getVmXMX(); if(xmx == 0) { PerformanceParameters memoryParameters = new PerformanceParameters(); ConfigurationOptimizer.getInstance().computeOptimisedRAMParams(memoryParameters); xmx = memoryParameters.getVmXMX(); } defaultCacheSizeValues.append(defaultCacheSize); defaultCacheSizeValues.append(BENCHMARK_SEPARATOR); if(xmx != 0) { defaultCacheSizeValues.append(Math.round(xmx * 0.5)); defaultCacheSizeValues.append(BENCHMARK_SEPARATOR); defaultCacheSizeValues.append(Math.round(xmx * 0.75)); defaultCacheSizeValues.append(BENCHMARK_SEPARATOR); } return defaultCacheSizeValues.toString(); } private void editVMParametersButtonActionPerformed(ActionEvent e) { Object source = e.getSource(); Window window = null; if (source instanceof Component) { Component component = (Component) source; window = SwingUtilities.getWindowAncestor(component); } String vmParametersAsBlankSeparatedString = vmParametersTextField.getText(); LineSplitTextEditDialog vmParamsEditDialog = new LineSplitTextEditDialog(window, vmParametersAsBlankSeparatedString, " ", "VM Parameters", VMParameters.canSave()); vmParamsEditDialog.show(); vmParametersTextField.setText(vmParamsEditDialog.getTextWithSeparators()); controller.changed(); } private Object[] getBenchmarkOperators() { ServiceRegistry<BenchmarkOperatorProvider> benchemarkOperatorServiceRegistry = ServiceRegistryManager.getInstance().getServiceRegistry(BenchmarkOperatorProvider.class); ServiceLoader.loadServices(benchemarkOperatorServiceRegistry); Set<BenchmarkOperatorProvider> providers = benchemarkOperatorServiceRegistry.getServices(); TreeSet<String> externalOperatorsAliases = new TreeSet<>(); for(BenchmarkOperatorProvider provider : providers) { Set<OperatorSpi> operatorSpis = provider.getBenchmarkOperators(); for(OperatorSpi operatorSpi : operatorSpis) { externalOperatorsAliases.add(operatorSpi.getOperatorAlias()); } } return externalOperatorsAliases.toArray(); } private void sysResetButtonActionPerformed() { setSystemPerformanceParametersToActualValues(); } private void sysComputeButtonActionPerformed() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); PerformanceParameters optimizedParameters = confOptimizer.computeOptimisedSystemParameters(); if(VMParameters.canSave() && !vmParametersTextField.getText().equals(optimizedParameters.getVMParameters())) { vmParametersTextField.setText(optimizedParameters.getVMParameters()); vmParametersTextField.setForeground(CURRENT_VALUES_COLOR); vmParametersTextField.setCaretPosition(0); } if(VMParameters.canSave() && !cacheSizeTextField.getText().equals(String.valueOf(optimizedParameters.getCacheSize()))) { cacheSizeTextField.setText(String.valueOf(optimizedParameters.getCacheSize())); cacheSizeTextField.setForeground(CURRENT_VALUES_COLOR); cacheSizeTextField.setCaretPosition(0); } if(!cachePathTextField.getText().equals(optimizedParameters.getCachePath().toString())) { cachePathTextField.setText(optimizedParameters.getCachePath().toString()); cachePathTextField.setForeground(CURRENT_VALUES_COLOR); } setCursor(Cursor.getDefaultCursor()); controller.changed(); } private void browseCachePathButtonActionPerformed() { JFileChooser fileChooser = new JFileChooser(cachePathTextField.getText()); fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnValue = fileChooser.showOpenDialog(this); if (returnValue == JFileChooser.APPROVE_OPTION) { File selectedDir = fileChooser.getSelectedFile(); cachePathTextField.setText(selectedDir.getAbsolutePath()); cachePathTextField.setForeground(CURRENT_VALUES_COLOR); controller.changed(); } } private void processingParamsComputeButtonActionPerformed(java.awt.event.ActionEvent evt) { if(validCompute()){ //Create performance parameters benchmark lists java.util.List<Integer> tileSizeList = new ArrayList<>(); java.util.List<String> tileDimensionList = new ArrayList<>(); java.util.List<Integer> cacheSizesList = new ArrayList<>(); java.util.List<Integer> nbThreadsList = new ArrayList<>(); for(String tileSize : StringUtils.split(benchmarkTileSizeTextField.getText(), ';')){ tileSizeList.add(Integer.parseInt(tileSize)); } //for(String dimension : StringUtils.split(benchmarkTileSizeTextField.getText(), ';')){ // tileDimensionList.add(dimension); //} tileDimensionList.add(JAI.getDefaultTileSize().width + "," + JAI.getDefaultTileSize().height); for(String cacheSize : StringUtils.split(cacheSizeTextField.getText(), ';')){ cacheSizesList.add(Integer.parseInt(cacheSize)); } for(String nbThread : StringUtils.split(benchmarkNbThreadsTextField.getText(), ';')){ nbThreadsList.add(Integer.parseInt(nbThread)); } Benchmark benchmarkModel = new Benchmark(tileSizeList, tileDimensionList, cacheSizesList, nbThreadsList); String opName = procGraphJComboBox.getSelectedItem().toString(); AppContext appContext = SnapApp.getDefault().getAppContext(); //launch Benchmark dialog BenchmarkDialog productDialog = new BenchmarkDialog(this, opName, benchmarkModel, appContext); productDialog.show(); } } private void processingParamsResetButtonActionPerformed(java.awt.event.ActionEvent evt) { setProcessingPerformanceParametersToActualValues(); } void load() { setSystemPerformanceParametersToActualValues(); setProcessingPerformanceParametersToActualValues(); } void updatePerformanceParameters(BenchmarkSingleCalculus benchmarkSingleCalcul){ tileSizeTextField.setText(benchmarkSingleCalcul.getDimensionString()); tileSizeTextField.setForeground(CURRENT_VALUES_COLOR); cacheSizeTextField.setText(Integer.toString(benchmarkSingleCalcul.getCacheSize())); cacheSizeTextField.setForeground(CURRENT_VALUES_COLOR); nbThreadsTextField.setText(Integer.toString(benchmarkSingleCalcul.getNbThreads())); nbThreadsTextField.setForeground(CURRENT_VALUES_COLOR); this.controller.changed(); } void store() { if(valid()) { PerformanceParameters updatedPerformanceParams = getPerformanceParameters(); confOptimizer.updateCustomisedParameters(updatedPerformanceParams); try { confOptimizer.saveCustomisedParameters(); } catch (IOException|BackingStoreException e) { SystemUtils.LOG.severe("Could not save performance parameters: " + e.getMessage()); setSystemPerformanceParametersToActualValues(); } } } private PerformanceParameters getPerformanceParameters() { PerformanceParameters parameters = new PerformanceParameters(); parameters.setVMParameters(vmParametersTextField.getText()); Path userDirPath = getUserDirPathFromString(cachePathTextField.getText()); parameters.setCachePath(userDirPath); parameters.setDefaultTileSize(Integer.parseInt(tileSizeTextField.getText())); parameters.setTileDimension(tileSizeTextField.getText() + "," + tileSizeTextField.getText()); parameters.setCacheSize(Integer.parseInt(cacheSizeTextField.getText())); parameters.setNbThreads(Integer.parseInt(nbThreadsTextField.getText())); return parameters; } boolean valid() { boolean isValid = true; File userDir = new File(cachePathTextField.getText()); if(userDir.exists() && !userDir.isDirectory()) { cachePathTextField.setForeground(ERROR_VALUES_COLOR); isValid = false; } else { cachePathTextField.setForeground(CURRENT_VALUES_COLOR); } //Commented because tiledimension has been removed temporary from the panel if(PerformanceParameters.isValidDimension(this.tileSizeTextField.getText())) { this.tileSizeTextField.setForeground(CURRENT_VALUES_COLOR); } else { this.tileSizeTextField.setForeground(ERROR_VALUES_COLOR); isValid = false; } String readerCacheSize = this.cacheSizeTextField.getText(); try{ Integer.parseInt(readerCacheSize); cacheSizeTextField.setForeground(CURRENT_VALUES_COLOR); } catch (NumberFormatException ex) { this.cacheSizeTextField.setForeground(ERROR_VALUES_COLOR); isValid = false; } String nbThreadsString = nbThreadsTextField.getText(); try{ int nbThreads = Integer.parseUnsignedInt(nbThreadsString); if(nbThreads > nbCores) { nbThreadsTextField.setForeground(ERROR_VALUES_COLOR); isValid = false; } else { nbThreadsTextField.setForeground(CURRENT_VALUES_COLOR); } } catch (NumberFormatException ex) { nbThreadsTextField.setForeground(ERROR_VALUES_COLOR); isValid = false; } return isValid; } private boolean validCompute() { boolean isValid = true; Pattern patternBenchmarkValues = Pattern.compile("([0-9]+[\\;]*)+"); /*String[] dimensions = StringUtils.split(benchmarkTileDimensionTextField.getText(), ';'); boolean isValidDimensions = true; for (String dimension : dimensions) { if (!PerformanceParameters.isValidDimension(dimension)) { isValidDimensions = false; } } if(isValidDimensions) { benchmarkTileDimensionTextField.setForeground(CURRENT_VALUES_COLOR); } else { isValid = false; benchmarkTileDimensionTextField.setForeground(ERROR_VALUES_COLOR); }*/ if (!patternBenchmarkValues.matcher(benchmarkTileSizeTextField.getText()).matches()) { benchmarkTileSizeTextField.setForeground(ERROR_VALUES_COLOR); isValid = false; } else { benchmarkTileSizeTextField.setForeground(CURRENT_VALUES_COLOR); } //if (!patternBenchmarkValues.matcher(benchmarkCacheSizeTextField.getText()).matches()) { // benchmarkCacheSizeTextField.setForeground(ERROR_VALUES_COLOR); // isValid = false; //} else { // benchmarkCacheSizeTextField.setForeground(CURRENT_VALUES_COLOR); //} if (!patternBenchmarkValues.matcher(benchmarkNbThreadsTextField.getText()).matches() || !validBenchmarkNbThreads()) { benchmarkNbThreadsTextField.setForeground(ERROR_VALUES_COLOR); isValid = false; } else { benchmarkNbThreadsTextField.setForeground(CURRENT_VALUES_COLOR); } return isValid; } private boolean validBenchmarkNbThreads(){ boolean valid = true; for(String nbThread : StringUtils.split(benchmarkNbThreadsTextField.getText(), ';')){ try { if(Integer.parseInt(nbThread) > nbCores){ valid = false; break; } } catch (NumberFormatException e){ valid = false; break; } } return valid; } private void setSystemPerformanceParametersToActualValues() { PerformanceParameters actualPerformanceParameters = confOptimizer.getActualPerformanceParameters(); vmParametersTextField.setText(actualPerformanceParameters.getVMParameters()); vmParametersTextField.setForeground(CURRENT_VALUES_COLOR); vmParametersTextField.setCaretPosition(0); cachePathTextField.setText(actualPerformanceParameters.getCachePath().toString()); cachePathTextField.setForeground(CURRENT_VALUES_COLOR); cacheSizeTextField.setText(String.valueOf(actualPerformanceParameters.getCacheSize())); cacheSizeTextField.setForeground(CURRENT_VALUES_COLOR); tileSizeTextField.setText(String.valueOf(actualPerformanceParameters.getDefaultTileSize())); tileSizeTextField.setForeground(CURRENT_VALUES_COLOR); } private void setProcessingPerformanceParametersToActualValues() { PerformanceParameters actualPerformanceParameters = confOptimizer.getActualPerformanceParameters(); tileSizeTextField.setText(Integer.toString(actualPerformanceParameters.getDefaultTileSize())); tileSizeTextField.setForeground(CURRENT_VALUES_COLOR); //cacheSizeTextField.setText(Integer.toString(actualPerformanceParameters.getCacheSize())); //cacheSizeTextField.setForeground(CURRENT_VALUES_COLOR); nbThreadsTextField.setText(Integer.toString(actualPerformanceParameters.getNbThreads())); nbThreadsTextField.setForeground(CURRENT_VALUES_COLOR); } private javax.swing.JTextField cacheSizeTextField; private javax.swing.JTextField benchmarkNbThreadsTextField; private javax.swing.JTextField benchmarkTileSizeTextField; private javax.swing.JButton editVMParametersButton; private javax.swing.JButton browseUserDirButton; private javax.swing.JLabel cacheSizeLabel; //private javax.swing.JTextField cacheSizeTextField; private javax.swing.JTextField tileSizeTextField; private javax.swing.JLabel jLabel1; private javax.swing.JLabel cachePathLabel; private javax.swing.JLabel vmParametersLabel; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JLabel largeCacheInfoLabel; private javax.swing.JLabel nbThreadsLabel; private javax.swing.JTextField nbThreadsTextField; private javax.swing.JComboBox procGraphJComboBox; private javax.swing.JPanel processingParametersPanel; private javax.swing.JButton processingParamsComputeButton; private javax.swing.JButton processingParamsResetButton; private javax.swing.JButton sysComputeButton; private javax.swing.JButton sysResetButton; private javax.swing.JPanel systemParametersPanel; private javax.swing.JLabel tileSizeLabel; private javax.swing.JTextField cachePathTextField; private javax.swing.JLabel vmParametersInfoLabel; private javax.swing.JTextField vmParametersTextField; }
39,711
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BenchmarkDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-smart-configurator-ui/src/main/java/org/esa/snap/smart/configurator/ui/BenchmarkDialog.java
/* * Copyright (C) 2015 CS SI * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.smart.configurator.ui; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import com.bc.ceres.core.VirtualDir; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.Operator; import org.esa.snap.core.gpf.common.WriteOp; import org.esa.snap.core.gpf.internal.OperatorContext; import org.esa.snap.core.gpf.internal.OperatorExecutor; import org.esa.snap.core.gpf.internal.OperatorProductReader; import org.esa.snap.core.gpf.ui.DefaultSingleTargetProductDialog; import org.esa.snap.core.gpf.ui.TargetProductSelectorModel; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.actions.file.SaveProductAsAction; import org.esa.snap.rcp.util.ProgressHandleMonitor; import org.esa.snap.smart.configurator.Benchmark; import org.esa.snap.smart.configurator.BenchmarkSingleCalculus; import org.esa.snap.smart.configurator.ConfigurationOptimizer; import org.esa.snap.smart.configurator.PerformanceParameters; import org.esa.snap.smart.configurator.StoredGraphOp; import org.esa.snap.ui.AppContext; import org.netbeans.api.progress.ProgressUtils; import org.openide.DialogDisplayer; import org.openide.NotifyDescriptor; import org.openide.util.Cancellable; import javax.media.jai.JAI; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableModel; import javax.swing.table.TableRowSorter; import java.awt.*; import java.io.File; import java.nio.file.Paths; import java.util.List; /** * Dialog to launch performance parameters benchmark. * * @author Manuel Campomanes */ public class BenchmarkDialog extends DefaultSingleTargetProductDialog { /** * Benchmark calculus model */ private Benchmark benchmarkModel; /** * Parent panel */ private PerformancePanel perfPanel; /** * Constructor * * @param perfPanel Parent JPanel * @param operatorName Operator name * @param benchmarkModel Benchmark model * @param appContext Application context */ public BenchmarkDialog(PerformancePanel perfPanel, String operatorName, Benchmark benchmarkModel, AppContext appContext) { super(operatorName, appContext, "Benchmark " + operatorName, null, false); this.benchmarkModel = benchmarkModel; this.getJDialog().setModal(true); this.perfPanel = perfPanel; } protected void executeOperator(Product targetProduct, ProgressHandleMonitor pm) throws Exception { final TargetProductSelectorModel model = getTargetProductSelector().getModel(); //To avoid a nullPointerException in model.getProductFile() if(model.getProductName()==null) { model.setProductName(targetProduct.getName()); } Operator execOp = null; if (targetProduct.getProductReader() instanceof OperatorProductReader) { final OperatorProductReader opReader = (OperatorProductReader) targetProduct.getProductReader(); Operator operator = opReader.getOperatorContext().getOperator(); boolean autoWriteDisabled = operator.getSpi().getOperatorDescriptor().isAutoWriteDisabled(); if (autoWriteDisabled) { execOp = operator; } } if (execOp == null) { WriteOp writeOp = new WriteOp(targetProduct, model.getProductFile(), model.getFormatName()); writeOp.setDeleteOutputOnFailure(true); writeOp.setWriteEntireTileRows(true); writeOp.setClearCacheAfterRowWrite(false); execOp = writeOp; } SubProgressMonitor pm2 = (SubProgressMonitor) SubProgressMonitor.create(pm, 95); //execute if(execOp.canComputeTile() || execOp.canComputeTileStack()) { final OperatorExecutor executor = OperatorExecutor.create(execOp); executor.execute(pm2); } else { execOp.execute(pm2); } pm2.done(); } @Override protected void onApply() { BenchmarkExecutor executor = new BenchmarkExecutor(); //launch processing with a progress bar ProgressHandleMonitor pm = ProgressHandleMonitor.create("Running benchmark", executor); executor.setProgressHandleMonitor(pm); ProgressUtils.runOffEventThreadWithProgressDialog(executor, "Benchmarking....", pm.getProgressHandle(), true, 50, 1000); } private class BenchmarkExecutor implements Runnable, Cancellable { ProgressHandleMonitor progressHandleMonitor = null; BenchmarkSingleCalculus currentBenchmarkSingleCalcul = null; private boolean canceled = false; private void setProgressHandleMonitor(ProgressHandleMonitor progressHandleMonitor) { this.progressHandleMonitor = progressHandleMonitor; } @Override public boolean cancel() { //load old params (before benchmark) benchmarkModel.loadBenchmarkPerfParams(currentBenchmarkSingleCalcul); canceled = true; return true; } @Override public void run() { canceled = false; if (progressHandleMonitor == null) { throw new IllegalStateException("Progress Handle Monitor not set"); } //temporary directory for benchmark String tmpdirPath = Paths.get(SystemUtils.getCacheDir().toString(), "snap-benchmark-tmp").toString(); appContext.getPreferences().setPropertyString(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, tmpdirPath); //add current performance parameters to benchmark PerformanceParameters currentPerformanceParameters = ConfigurationOptimizer.getInstance().getActualPerformanceParameters(); currentBenchmarkSingleCalcul = new BenchmarkSingleCalculus( currentPerformanceParameters.getDefaultTileSize(), currentPerformanceParameters.getTileHeight(),currentPerformanceParameters.getTileWidth(), currentPerformanceParameters.getCacheSize(), currentPerformanceParameters.getNbThreads()); if (!benchmarkModel.isAlreadyInList(currentBenchmarkSingleCalcul)) { benchmarkModel.addBenchmarkCalcul(currentBenchmarkSingleCalcul); } try { progressHandleMonitor.beginTask("Benchmark running... ", benchmarkModel.getBenchmarkCalculus().size() * 100); List<BenchmarkSingleCalculus> benchmarkSingleCalculusList = benchmarkModel.getBenchmarkCalculus(); int executionOrder = 0; for (BenchmarkSingleCalculus benchmarkSingleCalcul : benchmarkSingleCalculusList) { /*progressHandleMonitor.getProgressHandle().progress( String.format("Benchmarking ( tile size:%s , cache size:%d , nb threads:%d )", benchmarkSingleCalcul.getDimensionString(), benchmarkSingleCalcul.getCacheSize(), benchmarkSingleCalcul.getNbThreads()));*/ progressHandleMonitor.getProgressHandle().progress( String.format("Benchmarking ( cache size:%d , nb threads:%d )", benchmarkSingleCalcul.getCacheSize(), benchmarkSingleCalcul.getNbThreads())); final Product targetProduct; //load performance parameters for current benchmark benchmarkModel.loadBenchmarkPerfParams(benchmarkSingleCalcul); //processing start time long startTime = System.currentTimeMillis(); try { targetProduct = createTargetProduct(); } catch (Throwable t) { handleInitialisationError(t); throw t; } if (targetProduct == null) { throw new NullPointerException("Target product is null."); } //When the source product is read at the beginning, a preferred tile size is selected (tipically, the tile size of the properties). //There are some operators which do not use the properties for setting the tile size of the product and they use directly the tile size of the inputs. //Since the inputs are loaded only one time, the first tile size is always used. //In the line below, we re-write that preferred tile size in order to generate the output with the benchmark value. //TODO review because getTile from benchmarkSingleCalcul could be null or *... //targetProduct.setPreferredTileSize(new Dimension(Integer.parseInt(benchmarkSingleCalcul.getTileWidth()),Integer.parseInt(benchmarkSingleCalcul.getTileHeight()))); executeOperator(targetProduct, progressHandleMonitor); //save execution time long endTime = System.currentTimeMillis(); benchmarkSingleCalcul.setExecutionTime(endTime - startTime); benchmarkSingleCalcul.setExecutionOrder(executionOrder); executionOrder++; SystemUtils.LOG.fine(String.format("Start time: %d, end time: %d, diff: %d", startTime, endTime, endTime - startTime)); // we remove all tiles //TODO cambiar, esto solo funciona si es cache in memery, pero no si es en file JAI.getDefaultInstance().getTileCache().flush(); } progressHandleMonitor.done(); } catch (Exception ex) { SystemUtils.LOG.severe("Could not perform benchmark: " + ex.getMessage()); } finally { //load old params (before benchmark) benchmarkModel.loadBenchmarkPerfParams(currentBenchmarkSingleCalcul); //delete benchmark TMP directory VirtualDir.deleteFileTree(new File(tmpdirPath)); } managePostBenchmark(); } private void managePostBenchmark() { if (!canceled) { //sort benchmark results and return the fastest BenchmarkSingleCalculus bestBenchmarkSingleCalcul = benchmarkModel.getFasterBenchmarkSingleCalculus(); //load fastest params? benchmarkModel.loadBenchmarkPerfParams(bestBenchmarkSingleCalcul); showResults(); //update parent panel with best values perfPanel.updatePerformanceParameters(bestBenchmarkSingleCalcul); } close(); } private void showResults() { // table model class BenchmarkTableModel extends AbstractTableModel { //final String[] columnNames = benchmarkModel.getColumnsNames(); //final int[][] data = benchmarkModel.getRowsToShow(); final String[] columnNames = benchmarkModel.getColumnsNamesWithoutTileDimension(); final int[][] data = benchmarkModel.getRowsToShowWhitoutTileDimension(); @Override public Class getColumnClass(int column) { return Integer.class; } public int getColumnCount() { return columnNames.length; } public int getRowCount() { return data.length; } public String getColumnName(int col) { return columnNames[col]; } public Object getValueAt(int row, int col) { return data[row][col]; } } BenchmarkTableModel tableModel = new BenchmarkTableModel(); JTable table = new JTable(tableModel); // For sorting TableRowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel); table.setRowSorter(rowSorter); DefaultTableCellRenderer tcr = new DefaultTableCellRenderer(); tcr.setHorizontalAlignment(SwingConstants.CENTER); table.getColumnModel().getColumn(table.getColumnCount() - 1).setCellRenderer(tcr); JPanel panel = new JPanel(new BorderLayout(4, 4)); JScrollPane panelTable = new JScrollPane(table); panel.add(panelTable, BorderLayout.CENTER); NotifyDescriptor d = new NotifyDescriptor(panel, "Benchmark results", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, null); DialogDisplayer.getDefault().notify(d); } } }
13,922
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SmartConfigurator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-smart-configurator-ui/src/main/java/org/esa/snap/smart/configurator/ui/SmartConfigurator.java
/* * Copyright (C) 2015 CS SI * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.smart.configurator.ui; import org.esa.snap.core.util.SystemUtils; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import java.awt.BorderLayout; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; /** * Launcher for the performance optimisation out of SNAP. * * @author Nicolas Ducoin */ public class SmartConfigurator extends javax.swing.JFrame implements PropertyChangeListener { private PerformancePanel performancePanel; PerformanceOptionsPanelController controller; JButton okButton; /** * Creates new form SmartConfigurator */ public SmartConfigurator() { initComponents(); } private void initComponents() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) { SystemUtils.LOG.warning("Could not set up look&feel: " + e.getMessage()); } JPanel jPanel1 = new JPanel(); okButton = new JButton(); JButton cancelButton = new JButton(); controller = new PerformanceOptionsPanelController(); controller.addPropertyChangeListener(this); performancePanel = new PerformancePanel(controller); performancePanel.load(); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); org.openide.awt.Mnemonics.setLocalizedText(okButton, org.openide.util.NbBundle.getMessage(SmartConfigurator.class, "SmartConfigurator.okButton.text")); okButton.addActionListener(this::okButtonActionPerformed); jPanel1.add(okButton); org.openide.awt.Mnemonics.setLocalizedText(cancelButton, org.openide.util.NbBundle.getMessage(SmartConfigurator.class, "SmartConfigurator.cancelButton.text")); // NOI18N cancelButton.addActionListener(this::cancelButtonActionPerformed); jPanel1.add(cancelButton); getContentPane().add(jPanel1, BorderLayout.SOUTH); getContentPane().add(performancePanel, java.awt.BorderLayout.CENTER); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setIconImage(new ImageIcon(getClass().getResource("SNAP_icon_16.png")).getImage()); setTitle("SNAP Performance Configuration Optimisation"); pack(); } private void okButtonActionPerformed(java.awt.event.ActionEvent evt) { performancePanel.store(); System.exit(0); } private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } @Override public void propertyChange(PropertyChangeEvent evt) { if(performancePanel.valid()) { okButton.setEnabled(true); } else { okButton.setEnabled(false); } } /** * @param args the command line arguments */ public static void main(String args[]) { /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> new SmartConfigurator().setVisible(true)); } }
3,912
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PerformanceOptionsPanelController.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-smart-configurator-ui/src/main/java/org/esa/snap/smart/configurator/ui/PerformanceOptionsPanelController.java
/* * Copyright (C) 2015 CS SI * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.smart.configurator.ui; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import javax.swing.JComponent; import javax.swing.SwingUtilities; import org.netbeans.spi.options.OptionsPanelController; import org.openide.util.HelpCtx; import org.openide.util.Lookup; @OptionsPanelController.TopLevelRegistration( categoryName = "#OptionsCategory_Name_Performance", iconBase = "org/esa/snap/smart/configurator/ui/Performance32.png", keywords = "#OptionsCategory_Keywords_Performance_Optim", keywordsCategory = "Performance", position = 3 ) @org.openide.util.NbBundle.Messages({"OptionsCategory_Name_Performance=Performance", "OptionsCategory_Keywords_Performance_Optim=Performance optimization smart configurator"}) public final class PerformanceOptionsPanelController extends OptionsPanelController { private PerformancePanel panel; private final PropertyChangeSupport pcs = new PropertyChangeSupport(this); private boolean changed; public void update() { getPanel().load(); changed = false; } public void applyChanges() { SwingUtilities.invokeLater(() -> { getPanel().store(); changed = false; }); } public void cancel() { // need not do anything special, if no changes have been persisted yet } public boolean isValid() { return getPanel().valid(); } public boolean isChanged() { return changed; } public HelpCtx getHelpCtx() { return new HelpCtx("performanceParameters"); } public JComponent getComponent(Lookup masterLookup) { return getPanel(); } public void addPropertyChangeListener(PropertyChangeListener l) { pcs.addPropertyChangeListener(l); } public void removePropertyChangeListener(PropertyChangeListener l) { pcs.removePropertyChangeListener(l); } private PerformancePanel getPanel() { if (panel == null) { panel = new PerformancePanel(this); } return panel; } void changed() { if (!changed) { changed = true; pcs.firePropertyChange(OptionsPanelController.PROP_CHANGED, false, true); } pcs.firePropertyChange(OptionsPanelController.PROP_VALID, null, null); } }
3,049
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SourceUITest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/test/java/org/esa/snap/graphbuilder/gpf/ui/SourceUITest.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import org.esa.snap.GlobalTestConfig; 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.AppContext; import org.esa.snap.ui.product.ProductSceneView; import org.junit.Before; import org.junit.Test; import javax.swing.JComponent; import javax.swing.JOptionPane; import java.awt.*; import java.io.File; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; /** * Tests the SourceUI * User: lveci * Date: Feb 15, 2008 */ public class SourceUITest { SourceUI sourceUI; private Product[] defaultProducts; private AppContext appContext; private final Map<String, Object> parameterMap = new HashMap<>(5); private static final String FILE_PARAMETER = "file"; private static final String PIXEL_REGION_PARAMETER = "pixelRegion"; private static final String GEOMETRY_REGION_PARAMETER = "geometryRegion"; @Before public void setUp() throws Exception { sourceUI = new SourceUI(); appContext = new MockAppContext(); final File path = GlobalTestConfig.getSnapTestDataOutputDirectory(); defaultProducts = new Product[2]; for (int i = 0; i < defaultProducts.length; i++) { Product prod = new Product("P" + i, "T" + i, 10, 10); prod.setFileLocation(path); appContext.getProductManager().addProduct(prod); defaultProducts[i] = prod; } } @Test public void testCreateOpTab() { JComponent component = sourceUI.CreateOpTab("testOp", parameterMap, appContext); assertNotNull(component); assertEquals(sourceUI.sourceProductSelector.getProductNameComboBox().getModel().getSize(), 2); } @Test public void testValidateParameters() { sourceUI.CreateOpTab("testOp", parameterMap, appContext); UIValidation valid = sourceUI.validateParameters(); assertTrue(valid.getState() == UIValidation.State.OK); } @Test public void testUpdateParameters() { sourceUI.CreateOpTab("testOp", parameterMap, appContext); parameterMap.put(FILE_PARAMETER, defaultProducts[0].getFileLocation()); sourceUI.updateParameters(); File path = (File) parameterMap.get(FILE_PARAMETER); assertTrue(path.getAbsolutePath().equals(defaultProducts[0].getFileLocation().getAbsolutePath())); assertNotNull(parameterMap.get(PIXEL_REGION_PARAMETER)); assertNull(parameterMap.get(GEOMETRY_REGION_PARAMETER)); } private class MockAppContext implements AppContext { private PropertyMap preferences = new DefaultPropertyMap(); private ProductManager prodMan = new ProductManager(); public Window getApplicationWindow() { return null; } public String getApplicationName() { return "Killer App"; } public Product getSelectedProduct() { return defaultProducts[0]; } public void handleError(Throwable e) { JOptionPane.showMessageDialog(getApplicationWindow(), e.getMessage()); } public void handleError(String message, Throwable e) { JOptionPane.showMessageDialog(getApplicationWindow(), message); } public PropertyMap getPreferences() { return preferences; } public ProductManager getProductManager() { return prodMan; } public ProductSceneView getSelectedProductSceneView() { return null; } } }
4,427
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TargetUITest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/test/java/org/esa/snap/graphbuilder/gpf/ui/TargetUITest.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import org.esa.snap.GlobalTestConfig; 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.AppContext; import org.esa.snap.ui.product.ProductSceneView; import org.junit.Before; import org.junit.Test; import javax.swing.JComponent; import javax.swing.JOptionPane; import java.awt.Window; import java.io.File; import java.util.HashMap; import java.util.Map; import static org.junit.Assert.*; /** * Tests the SourceUI * User: lveci * Date: Feb 15, 2008 */ public class TargetUITest { TargetUI targetUI; private Product[] defaultProducts; private AppContext appContext; private final Map<String, Object> parameterMap = new HashMap<>(); private final String FILE_PARAMETER = "file"; @Before public void setUp() throws Exception { targetUI = new TargetUI(); appContext = new MockAppContext(); final File path = GlobalTestConfig.getSnapTestDataOutputDirectory(); defaultProducts = new Product[2]; for (int i = 0; i < defaultProducts.length; i++) { Product prod = new Product("P" + i, "T" + i, 10, 10); prod.setFileLocation(path); appContext.getProductManager().addProduct(prod); defaultProducts[i] = prod; } } @Test public void testCreateOpTab() { JComponent component = targetUI.CreateOpTab("testOp", parameterMap, appContext); assertNotNull(component); } @Test public void testUpdateParameters() { targetUI.CreateOpTab("testOp", parameterMap, appContext); parameterMap.put(FILE_PARAMETER, defaultProducts[0]); //todo need an existing file? } private class MockAppContext implements AppContext { private PropertyMap preferences = new DefaultPropertyMap(); private ProductManager prodMan = new ProductManager(); public Product getSelectedProduct() { return defaultProducts[0]; } public Window getApplicationWindow() { return null; } public String getApplicationName() { return "Killer App"; } public void handleError(Throwable e) { JOptionPane.showMessageDialog(getApplicationWindow(), e.getMessage()); } public void handleError(String message, Throwable e) { JOptionPane.showMessageDialog(getApplicationWindow(), message); } public PropertyMap getPreferences() { return preferences; } public ProductManager getProductManager() { return prodMan; } public ProductSceneView getSelectedProductSceneView() { return null; } } }
3,604
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BatchGraphDialogTest.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/test/java/org/esa/snap/graphbuilder/rcp/dialogs/BatchGraphDialogTest.java
package org.esa.snap.graphbuilder.rcp.dialogs; import com.bc.ceres.annotation.STTM; import org.esa.snap.core.gpf.graph.Node; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphNode; import org.junit.Test; import java.io.File; import java.util.Map; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; public class BatchGraphDialogTest { @Test @STTM("SNAP-3626") public void testEnsureWriteNodeTargetReset() { final GraphNode[] graphNodes = new GraphNode[3]; graphNodes[0] = new GraphNode(new Node("Read", "theReader")); graphNodes[1] = new GraphNode(new Node("Process", "the_processor")); final GraphNode node = new GraphNode(new Node("Write", "WriteOp")); node.getParameterMap().put("file", new File("whatever")); graphNodes[2] = node; BatchGraphDialog.ensureWriteNodeTargetReset(graphNodes); Map<String, Object> parameterMap = graphNodes[2].getParameterMap(); assertFalse(parameterMap.containsKey("file")); } @Test @STTM("SNAP-3626") public void testEnsureWriteNodeTargetReset_emptyNodeArray() { try { BatchGraphDialog.ensureWriteNodeTargetReset(new GraphNode[0]); } catch (Exception e) { fail("no exception expected"); } } @Test @STTM("SNAP-3626") public void testEnsureWriteNodeTargetReset_noWriteNode() { final GraphNode[] graphNodes = new GraphNode[2]; graphNodes[0] = new GraphNode(new Node("Read", "theReader")); graphNodes[1] = new GraphNode(new Node("Process", "the_processor")); try { BatchGraphDialog.ensureWriteNodeTargetReset(graphNodes); } catch (Exception e) { fail("no exception expected"); } } }
1,802
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TestGraphExecuter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/test/java/org/esa/snap/graphbuilder/rcp/dialogs/support/TestGraphExecuter.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphExecuter; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphNode; import org.junit.Before; import org.junit.Test; import java.util.Observer; import java.util.Set; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * GraphExecuter Tester. * * @author lveci * @version 1.0 * @since 12/21/2007 */ public class TestGraphExecuter implements Observer { private GraphExecuter graphEx; private String updateValue = ""; @Before public void setUp() throws Exception { //TestUtils.initTestEnvironment(); graphEx = new GraphExecuter(); graphEx.addObserver(this); } @Test public void testGetOperators() { Set opList = graphEx.GetOperatorList(); assertTrue(!opList.isEmpty()); } @Test public void testAddOperator() { updateValue = ""; graphEx.addOperator("testOp"); GraphNode[] nodeList = graphEx.getGraphNodes(); assertEquals(1, nodeList.length); assertEquals(updateValue, "Add"); } @Test public void testClear() { graphEx.addOperator("testOp"); GraphNode[] nodeList = graphEx.getGraphNodes(); assertEquals(1, nodeList.length); graphEx.clearGraph(); assertEquals(0, graphEx.getGraphNodes().length); } @Test public void testRemoveOperator() { GraphNode node = graphEx.addOperator("testOp"); GraphNode[] nodeList = graphEx.getGraphNodes(); assertEquals(1, nodeList.length); updateValue = ""; graphEx.removeOperator(node); assertEquals(0, graphEx.getGraphNodes().length); assertEquals(updateValue, "Remove"); } @Test public void testFindGraphNode() { GraphNode lostNode = graphEx.addOperator("lostOp"); GraphNode foundNode = graphEx.getGraphNodeList().findGraphNode(lostNode.getID()); assertTrue(foundNode.equals(lostNode)); graphEx.clearGraph(); } @Test public void testSetSelected() { GraphNode node = graphEx.addOperator("testOp"); updateValue = ""; graphEx.setSelectedNode(node); assertEquals(updateValue, "Selected"); graphEx.clearGraph(); } @Test public void testCreateGraph() throws GraphException { GraphNode nodeA = graphEx.addOperator("testOp"); GraphNode nodeB = graphEx.addOperator("testOp"); nodeB.connectOperatorSource(nodeA.getID()); //graphEx.writeGraph("D:\\data\\testGraph.xml"); //graphEx.executeGraph(new NullProgressMonitor()); } /** * Implements the functionality of Observer participant of Observer Design Pattern to define a one-to-many * dependency between a Subject object and any number of Observer objects so that when the * Subject object changes state, all its Observer objects are notified and updated automatically. * <p> * Defines an updating interface for objects that should be notified of changes in a subject. * * @param subject The Observerable subject * @param data optional data */ public void update(java.util.Observable subject, Object data) { GraphExecuter.GraphEvent event = (GraphExecuter.GraphEvent) data; GraphNode node = (GraphNode) event.getData(); String opID = node.getNode().getId(); if (event.getEventType() == GraphExecuter.events.ADD_EVENT) { updateValue = "Add"; } else if (event.getEventType() == GraphExecuter.events.REMOVE_EVENT) { updateValue = "Remove"; } else if (event.getEventType() == GraphExecuter.events.SELECT_EVENT) { updateValue = "Selected"; } } }
4,617
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TestGraphNode.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/test/java/org/esa/snap/graphbuilder/rcp/dialogs/support/TestGraphNode.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.bc.ceres.binding.dom.XppDomElement; import org.esa.snap.core.gpf.graph.Node; import org.esa.snap.core.gpf.graph.NodeSource; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphNode; import org.junit.Before; import org.junit.Test; import java.awt.Point; import static org.junit.Assert.*; /** * GraphNode Tester. * * @author lveci * @version 1.0 * @since <pre>12/21/2007</pre> */ public class TestGraphNode { private Node node; private GraphNode graphNode; @Before public void setUp() throws Exception { node = new Node("id", "readOp"); final XppDomElement parameters = new XppDomElement("parameters"); node.setConfiguration(parameters); graphNode = new GraphNode(node); } @Test public void testPosition() { Point p1 = new Point(1, 2); graphNode.setPos(p1); Point p2 = graphNode.getPos(); assertEquals(p1, p2); } @Test public void testNode() { assertEquals(node, graphNode.getNode()); assertEquals(node.getId(), graphNode.getID()); assertEquals(node.getOperatorName(), graphNode.getOperatorName()); } @Test public void testSourceConnection() { final Node sourceNode = new Node("sourceID", "testSourceNodeOp"); final XppDomElement parameters = new XppDomElement("parameters"); sourceNode.setConfiguration(parameters); GraphNode sourceGraphNode = new GraphNode(sourceNode); // test connect graphNode.connectOperatorSource(sourceGraphNode.getID()); NodeSource ns = node.getSource(0); assertNotNull(ns); assertEquals(ns.getSourceNodeId(), sourceNode.getId()); // test disconnect graphNode.disconnectOperatorSources(sourceGraphNode.getID()); NodeSource[] nsList = node.getSources(); assertEquals(nsList.length, 0); } }
2,679
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ReprojectionUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/ReprojectionUI.java
package org.esa.snap.graphbuilder.gpf.ui; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.datamodel.GeoCoding; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.ImageGeometry; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductFilter; import org.esa.snap.core.gpf.ui.CollocationCrsForm; import org.esa.snap.core.util.ProductUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.DemSelector; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.crs.CrsForm; import org.esa.snap.ui.crs.CrsSelectionPanel; import org.esa.snap.ui.crs.CustomCrsForm; import org.esa.snap.ui.crs.OutputGeometryForm; import org.esa.snap.ui.crs.OutputGeometryFormModel; import org.esa.snap.ui.crs.PredefinedCrsForm; import org.opengis.referencing.FactoryException; import org.opengis.referencing.crs.CoordinateReferenceSystem; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.HashMap; import java.util.Map; /** * User interface for Reprojection */ public class ReprojectionUI extends BaseOperatorUI { private static final String[] RESAMPLING_IDENTIFIER = {"Nearest", "Bilinear", "Bicubic"}; private JScrollPane scrollPane; private boolean orthoMode = false; private AppContext appContext = SnapApp.getDefault().getAppContext(); private DemSelector demSelector; private CrsSelectionPanel crsSelectionPanel; private OutputGeometryFormModel outputGeometryModel; private JButton outputParamButton; private ReprojectionUI.InfoForm infoForm; private CoordinateReferenceSystem crs; //TODO add collocationCRSForm //private CollocationCrsForm collocationCrsUI; private CustomCrsForm customCrsUI; //Components of output setting panel final JCheckBox preserveResolutionCheckBox = new JCheckBox("Preserve resolution",true); JCheckBox includeTPcheck = new JCheckBox("Reproject tie-point grids", true); final JTextField noDataField = new JTextField(Double.toString(Double.NaN)); JCheckBox addDeltaBandsChecker = new JCheckBox("Add delta lat/lon bands"); JComboBox<String> resampleComboBox = new JComboBox<>(RESAMPLING_IDENTIFIER); //Create panel @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { initializeOperatorUI(operatorName, parameterMap); final JComponent panel = createPanel(); initParameters(); scrollPane = new JScrollPane(panel); return scrollPane; } //called when sourceProduct is set @Override public void initParameters() { if(hasSourceProducts() && sourceProducts[0] != null) { crsSelectionPanel.setReferenceProduct(sourceProducts[0]); if((sourceProducts[0].getBand("longitude") != null && sourceProducts[0].getBand("latitude") != null) || (sourceProducts[0].getTiePointGrid("longitude") != null && sourceProducts[0].getTiePointGrid("latitude") != null)) { addDeltaBandsChecker.setEnabled(true); } else { addDeltaBandsChecker.setEnabled(false); } } updateCRS(); updateParameters(); } @Override public UIValidation validateParameters() { return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { paramMap.clear(); paramMap.put("resamplingName", resampleComboBox.getSelectedItem().toString()); paramMap.put("includeTiePointGrids", includeTPcheck.isSelected()); paramMap.put("addDeltaBands", addDeltaBandsChecker.isSelected()); paramMap.put("noDataValue", Double.parseDouble(noDataField.getText())); // if (!collocationCrsUI.getRadioButton().isSelected()) { CoordinateReferenceSystem selectedCrs = getSelectedCrs(); if (selectedCrs != null) { paramMap.put("crs", selectedCrs.toWKT()); } else { paramMap.put("crs", "EPSG:4326"); } // collocationCrsUI.prepareHide(); // } else { // //TODO // final Map<String, Product> productMap = new HashMap<>(5); // productMap.put("source", getSourceProduct()); // if (collocationCrsUI.getRadioButton().isSelected()) { // collocationCrsUI.prepareShow(); // productMap.put("collocateWith", collocationCrsUI.getCollocationProduct()); // } // } if (orthoMode) { paramMap.put("orthorectify", orthoMode); if (demSelector.isUsingExternalDem()) { paramMap.put("elevationModelName", demSelector.getDemName()); } else { paramMap.put("elevationModelName", null); } } if (!preserveResolutionCheckBox.isSelected() && outputGeometryModel != null) { PropertySet container = outputGeometryModel.getPropertySet(); paramMap.put("referencePixelX", container.getValue("referencePixelX")); paramMap.put("referencePixelY", container.getValue("referencePixelY")); paramMap.put("easting", container.getValue("easting")); paramMap.put("northing", container.getValue("northing")); paramMap.put("orientation", container.getValue("orientation")); paramMap.put("pixelSizeX", container.getValue("pixelSizeX")); paramMap.put("pixelSizeY", container.getValue("pixelSizeY")); paramMap.put("width", container.getValue("width")); paramMap.put("height", container.getValue("height")); } } private JComponent createPanel() { final JPanel parameterPanel = new JPanel(); final TableLayout layout = new TableLayout(1); layout.setTablePadding(4, 4); layout.setTableFill(TableLayout.Fill.HORIZONTAL); layout.setTableAnchor(TableLayout.Anchor.WEST); layout.setTableWeightX(1.0); parameterPanel.setLayout(layout); //Create panel with CrsForms customCrsUI = new CustomCrsForm(appContext); CrsForm predefinedCrsUI = new PredefinedCrsForm(appContext); //collocationCrsUI = new CollocationCrsForm(appContext); CrsForm[] crsForms = new CrsForm[]{customCrsUI, predefinedCrsUI/*, collocationCrsUI*/}; crsSelectionPanel = new CrsSelectionPanel(crsForms); crsSelectionPanel.prepareShow(); //add CrsPanel to parameter panel parameterPanel.add(crsSelectionPanel); //if orthoMode, create and add demSelector if (orthoMode) { demSelector = new DemSelector(); parameterPanel.add(demSelector); } //create and add the output setting panel parameterPanel.add(createOuputSettingsPanel()); //create and add the info panel infoForm = new ReprojectionUI.InfoForm(); parameterPanel.add(infoForm.createUI()); //add change listener crsSelectionPanel.addPropertyChangeListener("crs", evt -> updateCRS()); updateCRS(); return parameterPanel; } Product getSourceProduct() { if(!hasSourceProducts()) { return null; } return sourceProducts[0]; } CoordinateReferenceSystem getSelectedCrs() { return crs; } private void updateCRS() { final Product sourceProduct = getSourceProduct(); try { if (sourceProduct != null) { crs = crsSelectionPanel.getCrs(ProductUtils.getCenterGeoPos(sourceProduct)); infoForm.setCenterPos(ProductUtils.getCenterGeoPos(sourceProduct)); if (outputGeometryModel != null) { outputGeometryModel.setSourceProduct(sourceProduct); } if (crs != null) { infoForm.setCrsInfoText(crs.getName().getCode(), crs.toString()); } else { infoForm.setCrsErrorText("No valid 'Coordinate Reference System' selected."); } } else { infoForm.setCrsErrorText("No source product selected."); crs = null; } } catch (FactoryException e) { infoForm.setCrsErrorText(e.getMessage()); crs = null; } if (outputGeometryModel != null) { outputGeometryModel.setTargetCrs(crs); } updateOutputParameterState(); } private void updateProductSize() { int width = 0; int height = 0; final Product sourceProduct = getSourceProduct(); if (sourceProduct != null && crs != null) { if (!preserveResolutionCheckBox.isSelected() && outputGeometryModel != null) { PropertySet container = outputGeometryModel.getPropertySet(); width = container.getValue("width"); height = container.getValue("height"); } else { ImageGeometry iGeometry; // final Product collocationProduct = collocationCrsUI.getCollocationProduct(); // if (collocationCrsUI.getRadioButton().isSelected() && collocationProduct != null) { // iGeometry = ImageGeometry.createCollocationTargetGeometry(sourceProduct, collocationProduct); // } else { iGeometry = ImageGeometry.createTargetGeometry(sourceProduct, crs, null, null, null, null, null, null, null, null, null); // } Rectangle imageRect = iGeometry.getImageRect(); width = imageRect.width; height = imageRect.height; } } infoForm.setWidth(width); infoForm.setHeight(height); } private class InfoForm { private JLabel widthLabel; private JLabel heightLabel; private JLabel centerLatLabel; private JLabel centerLonLabel; private JLabel crsLabel; private String wkt; private JButton wktButton; void setWidth(int width) { widthLabel.setText(Integer.toString(width)); } void setHeight(int height) { heightLabel.setText(Integer.toString(height)); } void setCenterPos(GeoPos geoPos) { if (geoPos != null) { centerLatLabel.setText(geoPos.getLatString()); centerLonLabel.setText(geoPos.getLonString()); } else { centerLatLabel.setText(""); centerLonLabel.setText(""); } } void setCrsErrorText(String infoText) { setCrsInfoText("<html><b>" + infoText + "</b>", null); } void setCrsInfoText(String infoText, String wkt) { this.wkt = wkt; crsLabel.setText(infoText); boolean hasWKT = (wkt != null); wktButton.setEnabled(hasWKT); } JPanel createUI() { widthLabel = new JLabel(); heightLabel = new JLabel(); centerLatLabel = new JLabel(); centerLonLabel = new JLabel(); crsLabel = new JLabel(); final TableLayout tableLayout = new TableLayout(5); tableLayout.setTableAnchor(TableLayout.Anchor.WEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTablePadding(4, 4); tableLayout.setColumnWeightX(0, 0.0); tableLayout.setColumnWeightX(1, 0.0); tableLayout.setColumnWeightX(2, 1.0); tableLayout.setColumnWeightX(3, 0.0); tableLayout.setColumnWeightX(4, 1.0); tableLayout.setCellColspan(2, 1, 3); tableLayout.setCellPadding(0, 3, new Insets(4, 24, 4, 20)); tableLayout.setCellPadding(1, 3, new Insets(4, 24, 4, 20)); final JPanel panel = new JPanel(tableLayout); panel.setBorder(BorderFactory.createTitledBorder("Output Information")); panel.add(new JLabel("Scene width:")); panel.add(widthLabel); panel.add(new JLabel("pixel")); panel.add(new JLabel("Center longitude:")); panel.add(centerLonLabel); panel.add(new JLabel("Scene height:")); panel.add(heightLabel); panel.add(new JLabel("pixel")); panel.add(new JLabel("Center latitude:")); panel.add(centerLatLabel); panel.add(new JLabel("CRS:")); panel.add(crsLabel); wktButton = new JButton("Show WKT"); wktButton.addActionListener(e -> { JTextArea wktArea = new JTextArea(30, 40); wktArea.setEditable(false); wktArea.setText(wkt); final JScrollPane scrollPane = new JScrollPane(wktArea); final ModalDialog dialog = new ModalDialog(appContext.getApplicationWindow(), "Coordinate reference system as well known text", scrollPane, ModalDialog.ID_OK, null); dialog.show(); }); wktButton.setEnabled(false); panel.add(wktButton); return panel; } } private JPanel createOuputSettingsPanel() { final TableLayout tableLayout = new TableLayout(3); tableLayout.setTableAnchor(TableLayout.Anchor.WEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setColumnFill(0, TableLayout.Fill.NONE); tableLayout.setTablePadding(4, 4); tableLayout.setColumnPadding(0, new Insets(4, 4, 4, 20)); tableLayout.setColumnWeightX(0, 0.0); tableLayout.setColumnWeightX(1, 0.0); tableLayout.setColumnWeightX(2, 1.0); tableLayout.setCellColspan(0, 1, 2); tableLayout.setCellPadding(1, 0, new Insets(4, 24, 4, 20)); final JPanel outputSettingsPanel = new JPanel(tableLayout); outputSettingsPanel.setBorder(BorderFactory.createTitledBorder("Output Settings")); preserveResolutionCheckBox.addActionListener(e -> { if (preserveResolutionCheckBox.isSelected()) { outputParamButton.setEnabled(false); } else { outputParamButton.setEnabled(true); } }); outputSettingsPanel.add(preserveResolutionCheckBox); outputSettingsPanel.add(includeTPcheck); outputParamButton = new JButton("Output Parameters..."); outputParamButton.setEnabled(!preserveResolutionCheckBox.isSelected()); outputParamButton.addActionListener(new OutputParamActionListener()); outputSettingsPanel.add(outputParamButton); outputSettingsPanel.add(new JLabel("No-data value:")); outputSettingsPanel.add(noDataField); outputSettingsPanel.add(addDeltaBandsChecker); outputSettingsPanel.add(new JLabel("Resampling method:")); resampleComboBox.setPrototypeDisplayValue(RESAMPLING_IDENTIFIER[0]); outputSettingsPanel.add(resampleComboBox); return outputSettingsPanel; } private void updateOutputParameterState() { outputParamButton.setEnabled(!preserveResolutionCheckBox.isSelected() && (crs != null)); updateProductSize(); } private void showWarningMessage(String message) { AbstractDialog.showWarningDialog(scrollPane, message, "Reprojection"); } private class OutputParamActionListener implements ActionListener { @Override public void actionPerformed(ActionEvent event) { try { final Product sourceProduct = getSourceProduct(); if (sourceProduct == null) { showWarningMessage("Please select a product to reproject.\n"); return; } if (crs == null) { showWarningMessage("Please specify a 'Coordinate Reference System' first.\n"); return; } OutputGeometryFormModel workCopy; if (outputGeometryModel != null) { workCopy = new OutputGeometryFormModel(outputGeometryModel); } else { // final Product collocationProduct = collocationCrsUI.getCollocationProduct(); // if (collocationCrsUI.getRadioButton().isSelected() && collocationProduct != null) { // workCopy = new OutputGeometryFormModel(sourceProduct, collocationProduct); // } else { workCopy = new OutputGeometryFormModel(sourceProduct, crs); // } } final OutputGeometryForm form = new OutputGeometryForm(workCopy); final ModalDialog outputParametersDialog = new OutputParametersDialog(appContext.getApplicationWindow(), sourceProduct, workCopy); outputParametersDialog.setContent(form); if (outputParametersDialog.show() == ModalDialog.ID_OK) { outputGeometryModel = workCopy; updateProductSize(); } } catch (Exception e) { appContext.handleError("Could not create a 'Coordinate Reference System'.\n" + e.getMessage(), e); } } } private class OutputParametersDialog extends ModalDialog { private static final String TITLE = "Output Parameters"; private final Product sourceProduct; private final OutputGeometryFormModel outputGeometryFormModel; public OutputParametersDialog(Window parent, Product sourceProduct, OutputGeometryFormModel outputGeometryFormModel) { super(parent, TITLE, ModalDialog.ID_OK_CANCEL | ModalDialog.ID_RESET, null); this.sourceProduct = sourceProduct; this.outputGeometryFormModel = outputGeometryFormModel; } @Override protected void onReset() { // final Product collocationProduct = collocationCrsUI.getCollocationProduct(); ImageGeometry imageGeometry; //if (collocationCrsUI.getRadioButton().isSelected() && collocationProduct != null) { // imageGeometry = ImageGeometry.createCollocationTargetGeometry(sourceProduct, collocationProduct); // } else { imageGeometry = ImageGeometry.createTargetGeometry(sourceProduct, crs, null, null, null, null, null, null, null, null, null); //} outputGeometryFormModel.resetToDefaults(imageGeometry); } } }
19,456
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatorUIUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/OperatorUIUtils.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import org.esa.snap.core.datamodel.Product; import org.esa.snap.engine_utilities.gpf.CommonReaders; import javax.swing.JList; import java.awt.Dimension; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Helper functions for OperatorUIs */ public final class OperatorUIUtils { public final static String SOURCE_BAND_NAMES = "sourceBandNames"; public static void initParamList(final JList paramList, final String[] availNames) { initParamList(paramList, availNames, null); } public static void initParamList(final JList paramList, final String[] availNames, final Object[] defaultSelection) { final List selectedValues = paramList.getSelectedValuesList(); paramList.removeAll(); paramList.setListData(availNames); paramList.setFixedCellWidth(200); paramList.setMinimumSize(new Dimension(50, 4)); final int size = paramList.getModel().getSize(); final List<Integer> indices = new ArrayList<>(size); for (Object selectedValue : selectedValues) { final String selValue = (String) selectedValue; for (int j = 0; j < size; ++j) { final String val = (String) paramList.getModel().getElementAt(j); if (val.equals(selValue)) { indices.add(j); break; } } } if (selectedValues.isEmpty() && defaultSelection != null) { int j = 0; for (String name : availNames) { for (Object defaultSel : defaultSelection) { if (name.equals(defaultSel.toString())) { indices.add(j); } } ++j; } } setSelectedListIndices(paramList, indices); } public static void setSelectedListIndices(final JList list, final List<Integer> indices) { final int[] selIndex = new int[indices.size()]; for (int i = 0; i < indices.size(); ++i) { selIndex[i] = indices.get(i); } list.setSelectedIndices(selIndex); } public static void updateParamList(final JList paramList, final Map<String, Object> paramMap, final String paramName) { final List selectedValues = paramList.getSelectedValuesList(); final String names[] = new String[selectedValues.size()]; int i = 0; for (Object selectedValue : selectedValues) { names[i++] = (String) selectedValue; } if(names.length == 0 && paramMap.get(paramName) != null) // don't overwrite with empty value return; paramMap.put(paramName, names); } public static double getNoDataValue(final File extFile) { try { final Product product = CommonReaders.readProduct(extFile); if (product != null) return product.getBandAt(0).getNoDataValue(); } catch (Exception e) { // } return 0; } }
3,831
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatorUIDescriptor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/OperatorUIDescriptor.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.graphbuilder.gpf.ui; /** * An <code>OperatorUI</code> is used as a user interface for an <code>Operator</code>. */ public interface OperatorUIDescriptor { String getId(); String getOperatorName(); Boolean disableFromGraphBuilder(); OperatorUI createOperatorUI(); }
1,032
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatorUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/OperatorUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import com.bc.ceres.binding.dom.XppDomElement; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.ui.AppContext; import javax.swing.JComponent; import java.util.Map; /** * An <code>OperatorUI</code> is used as a user interface for an <code>Operator</code>. */ public interface OperatorUI { String getOperatorName(); JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext); void initParameters(); UIValidation validateParameters(); void updateParameters(); void setSourceProducts(Product[] products); boolean hasSourceProducts(); void convertToDOM(XppDomElement parentElement) throws GraphException; Map<String, Object> getParameters(); }
1,562
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DefaultUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/DefaultUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.PropertyPane; import org.esa.snap.ui.AppContext; import javax.swing.JComponent; import javax.swing.JScrollPane; import java.util.Map; /** * Default OperatorUI for operators using @parameter */ public class DefaultUI extends BaseOperatorUI { @Override public JComponent CreateOpTab(final String operatorName, final Map<String, Object> parameterMap, final AppContext appContext) { initializeOperatorUI(operatorName, parameterMap); final BindingContext context = new BindingContext(propertySet); initParameters(); final PropertyPane parametersPane = new PropertyPane(context); return new JScrollPane(parametersPane.createPanel()); } @Override public void initParameters() { updateSourceBands(); } @Override public UIValidation validateParameters() { return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { } private void updateSourceBands() { if (propertySet == null) return; final Property[] properties = propertySet.getProperties(); for (Property p : properties) { final PropertyDescriptor descriptor = p.getDescriptor(); final String alias = descriptor.getAlias(); if (sourceProducts != null && alias != null && alias.equals("sourceBands")) { final String[] bandNames = getBandNames(); if (bandNames.length > 0) { final ValueSet valueSet = new ValueSet(bandNames); descriptor.setValueSet(valueSet); try { if (descriptor.getType().isArray()) { if (p.getValue() == null) p.setValue(bandNames);//new String[] {bandNames[0]}); } else { p.setValue(bandNames[0]); } } catch (ValidationException e) { System.out.println(e.toString()); } } } } } }
3,178
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BaseOperatorUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/BaseOperatorUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import com.bc.ceres.binding.*; import com.bc.ceres.binding.dom.DomConverter; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.binding.dom.XppDomElement; import com.thoughtworks.xstream.io.xml.xppdom.XppDom; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory; import org.esa.snap.core.gpf.descriptor.OperatorDescriptor; import org.esa.snap.core.gpf.descriptor.PropertySetDescriptorFactory; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.ui.AppContext; import javax.swing.*; import java.lang.reflect.Array; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.Set; /** * The abstract base class for all operator user interfaces intended to be extended by clients. * The following methods are intended to be implemented or overidden: * CreateOpTab() must be implemented in order to create the operator user interface component * User: lveci * Date: Feb 12, 2008 */ public abstract class BaseOperatorUI implements OperatorUI { protected PropertySet propertySet = null; protected Map<String, Object> paramMap = null; protected Product[] sourceProducts = null; protected String operatorName = ""; private static Converter getItemConverter(final Object obj) { return ConverterRegistry.getInstance().getConverter(obj.getClass()); } private static Converter getItemConverter(final PropertyDescriptor descriptor) { final Class<?> itemType = descriptor.getType().getComponentType(); Converter itemConverter = descriptor.getConverter(); if (itemConverter == null) { itemConverter = ConverterRegistry.getInstance().getConverter(itemType); } return itemConverter; } private static String getElementName(final Property p) { final String alias = p.getDescriptor().getAlias(); if (alias != null && !alias.isEmpty()) { return alias; } return p.getDescriptor().getName(); } public abstract JComponent CreateOpTab(final String operatorName, final Map<String, Object> parameterMap, final AppContext appContext); public abstract void initParameters(); public abstract UIValidation validateParameters(); public abstract void updateParameters(); public String getOperatorName() { return operatorName; } protected void initializeOperatorUI(final String operatorName, final Map<String, Object> parameterMap) { this.operatorName = operatorName; this.paramMap = parameterMap; final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName); if (operatorSpi == null) { throw new IllegalArgumentException("operator " + operatorName + " not found"); } final ParameterDescriptorFactory descriptorFactory = new ParameterDescriptorFactory(); final OperatorDescriptor operatorDescriptor = operatorSpi.getOperatorDescriptor(); final PropertySetDescriptor propertySetDescriptor; try { propertySetDescriptor = PropertySetDescriptorFactory.createForOperator(operatorDescriptor, descriptorFactory.getSourceProductMap()); } catch (ConversionException e) { throw new IllegalStateException("Not able to init OperatorParameterSupport.", e); } propertySet = PropertyContainer.createMapBacked(paramMap, propertySetDescriptor); if (paramMap.isEmpty()) { try { propertySet.setDefaultValues(); } catch (IllegalStateException e) { // todo - handle exception here e.printStackTrace(); } } } public void setSourceProducts(final Product[] products) { if (sourceProducts == null || !Arrays.equals(sourceProducts, products)) { sourceProducts = products; if (paramMap != null) { initParameters(); } } } public boolean hasSourceProducts() { return sourceProducts != null; } public void convertToDOM(final XppDomElement parentElement) throws GraphException { if (propertySet == null) { setParamsToConfiguration(parentElement.getXppDom()); return; } final Property[] properties = propertySet.getProperties(); for (Property p : properties) { final PropertyDescriptor descriptor = p.getDescriptor(); final DomConverter domConverter = descriptor.getDomConverter(); if (domConverter != null) { try { final DomElement childElement = parentElement.createChild(getElementName(p)); domConverter.convertValueToDom(p.getValue(), childElement); } catch (ConversionException e) { e.printStackTrace(); } } else { final String itemAlias = descriptor.getItemAlias(); if (descriptor.getType().isArray() && itemAlias != null && !itemAlias.isEmpty()) { final DomElement childElement = descriptor.getBooleanProperty("itemsInlined") ? parentElement : parentElement.createChild(getElementName(p)); final Object array = p.getValue(); final Converter itemConverter = getItemConverter(descriptor); if (array != null && itemConverter != null) { final int arrayLength = Array.getLength(array); for (int i = 0; i < arrayLength; i++) { final Object component = Array.get(array, i); final DomElement itemElement = childElement.createChild(itemAlias); final String text = itemConverter.format(component); if (text != null && !text.isEmpty()) { itemElement.setValue(text); } } } } else { final DomElement childElement = parentElement.createChild(getElementName(p)); final Object childValue = p.getValue(); final Converter converter = descriptor.getConverter(); if (converter == null) { throw new GraphException(operatorName + " BaseOperatorUI: no converter found for parameter " + descriptor.getName()); } String text = converter.format(childValue); if (text != null && !text.isEmpty()) { childElement.setValue(text); } } } } } /** * The method check if there are at least one multi-size source product * * @return false if there is not multi-size source product */ protected boolean hasMultiSizeProducts() { if (sourceProducts != null) { for (Product prod : sourceProducts) { if (prod.isMultiSize()) return true; } } return false; } protected String[] getBandNames() { final ArrayList<String> bandNames = new ArrayList<>(5); if (sourceProducts != null) { for (Product prod : sourceProducts) { if (sourceProducts.length > 1) { for (String name : prod.getBandNames()) { bandNames.add(name + "::" + prod.getName()); } } else { bandNames.addAll(Arrays.asList(prod.getBandNames())); } } } return bandNames.toArray(new String[0]); } protected String[] getGeometries() { final ArrayList<String> geometryNames = new ArrayList<>(5); if (sourceProducts != null) { for (Product prod : sourceProducts) { if (sourceProducts.length > 1) { for (String name : prod.getMaskGroup().getNodeNames()) { geometryNames.add(name + "::" + prod.getName()); } } else { geometryNames.addAll(Arrays.asList(prod.getMaskGroup().getNodeNames())); } } } return geometryNames.toArray(new String[geometryNames.size()]); } private void setParamsToConfiguration(final XppDom config) { if (paramMap == null) return; final Set<String> keys = paramMap.keySet(); // The set of keys in the map. for (String key : keys) { final Object value = paramMap.get(key); // Get the value for that key. if (value == null) continue; XppDom xml = config.getChild(key); if (xml == null) { xml = new XppDom(key); config.addChild(xml); } Converter itemConverter = getItemConverter(value); if (itemConverter != null) { final String text = itemConverter.format(value); if (text != null && !text.isEmpty()) { xml.setValue(text); } } else { xml.setValue(value.toString()); } } } @Override public Map<String, Object> getParameters() { return this.paramMap; } }
10,403
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DefaultOperatorUIDescriptor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/DefaultOperatorUIDescriptor.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.graphbuilder.gpf.ui; import com.bc.ceres.core.Assert; /** * Provides a standard implementation for {@link OperatorUIDescriptor}. */ public class DefaultOperatorUIDescriptor implements OperatorUIDescriptor { private String id; private String operatorName; private Boolean disableFromGraphBuilder; private Class<? extends OperatorUI> operatorUIClass; public DefaultOperatorUIDescriptor(final String id, final String operatorName, final Class<? extends OperatorUI> operatorUIClass, final Boolean disableFromGraphBuilder) { this.id = id; this.operatorName = operatorName; this.operatorUIClass = operatorUIClass; this.disableFromGraphBuilder = disableFromGraphBuilder; } public String getId() { return id; } public String getOperatorName() { return operatorName; } public Boolean disableFromGraphBuilder() { return disableFromGraphBuilder; } public OperatorUI createOperatorUI() { if(operatorUIClass == null) { return new DefaultUI(); } Object object; try { object = operatorUIClass.newInstance(); } catch (Throwable e) { throw new IllegalStateException("operatorUIClass.newInstance()", e); } Assert.state(object instanceof OperatorUI, "object instanceof operatorUI"); return (OperatorUI) object; } }
2,239
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductSetReaderOpUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/ProductSetReaderOpUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import org.esa.snap.graphbuilder.rcp.dialogs.ProductSetPanel; import org.esa.snap.graphbuilder.rcp.dialogs.support.FileTable; import org.esa.snap.ui.AppContext; import javax.swing.JComponent; import java.io.File; import java.util.Map; /** * Stack Reader Operator User Interface * User: lveci * Date: Feb 12, 2008 */ public class ProductSetReaderOpUI extends BaseOperatorUI { private final FileTable productSetTable = new FileTable(); @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { initializeOperatorUI(operatorName, parameterMap); ProductSetPanel panel = new ProductSetPanel(appContext, "", productSetTable, false, true); initParameters(); return panel; } @Override public void initParameters() { final String[] fList = (String[]) paramMap.get("fileList"); productSetTable.setFiles(fList); } @Override public UIValidation validateParameters() { return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { final File[] fileList = productSetTable.getFileList(); if (fileList.length == 0) return; final String[] fList = new String[fileList.length]; for (int i = 0; i < fileList.length; ++i) { if (fileList[i].getName().isEmpty()) fList[i] = ""; else fList[i] = fileList[i].getAbsolutePath(); } paramMap.put("fileList", fList); } public void setProductFileList(final File[] productFileList) { productSetTable.setFiles(productFileList); } }
2,456
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TargetUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/TargetUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import org.esa.snap.core.gpf.ui.TargetProductSelector; import org.esa.snap.core.gpf.ui.TargetProductSelectorModel; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.SaveProductAsAction; import org.esa.snap.ui.AppContext; import javax.swing.JComponent; import java.io.File; import java.util.Map; /** * Writer OperatorUI */ public class TargetUI extends BaseOperatorUI { TargetProductSelector targetProductSelector = null; private static final String FILE_PARAMETER = "file"; private static final String FORMAT_PARAMETER = "formatName"; private static final String defaultFileName = "target"; private String sourceProductName; private AppContext appContext; @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { paramMap = parameterMap; targetProductSelector = new TargetProductSelector(new TargetProductSelectorModel(), true); this.appContext = appContext; File saveDir = null; final Object value = paramMap.get(FILE_PARAMETER); if (value != null) { final File file = (File) value; saveDir = file.getParentFile(); } if (saveDir == null) { final String homeDirPath = SystemUtils.getUserHomeDir().getPath(); final String savePath = SnapApp.getDefault().getPreferences().get(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, homeDirPath); saveDir = new File(savePath); } targetProductSelector.getModel().setProductDir(saveDir); initParameters(); return targetProductSelector.createDefaultPanel(); } @Override public void initParameters() { assert (paramMap != null); String fileName = getDefaultFileName(); String format = "BEAM-DIMAP"; final Object formatValue = paramMap.get(FORMAT_PARAMETER); if (formatValue != null) { format = (String) formatValue; } if (fileName != null) { targetProductSelector.getProductNameTextField().setText(fileName); targetProductSelector.getModel().setProductName(fileName); targetProductSelector.getModel().setFormatName(format); } } private String getDefaultFileName() { String fileName = defaultFileName; final Object fileValue = paramMap.get(FILE_PARAMETER); if (fileValue != null) { final File file = (File) fileValue; fileName = FileUtils.getFilenameWithoutExtension(file); } if (sourceProducts != null && sourceProducts.length > 0) { boolean sourceProductsChange = false; if(!sourceProducts[0].getName().equals(sourceProductName)) { if(sourceProductName != null) { sourceProductsChange = true; } sourceProductName = sourceProducts[0].getName(); } if(fileName.equals(defaultFileName) || sourceProductsChange) { fileName = sourceProducts[0].getName(); } } return fileName; } @Override public UIValidation validateParameters() { final String productName = targetProductSelector.getModel().getProductName(); if (productName == null || productName.isEmpty()) return new UIValidation(UIValidation.State.ERROR, "productName not specified"); final File file = targetProductSelector.getModel().getProductFile(); if (file == null) return new UIValidation(UIValidation.State.ERROR, "Target file not specified"); final String productDir = targetProductSelector.getModel().getProductDir().getAbsolutePath(); SnapApp.getDefault().getPreferences().put(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, productDir); return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { if (targetProductSelector.getModel().getProductName() != null) { paramMap.put("file", targetProductSelector.getModel().getProductFile()); paramMap.put("formatName", targetProductSelector.getModel().getFormatName()); } } }
5,111
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SourceUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/SourceUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import com.bc.ceres.swing.selection.SelectionChangeEvent; import com.bc.ceres.swing.selection.SelectionChangeListener; import org.esa.snap.core.dataio.DecodeQualification; import org.esa.snap.core.dataio.ProductIOPlugInManager; import org.esa.snap.core.dataio.ProductReaderPlugIn; import org.esa.snap.core.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.gpf.ui.SourceProductSelector; import org.esa.snap.core.util.GeoUtils; import org.esa.snap.core.util.math.MathUtils; import org.esa.snap.engine_utilities.gpf.CommonReaders; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.loading.SwingUtils; import org.locationtech.jts.geom.Geometry; import javax.swing.*; import javax.swing.event.ChangeEvent; import java.awt.*; import java.awt.geom.Rectangle2D; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; /** * Reader OperatorUI */ public class SourceUI extends BaseOperatorUI { private static final int MIN_SCENE_VALUE = 0; private static final String FILE_PARAMETER = "file"; private static final String FORMAT_PARAMETER = "formatName"; private static final String USE_ADVANCED_OPTIONS_PARAMETER = "useAdvancedOptions"; private static final String BAND_LIST_PARAMETER = "bandNames"; private static final String MASK_LIST_PARAMETER = "maskNames"; private static final String PIXEL_REGION_PARAMETER = "pixelRegion"; private static final String GEOMETRY_REGION_PARAMETER = "geometryRegion"; private static final String COPY_METADATA_PARAMETER = "copyMetadata"; private static final String ANY_FORMAT = "Any Format"; private final JList bandList = new JList(); private final JList maskList = new JList(); SourceProductSelector sourceProductSelector = null; private JComboBox<String> formatNameComboBox = new JComboBox<>(); private JButton advancedOptionsBtn = new JButton("Advanced options"); private JPanel advancedOptionsPanel = new JPanel(new GridBagLayout()); private AtomicBoolean updatingUI = new AtomicBoolean(false); private JCheckBox copyMetadata = new JCheckBox("Copy Metadata", true); private JRadioButton pixelCoordRadio = new JRadioButton("Pixel Coordinates"); private JRadioButton geoCoordRadio = new JRadioButton("Geographic Coordinates"); private JPanel pixelPanel = new JPanel(new GridBagLayout()); private JPanel geoPanel = new JPanel(new GridBagLayout()); private JSpinner pixelCoordXSpinner; private JSpinner pixelCoordYSpinner; private JSpinner pixelCoordWidthSpinner; private JSpinner pixelCoordHeightSpinner; private JSpinner geoCoordWestLongSpinner; private JSpinner geoCoordEastLongSpinner; private JSpinner geoCoordNorthLatSpinner; private JSpinner geoCoordSouthLatSpinner; private static List<String> getFormatsForFile(final File file) { final Iterator<ProductReaderPlugIn> allReaderPlugIns = ProductIOPlugInManager.getInstance().getAllReaderPlugIns(); final List<String> formatNameList = new ArrayList<>(); while (allReaderPlugIns.hasNext()) { ProductReaderPlugIn reader = allReaderPlugIns.next(); String[] formatNames = reader.getFormatNames(); for (String formatName : formatNames) { if (file == null || reader.getDecodeQualification(file) != DecodeQualification.UNABLE && !formatNameList.contains(formatName)) { formatNameList.add(formatName); } } } formatNameList.sort(String::compareTo); formatNameList.add(0, ANY_FORMAT); return formatNameList; } @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { paramMap = parameterMap; sourceProductSelector = new SourceProductSelector(appContext); sourceProductSelector.initProducts(); sourceProductSelector.addSelectionChangeListener(new SourceSelectionChangeListener()); final JComponent panel = createPanel(); initParameters(); final Product selectedProduct = sourceProductSelector.getSelectedProduct(); if (selectedProduct != null) { updateFormatNamesCombo(selectedProduct.getFileLocation()); } return new JScrollPane(panel); } private void updateFormatNamesCombo(final File file) { if (file == null) { return; } final List<String> formatNameList = getFormatsForFile(file); formatNameComboBox.removeAllItems(); for (String format : formatNameList) { formatNameComboBox.addItem(format); } } @Override public void initParameters() { assert (paramMap != null); final Object fileValue = paramMap.get(FILE_PARAMETER); if (fileValue != null) { try { final File file = (File) fileValue; Product srcProduct = null; // check if product is already opened final Product[] openedProducts = SnapApp.getDefault().getProductManager().getProducts(); for (Product openedProduct : openedProducts) { if (file.equals(openedProduct.getFileLocation())) { srcProduct = openedProduct; break; } } if (srcProduct == null) { srcProduct = CommonReaders.readProduct(file); } if (sourceProductSelector.getSelectedProduct() == null || sourceProductSelector.getSelectedProduct().getFileLocation() != fileValue) { sourceProductSelector.setSelectedProduct(srcProduct); } } catch (IOException e) { // do nothing } } final Object formatValue = paramMap.get(FORMAT_PARAMETER); if (formatValue != null) { formatNameComboBox.setSelectedItem(formatValue); } else { formatNameComboBox.setSelectedItem(ANY_FORMAT); } } @Override public UIValidation validateParameters() { if (sourceProductSelector != null && sourceProductSelector.getSelectedProduct() == null) { return new UIValidation(UIValidation.State.ERROR, "Source product not selected"); } return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { if (sourceProductSelector != null) { final Product prod = sourceProductSelector.getSelectedProduct(); if (prod != null && prod.getFileLocation() != null) { File currentProductFileLocation = (File) paramMap.get(FILE_PARAMETER); paramMap.put(FILE_PARAMETER, prod.getFileLocation()); if (currentProductFileLocation == null || currentProductFileLocation != prod.getFileLocation()) { // sourceProducts from BaseOperatorUI should be populated in order to be able to later obtain getBandNames(), getGeometries(), // therefore calling setSourceProduct(prod); would not be enough, setSourceProducts() is needed setSourceProducts(new Product[]{prod}); OperatorUIUtils.initParamList(bandList, getBandNames()); OperatorUIUtils.initParamList(maskList, getGeometries()); pixelPanelChanged(); geoCodingChange(); } } } String selectedFormat = (String) formatNameComboBox.getSelectedItem(); if (selectedFormat != null && selectedFormat.equals(ANY_FORMAT)) { selectedFormat = null; } paramMap.put(FORMAT_PARAMETER, selectedFormat); paramMap.put(USE_ADVANCED_OPTIONS_PARAMETER, advancedOptionsPanel.isVisible()); OperatorUIUtils.updateParamList(bandList, paramMap, BAND_LIST_PARAMETER); OperatorUIUtils.updateParamList(maskList, paramMap, MASK_LIST_PARAMETER); paramMap.remove(PIXEL_REGION_PARAMETER); paramMap.remove(GEOMETRY_REGION_PARAMETER); if (pixelCoordRadio.isSelected()) { paramMap.put(PIXEL_REGION_PARAMETER, new Rectangle(((Number) pixelCoordXSpinner.getValue()).intValue(), ((Number) pixelCoordYSpinner.getValue()).intValue(), ((Number) pixelCoordWidthSpinner.getValue()).intValue(), ((Number) pixelCoordHeightSpinner.getValue()).intValue())); } if (geoCoordRadio.isSelected()) { paramMap.put(GEOMETRY_REGION_PARAMETER, getGeometry()); } paramMap.put(COPY_METADATA_PARAMETER, copyMetadata.isSelected()); } public void updateAdvancedOptionsUIAtProductChange() { if (sourceProductSelector != null) { advancedOptionsBtn.setEnabled(sourceProductSelector.getSelectedProduct() != null); final Product prod = sourceProductSelector.getSelectedProduct(); if (prod != null && prod.getFileLocation() != null) { File currentProductFileLocation = (File) paramMap.get(FILE_PARAMETER); if (currentProductFileLocation == null || currentProductFileLocation != prod.getFileLocation()) { // for same types of products (with identical band names) the selected bands/masks are kept, therefore clear the selection when input product changes bandList.clearSelection(); maskList.clearSelection(); // reset default visible coords panel pixelCoordRadio.setSelected(true); pixelPanel.setVisible(true); geoPanel.setVisible(false); // also reset pixel coords pixelCoordXSpinner.setValue(0); pixelCoordYSpinner.setValue(0); pixelCoordWidthSpinner.setValue(Integer.MAX_VALUE); pixelCoordHeightSpinner.setValue(Integer.MAX_VALUE); // trigger the calculation of product bounds pixelPanelChanged(); // sync geo coords syncLatLonWithXYParams(); } } } } public void setSourceProduct(final Product product) { if (sourceProductSelector != null) { sourceProductSelector.setSelectedProduct(product); if (product != null && product.getFileLocation() != null) { paramMap.put(FILE_PARAMETER, product.getFileLocation()); } } } private JComponent createPanel() { int gapBetweenRows = 10; int gapBetweenColumns = 10; initPixelCoordUIComponents(); initGeoCoordUIComponents(); createPixelPanel(gapBetweenColumns, gapBetweenRows); createGeoCodingPanel(gapBetweenColumns, gapBetweenRows); pixelCoordRadio.setSelected(true); pixelCoordRadio.setActionCommand("pixelCoordRadio"); geoCoordRadio.setActionCommand("geoCoordRadio"); ButtonGroup group = new ButtonGroup(); group.add(pixelCoordRadio); group.add(geoCoordRadio); advancedOptionsBtn.addActionListener(e -> { advancedOptionsPanel.setVisible(!advancedOptionsPanel.isVisible()); advancedOptionsBtn.setText(advancedOptionsPanel.isVisible() ? "Without Advanced options" : "Advanced options"); }); advancedOptionsBtn.setEnabled(sourceProductSelector.getSelectedProduct() != null); pixelCoordRadio.addActionListener(e -> { pixelPanel.setVisible(true); geoPanel.setVisible(false); }); geoCoordRadio.addActionListener(e -> { pixelPanel.setVisible(false); geoPanel.setVisible(true); }); JPanel contentPanel = new JPanel(new GridBagLayout()); GridBagConstraints gbc = SwingUtils.buildConstraints(0, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.WEST, 2, 1, 0, 0); JPanel productSelectionPanel = sourceProductSelector.createDefaultPanel(); productSelectionPanel.setMinimumSize(new Dimension(600, 70)); productSelectionPanel.setPreferredSize(new Dimension(600, 70)); contentPanel.add(productSelectionPanel, gbc); gbc = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); contentPanel.add(new JLabel("Data Format:"), gbc); gbc = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); formatNameComboBox.setToolTipText("Select 'Any Format' to let SNAP decide"); contentPanel.add(formatNameComboBox, gbc); gbc = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.WEST, 1, 1, gapBetweenRows, 0); contentPanel.add(advancedOptionsBtn, gbc); gbc = SwingUtils.buildConstraints(0, 3, GridBagConstraints.BOTH, GridBagConstraints.WEST, 2, 1, 0, 0); advancedOptionsPanel.setVisible(false); contentPanel.add(advancedOptionsPanel, gbc); gbc = SwingUtils.buildConstraints(0, 4, GridBagConstraints.BOTH, GridBagConstraints.WEST, 2, 1, 0, 0); contentPanel.add(new JPanel(), gbc); gbc = SwingUtils.buildConstraints(0, 0, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); advancedOptionsPanel.add(new JLabel("Source Bands:"), gbc); gbc = SwingUtils.buildConstraints(1, 0, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); advancedOptionsPanel.add(new JScrollPane(bandList), gbc); gbc = SwingUtils.buildConstraints(0, 1, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); advancedOptionsPanel.add(copyMetadata, gbc); gbc = SwingUtils.buildConstraints(0, 2, GridBagConstraints.NONE, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); advancedOptionsPanel.add(new JLabel("Source Masks:"), gbc); gbc = SwingUtils.buildConstraints(1, 2, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); advancedOptionsPanel.add(new JScrollPane(maskList), gbc); JPanel regionTypePanel = new JPanel(new GridLayout(1, 2)); regionTypePanel.add(pixelCoordRadio); regionTypePanel.add(geoCoordRadio); gbc = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 2, 1, gapBetweenRows, 0); advancedOptionsPanel.add(regionTypePanel, gbc); gbc = SwingUtils.buildConstraints(0, 4, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 2, 1, gapBetweenRows, 0); advancedOptionsPanel.add(pixelPanel, gbc); gbc = SwingUtils.buildConstraints(0, 5, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 2, 1, gapBetweenRows, 0); advancedOptionsPanel.add(geoPanel, gbc); geoPanel.setVisible(false); return contentPanel; } private void initPixelCoordUIComponents() { pixelCoordXSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 25)); pixelCoordXSpinner.getModel().setValue(MIN_SCENE_VALUE); pixelCoordXSpinner.setToolTipText("Start X co-ordinate given in pixels"); pixelCoordXSpinner.addChangeListener(this::updateUIStatePixelCoordsChanged); pixelCoordYSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 25)); pixelCoordYSpinner.getModel().setValue(MIN_SCENE_VALUE); pixelCoordYSpinner.setToolTipText("Start Y co-ordinate given in pixels"); pixelCoordYSpinner.addChangeListener(this::updateUIStatePixelCoordsChanged); pixelCoordWidthSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 25)); pixelCoordWidthSpinner.getModel().setValue(Integer.MAX_VALUE); pixelCoordWidthSpinner.setToolTipText("Product width"); pixelCoordWidthSpinner.addChangeListener(this::updateUIStatePixelCoordsChanged); pixelCoordHeightSpinner = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 25)); pixelCoordHeightSpinner.getModel().setValue(Integer.MAX_VALUE); pixelCoordHeightSpinner.setToolTipText("Product height"); pixelCoordHeightSpinner.addChangeListener(this::updateUIStatePixelCoordsChanged); } private void initGeoCoordUIComponents() { geoCoordNorthLatSpinner = new JSpinner(new SpinnerNumberModel(0.0, -90.0, 90.0, 1.0)); geoCoordNorthLatSpinner.getModel().setValue(90.0); geoCoordNorthLatSpinner.setToolTipText("North bound latitude (°)"); geoCoordNorthLatSpinner.addChangeListener(this::updateUIStateGeoCoordsChanged); geoCoordWestLongSpinner = new JSpinner(new SpinnerNumberModel(0.0, -180.0, 180.0, 1.0)); geoCoordWestLongSpinner.getModel().setValue(-180.0); geoCoordWestLongSpinner.setToolTipText("West bound longitude (°)"); geoCoordWestLongSpinner.addChangeListener(this::updateUIStateGeoCoordsChanged); geoCoordSouthLatSpinner = new JSpinner(new SpinnerNumberModel(0.0, -90.0, 90.0, 1.0)); geoCoordSouthLatSpinner.getModel().setValue(-90.0); geoCoordSouthLatSpinner.setToolTipText("South bound latitude (°)"); geoCoordSouthLatSpinner.addChangeListener(this::updateUIStateGeoCoordsChanged); geoCoordEastLongSpinner = new JSpinner(new SpinnerNumberModel(0.0, -180.0, 180.0, 1.0)); geoCoordEastLongSpinner.getModel().setValue(180.0); geoCoordEastLongSpinner.setToolTipText("East bound longitude (°)"); geoCoordEastLongSpinner.addChangeListener(this::updateUIStateGeoCoordsChanged); } private void createPixelPanel(int gapBetweenColumns, int gapBetweenRows) { GridBagConstraints pixgbc = SwingUtils.buildConstraints(0, 0, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 1, 1, 0, 0); pixelPanel.add(new JLabel("SceneX:"), pixgbc); pixgbc = SwingUtils.buildConstraints(1, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, 0, gapBetweenColumns); pixelPanel.add(pixelCoordXSpinner, pixgbc); pixgbc = SwingUtils.buildConstraints(0, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); pixelPanel.add(new JLabel("SceneY:"), pixgbc); pixgbc = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); pixelPanel.add(pixelCoordYSpinner, pixgbc); pixgbc = SwingUtils.buildConstraints(0, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); pixelPanel.add(new JLabel("Scene width:"), pixgbc); pixgbc = SwingUtils.buildConstraints(1, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); pixelPanel.add(pixelCoordWidthSpinner, pixgbc); pixgbc = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); pixelPanel.add(new JLabel("Scene height:"), pixgbc); pixgbc = SwingUtils.buildConstraints(1, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); pixelPanel.add(pixelCoordHeightSpinner, pixgbc); } private void createGeoCodingPanel(int gapBetweenColumns, int gapBetweenRows) { GridBagConstraints geobc = SwingUtils.buildConstraints(0, 0, GridBagConstraints.BOTH, GridBagConstraints.CENTER, 1, 1, 0, 0); geoPanel.add(new JLabel("North latitude bound:"), geobc); geobc = SwingUtils.buildConstraints(1, 0, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, 0, gapBetweenColumns); geoPanel.add(geoCoordNorthLatSpinner, geobc); geobc = SwingUtils.buildConstraints(0, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); geoPanel.add(new JLabel("West longitude bound:"), geobc); geobc = SwingUtils.buildConstraints(1, 1, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); geoPanel.add(geoCoordWestLongSpinner, geobc); geobc = SwingUtils.buildConstraints(0, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); geoPanel.add(new JLabel("South latitude bound:"), geobc); geobc = SwingUtils.buildConstraints(1, 2, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); geoPanel.add(geoCoordSouthLatSpinner, geobc); geobc = SwingUtils.buildConstraints(0, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, 0); geoPanel.add(new JLabel("East longitude bound:"), geobc); geobc = SwingUtils.buildConstraints(1, 3, GridBagConstraints.HORIZONTAL, GridBagConstraints.CENTER, 1, 1, gapBetweenRows, gapBetweenColumns); geoPanel.add(geoCoordEastLongSpinner, geobc); } private void updateUIStatePixelCoordsChanged(ChangeEvent event) { if (updatingUI.compareAndSet(false, true)) { try { if (event != null && pixelCoordRadio.isEnabled()) { pixelPanelChanged(); syncLatLonWithXYParams(); } } finally { updatingUI.set(false); } } } private void updateUIStateGeoCoordsChanged(ChangeEvent event) { if (updatingUI.compareAndSet(false, true)) { try { if (event != null && geoCoordRadio.isEnabled()) { geoCodingChange(); } } finally { updatingUI.set(false); } } } private void pixelPanelChanged() { int productWidth = 0; int productHeight = 0; if (sourceProductSelector != null) { final Product prod = sourceProductSelector.getSelectedProduct(); productWidth = prod.getSceneRasterWidth(); productHeight = prod.getSceneRasterHeight(); } int x1 = ((Number) pixelCoordXSpinner.getValue()).intValue(); int y1 = ((Number) pixelCoordYSpinner.getValue()).intValue(); int w = ((Number) pixelCoordWidthSpinner.getValue()).intValue(); int h = ((Number) pixelCoordHeightSpinner.getValue()).intValue(); if (x1 < 0) { x1 = 0; } if (x1 > productWidth - 2) { x1 = productWidth - 2; } if (y1 < 0) { y1 = 0; } if (y1 > productHeight - 2) { y1 = productHeight - 2; } if (w > productWidth) { w = productWidth; } if (x1 + w > productWidth) { if ((w - x1) >= 2) { w = w - x1; } else { w = productWidth - x1; } } if (h > productHeight) { h = productHeight; } if (y1 + h > productHeight) { if (h - y1 >= 2) { h = h - y1; } else { h = productHeight - y1; } } //reset fields values when the user writes wrong values pixelCoordXSpinner.setValue(0); pixelCoordYSpinner.setValue(0); pixelCoordWidthSpinner.setValue(w); pixelCoordHeightSpinner.setValue(h); pixelCoordXSpinner.setValue(x1); pixelCoordYSpinner.setValue(y1); pixelCoordWidthSpinner.setValue(w); pixelCoordHeightSpinner.setValue(h); } private void geoCodingChange() { final GeoPos geoPos1 = new GeoPos((Double) geoCoordNorthLatSpinner.getValue(), (Double) geoCoordWestLongSpinner.getValue()); final GeoPos geoPos2 = new GeoPos((Double) geoCoordSouthLatSpinner.getValue(), (Double) geoCoordEastLongSpinner.getValue()); updateXYParams(geoPos1, geoPos2); } private void syncLatLonWithXYParams() { GeoCoding geoCoding = null; if (sourceProductSelector != null) { final Product prod = sourceProductSelector.getSelectedProduct(); geoCoding = prod.getSceneGeoCoding(); } if (geoCoding != null) { final PixelPos pixelPos1 = new PixelPos((Integer) pixelCoordXSpinner.getValue(), (Integer) pixelCoordYSpinner.getValue()); int paramX2 = (Integer) pixelCoordWidthSpinner.getValue() + (Integer) pixelCoordXSpinner.getValue() - 1; int paramY2 = (Integer) pixelCoordHeightSpinner.getValue() + (Integer) pixelCoordYSpinner.getValue() - 1; final PixelPos pixelPos2 = new PixelPos(paramX2, paramY2); final GeoPos geoPos1 = geoCoding.getGeoPos(pixelPos1, null); final GeoPos geoPos2 = geoCoding.getGeoPos(pixelPos2, null); if (geoPos1.isValid()) { double lat = geoPos1.getLat(); lat = MathUtils.crop(lat, -90.0, 90.0); geoCoordNorthLatSpinner.setValue(lat); double lon = geoPos1.getLon(); lon = MathUtils.crop(lon, -180.0, 180.0); geoCoordWestLongSpinner.setValue(lon); } if (geoPos2.isValid()) { double lat = geoPos2.getLat(); lat = MathUtils.crop(lat, -90.0, 90.0); geoCoordSouthLatSpinner.setValue(lat); double lon = geoPos2.getLon(); lon = MathUtils.crop(lon, -180.0, 180.0); geoCoordEastLongSpinner.setValue(lon); } } } private void updateXYParams(GeoPos geoPos1, GeoPos geoPos2) { GeoCoding geoCoding = null; int productWidth = 0; int productHeight = 0; if (sourceProductSelector != null) { final Product prod = sourceProductSelector.getSelectedProduct(); geoCoding = prod.getSceneGeoCoding(); productWidth = prod.getSceneRasterWidth(); productHeight = prod.getSceneRasterHeight(); } if (geoCoding != null) { final PixelPos pixelPos1 = geoCoding.getPixelPos(geoPos1, null); if (!pixelPos1.isValid()) { pixelPos1.setLocation(0, 0); } final PixelPos pixelPos2 = geoCoding.getPixelPos(geoPos2, null); if (!pixelPos2.isValid()) { pixelPos2.setLocation(productWidth, productHeight); } final Rectangle.Float region = new Rectangle.Float(); region.setFrameFromDiagonal(pixelPos1.x, pixelPos1.y, pixelPos2.x, pixelPos2.y); final Rectangle.Float productBounds; productBounds = new Rectangle.Float(0, 0, productWidth, productHeight); Rectangle2D finalRegion = productBounds.createIntersection(region); if (isValueInNumericSpinnerRange(pixelCoordXSpinner, (int) finalRegion.getMinX())) { pixelCoordXSpinner.setValue((int) finalRegion.getMinX()); } if (isValueInNumericSpinnerRange(pixelCoordYSpinner, (int) finalRegion.getMinY())) { pixelCoordYSpinner.setValue((int) finalRegion.getMinY()); } int width = (int) (finalRegion.getMaxX() - finalRegion.getMinX()) + 1; int height = (int) (finalRegion.getMaxY() - finalRegion.getMinY()) + 1; if (isValueInNumericSpinnerRange(pixelCoordWidthSpinner, width)) { pixelCoordWidthSpinner.setValue(width); } if (isValueInNumericSpinnerRange(pixelCoordHeightSpinner, height)) { pixelCoordHeightSpinner.setValue(height); } } } private boolean isValueInNumericSpinnerRange(JSpinner spinner, Integer value) { final Integer min = (Integer) ((SpinnerNumberModel) spinner.getModel()).getMinimum(); final Integer max = (Integer) ((SpinnerNumberModel) spinner.getModel()).getMaximum(); return value >= min && value <= max; } private Geometry getGeometry() { GeoCoding geoCoding = null; int productWidth = 0; int productHeight = 0; if (sourceProductSelector != null) { final Product prod = sourceProductSelector.getSelectedProduct(); geoCoding = prod.getSceneGeoCoding(); productWidth = prod.getSceneRasterWidth(); productHeight = prod.getSceneRasterHeight(); } if (geoCoding != null) { final GeoPos geoPos1 = new GeoPos((Double) geoCoordNorthLatSpinner.getValue(), (Double) geoCoordWestLongSpinner.getValue()); final GeoPos geoPos2 = new GeoPos((Double) geoCoordSouthLatSpinner.getValue(), (Double) geoCoordEastLongSpinner.getValue()); final PixelPos pixelPos1 = geoCoding.getPixelPos(geoPos1, null); final PixelPos pixelPos2 = geoCoding.getPixelPos(geoPos2, null); final Rectangle.Float region = new Rectangle.Float(); region.setFrameFromDiagonal(pixelPos1.x, pixelPos1.y, pixelPos2.x, pixelPos2.y); final Rectangle.Float productBounds = new Rectangle.Float(0, 0, productWidth, productHeight); Rectangle2D finalRegion = productBounds.createIntersection(region); Rectangle bounds = new Rectangle((int) finalRegion.getMinX(), (int) finalRegion.getMinY(), (int) (finalRegion.getMaxX() - finalRegion.getMinX()) + 1, (int) (finalRegion.getMaxY() - finalRegion.getMinY()) + 1); return GeoUtils.computeGeometryUsingPixelRegion(geoCoding, bounds); } return null; } private class SourceSelectionChangeListener implements SelectionChangeListener { public void selectionChanged(SelectionChangeEvent event) { final Object selected = event.getSelection().getSelectedValue(); if (selected instanceof Product) { Product product = (Product) selected; if (product.getFileLocation() != null) { updateFormatNamesCombo(product.getFileLocation()); } } updateAdvancedOptionsUIAtProductChange(); updateParameters(); } public void selectionContextChanged(SelectionChangeEvent event) { //nothing to do } } }
31,525
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BandMathsOpUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/BandMathsOpUI.java
package org.esa.snap.graphbuilder.gpf.ui; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.datamodel.ProductNodeList; import org.esa.snap.core.dataop.barithm.BandArithmetic; import org.esa.snap.core.gpf.common.BandMathsOp; import org.esa.snap.core.jexp.ParseException; import org.esa.snap.core.param.ParamChangeEvent; import org.esa.snap.core.param.ParamChangeListener; import org.esa.snap.core.param.ParamProperties; import org.esa.snap.core.param.Parameter; import org.esa.snap.core.util.Debug; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.product.ProductExpressionPane; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.SwingUtilities; import java.awt.GridBagConstraints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Map; import java.util.Vector; /** User interface for BandMaths Operator */ public class BandMathsOpUI extends BaseOperatorUI { private static final String _PARAM_NAME_BAND = "targetBand"; private Parameter paramBand = null; private Parameter paramBandType = null; private Parameter paramBandUnit = null; private Parameter paramNoDataValue = null; private Parameter paramExpression = null; private Product targetProduct = null; private Band targetBand = null; private ProductNodeList<Product> productsList = null; private JButton editExpressionButton = null; private JComponent panel = null; private String errorText = ""; private AppContext appContext; private BandMathsOp.BandDescriptor bandDesc = new BandMathsOp.BandDescriptor(); @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { this.appContext = appContext; initializeOperatorUI(operatorName, parameterMap); initVariables(); panel = createUI(); initParameters(); return panel; } @Override public void initParameters() { Object[] bandDescriptors = (Object[])paramMap.get("targetBands"); if(bandDescriptors == null) bandDescriptors = (Object[])paramMap.get("targetBandDescriptors"); if(bandDescriptors != null && bandDescriptors.length > 0) { bandDesc = (BandMathsOp.BandDescriptor)(bandDescriptors[0]); bandDesc.type = ProductData.TYPESTRING_FLOAT32; try { paramBand.setValueAsText(bandDesc.name); paramBandType.setValueAsText(bandDesc.type); paramBandUnit.setValueAsText(bandDesc.unit != null ? bandDesc.unit : ""); paramNoDataValue.setValueAsText(String.valueOf(bandDesc.noDataValue)); paramExpression.setValueAsText(bandDesc.expression); } catch(Exception e) { SystemUtils.LOG.warning(e.getMessage()); } } if(sourceProducts != null && sourceProducts.length > 0) { targetProduct = sourceProducts[0]; targetBand = new Band(bandDesc.name, ProductData.TYPE_FLOAT32, targetProduct.getSceneRasterWidth(), targetProduct.getSceneRasterHeight()); targetBand.setDescription(""); //targetBand.setUnit(dialog.getNewBandsUnit()); productsList = new ProductNodeList<Product>(); for (Product prod : sourceProducts) { productsList.add(prod); } } else { targetProduct = null; targetBand = null; } updateUIState(paramBand.getName()); } @Override public UIValidation validateParameters() { if(!(targetProduct == null || isValidExpression())) return new UIValidation(UIValidation.State.ERROR, "Expression is invalid. "+ errorText); return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { bandDesc.name = paramBand.getValueAsText(); bandDesc.type = paramBandType.getValueAsText(); bandDesc.unit = paramBandUnit.getValueAsText(); String noDataValueStr = paramNoDataValue.getValueAsText(); bandDesc.noDataValue = noDataValueStr.isEmpty() ? 0 : Double.parseDouble(noDataValueStr); bandDesc.expression = paramExpression.getValueAsText(); final BandMathsOp.BandDescriptor[] bandDescriptors = new BandMathsOp.BandDescriptor[1]; bandDescriptors[0] = bandDesc; paramMap.put("targetBandDescriptors", bandDescriptors); } private void initVariables() { final ParamChangeListener paramChangeListener = createParamChangeListener(); BandMathsOp.BandDescriptor[] bandDescriptors = (BandMathsOp.BandDescriptor[])paramMap.get("targetBandDescriptors"); if(bandDescriptors != null && bandDescriptors.length > 0) { bandDesc = bandDescriptors[1]; } else { bandDesc.name = "newBand"; bandDesc.type = "float32"; } paramBand = new Parameter(_PARAM_NAME_BAND, bandDesc.name); paramBand.getProperties().setValueSetBound(false); paramBand.getProperties().setLabel("Target Band"); /*I18N*/ paramBand.addParamChangeListener(paramChangeListener); paramBandType = new Parameter("bandType", bandDesc.type); paramBandType.getProperties().setValueSetBound(false); paramBandType.getProperties().setLabel("Target Band Type"); /*I18N*/ paramBandType.addParamChangeListener(paramChangeListener); paramBandUnit = new Parameter("bandUnit", bandDesc.unit); paramBandUnit.getProperties().setValueSetBound(false); paramBandUnit.getProperties().setLabel("Band Unit"); /*I18N*/ paramBandUnit.addParamChangeListener(paramChangeListener); paramNoDataValue = new Parameter("bandNodataValue", bandDesc.noDataValue); paramNoDataValue.getProperties().setValueSetBound(false); paramNoDataValue.getProperties().setLabel("No-Data Value"); /*I18N*/ paramNoDataValue.addParamChangeListener(paramChangeListener); paramExpression = new Parameter("arithmetikExpr", bandDesc.expression); paramExpression.getProperties().setLabel("Expression"); /*I18N*/ paramExpression.getProperties().setDescription("Arithmetic expression"); /*I18N*/ paramExpression.getProperties().setNumRows(5); // paramExpression.getProperties().setEditorClass(ArithmetikExpressionEditor.class); // paramExpression.getProperties().setValidatorClass(BandArithmeticExprValidator.class); setArithmetikValues(); } private JComponent createUI() { editExpressionButton = new JButton("Edit Expression..."); editExpressionButton.setName("editExpressionButton"); editExpressionButton.addActionListener(createEditExpressionButtonListener()); final JPanel gridPanel = GridBagUtils.createPanel(); int line = 0; final GridBagConstraints gbc = new GridBagConstraints(); gbc.gridy = ++line; GridBagUtils.addToPanel(gridPanel, paramBand.getEditor().getLabelComponent(), gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(gridPanel, paramBand.getEditor().getComponent(), gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(gridPanel, paramBandType.getEditor().getLabelComponent(), gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(gridPanel, paramBandType.getEditor().getComponent(), gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(gridPanel, paramBandUnit.getEditor().getLabelComponent(), gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(gridPanel, paramBandUnit.getEditor().getComponent(), gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(gridPanel, paramNoDataValue.getEditor().getLabelComponent(), gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=WEST"); GridBagUtils.addToPanel(gridPanel, paramNoDataValue.getEditor().getComponent(), gbc, "weightx=1, insets.top=3, gridwidth=2, fill=HORIZONTAL, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(gridPanel, paramExpression.getEditor().getLabelComponent(), gbc, "weightx=0, insets.top=3, gridwidth=1, fill=HORIZONTAL, anchor=NORTHWEST"); GridBagUtils.addToPanel(gridPanel, paramExpression.getEditor().getComponent(), gbc, "weightx=1, weighty=1, insets.top=3, gridwidth=2, fill=BOTH, anchor=WEST"); gbc.gridy = ++line; GridBagUtils.addToPanel(gridPanel, editExpressionButton, gbc, "weighty=0, insets.top=3, gridwidth=3, fill=NONE, anchor=EAST"); return gridPanel; } private void setArithmetikValues() { final ParamProperties props = paramExpression.getProperties(); props.setPropertyValue(ParamProperties.COMP_PRODUCTS_FOR_BAND_ARITHMETHIK_KEY, getCompatibleProducts()); props.setPropertyValue(ParamProperties.SEL_PRODUCT_FOR_BAND_ARITHMETHIK_KEY, targetProduct); } private ParamChangeListener createParamChangeListener() { return new ParamChangeListener() { public void parameterValueChanged(ParamChangeEvent event) { updateUIState(event.getParameter().getName()); } }; } private Product[] getCompatibleProducts() { if (targetProduct == null) { return null; } final Vector<Product> compatibleProducts = new Vector<>(); compatibleProducts.add(targetProduct); final float geolocationEps = 180; Debug.trace("BandArithmetikDialog.geolocationEps = " + geolocationEps); Debug.trace("BandArithmetikDialog.getCompatibleProducts:"); Debug.trace(" comparing: " + targetProduct.getName()); for (int i = 0; i < productsList.size(); i++) { final Product product = productsList.getAt(i); if (targetProduct != product) { Debug.trace(" with: " + product.getDisplayName()); final boolean compatibleProduct = targetProduct.isCompatibleProduct(product, geolocationEps); Debug.trace(" result: " + compatibleProduct); if (compatibleProduct) { compatibleProducts.add(product); } } } return compatibleProducts.toArray(new Product[compatibleProducts.size()]); } private ActionListener createEditExpressionButtonListener() { return new ActionListener() { public void actionPerformed(ActionEvent e) { ProductExpressionPane pep = ProductExpressionPane.createGeneralExpressionPane(getCompatibleProducts(), targetProduct, appContext.getPreferences()); pep.setCode(paramExpression.getValueAsText()); int status = pep.showModalDialog(SwingUtilities.getWindowAncestor(panel), "Arithmetic Expression Editor"); if (status == ModalDialog.ID_OK) { paramExpression.setValue(pep.getCode(), null); Debug.trace("BandArithmetikDialog: expression is: " + pep.getCode()); bandDesc.expression = paramExpression.getValueAsText(); } pep.dispose(); pep = null; } }; } private boolean isValidExpression() { errorText = ""; final Product[] products = getCompatibleProducts(); if (products == null || products.length == 0) { return false; } String expression = paramExpression.getValueAsText(); if (expression == null || expression.length() == 0) { return false; } try { BandArithmetic.parseExpression(expression, products, 0); } catch (ParseException e) { errorText = e.getMessage(); return false; } return true; } private void updateUIState(String parameterName) { if (parameterName == null) { return; } if (parameterName.equals(_PARAM_NAME_BAND)) { final boolean b = targetProduct != null; paramExpression.setUIEnabled(b); editExpressionButton.setEnabled(b); paramBand.setUIEnabled(b); paramBandType.setUIEnabled(b); paramBandUnit.setUIEnabled(b); paramNoDataValue.setUIEnabled(b); if (b) { setArithmetikValues(); } final String selectedBandName = paramBand.getValueAsText(); if (b) { if (selectedBandName != null && selectedBandName.length() > 0) { targetBand = targetProduct.getBand(selectedBandName); } } } } }
13,780
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatorUIRegistry.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/OperatorUIRegistry.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.graphbuilder.gpf.ui; import com.bc.ceres.core.Assert; import org.esa.snap.core.util.SystemUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import org.openide.modules.ModuleInfo; import org.openide.util.Lookup; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; /** * An <code>OperatorUIRegistry</code> provides access to operator user interfaces as described by their OperatorUIDescriptor. */ public class OperatorUIRegistry { private static OperatorUIRegistry instance = null; private final Map<String, OperatorUIDescriptor> operatorUIDescriptors = new HashMap<>(); public OperatorUIRegistry() { registerOperatorUIs(); } public static OperatorUIRegistry getInstance() { if(instance == null) { instance = new OperatorUIRegistry(); } return instance; } public OperatorUIDescriptor[] getOperatorUIDescriptors() { return operatorUIDescriptors.values().toArray(new OperatorUIDescriptor[operatorUIDescriptors.values().size()]); } public OperatorUIDescriptor getOperatorUIDescriptor(final String operatorName) { return operatorUIDescriptors.get(operatorName); } private void registerOperatorUIs() { FileObject fileObj = FileUtil.getConfigFile("OperatorUIs"); if(fileObj == null) { SystemUtils.LOG.warning("No operatorUIs found."); return; } final FileObject[] files = fileObj.getChildren(); final List<FileObject> orderedFiles = FileUtil.getOrder(Arrays.asList(files), true); for (FileObject file : orderedFiles) { OperatorUIDescriptor operatorUIDescriptor = null; try { operatorUIDescriptor = createOperatorUIDescriptor(file); } catch (Exception e) { SystemUtils.LOG.severe(String.format("Failed to create operatorUI from layer.xml path '%s'", file.getPath())); } if (operatorUIDescriptor != null) { // must have only one operatorUI per operator final OperatorUIDescriptor existingDescriptor = operatorUIDescriptors.get(operatorUIDescriptor.getOperatorName()); if (existingDescriptor != null) { SystemUtils.LOG.info(String.format("OperatorUI [%s] has been redeclared for [%s]!\n", operatorUIDescriptor.getId(), operatorUIDescriptor.getOperatorName())); } operatorUIDescriptors.put(operatorUIDescriptor.getOperatorName(), operatorUIDescriptor); SystemUtils.LOG.fine(String.format("New operatorUI added from layer.xml path '%s': %s", file.getPath(), operatorUIDescriptor.getOperatorName())); } } } public static OperatorUIDescriptor createOperatorUIDescriptor(FileObject fileObject) { final String id = fileObject.getName(); final String operatorName = (String) fileObject.getAttribute("operatorName"); Assert.argument(operatorName != null && !operatorName.isEmpty(), "Missing attribute 'operatorName'"); final Class<? extends OperatorUI> operatorUIClass = getClassAttribute(fileObject, "operatorUIClass", OperatorUI.class, false); Boolean disableFromGraphBuilder = false; try { final String disableFromGraphBuilderStr = (String) fileObject.getAttribute("disableFromGraphBuilder"); if (disableFromGraphBuilderStr != null) { disableFromGraphBuilder = Boolean.parseBoolean(disableFromGraphBuilderStr); } } catch (Exception e) { SystemUtils.LOG.severe("OperatorUIRegistry: Unable to parse disableFromGraphBuilder "+e.toString()); //continue } return new DefaultOperatorUIDescriptor(id, operatorName, operatorUIClass, disableFromGraphBuilder); } public static OperatorUI CreateOperatorUI(final String operatorName) { final OperatorUIRegistry reg = OperatorUIRegistry.getInstance(); if (reg != null) { OperatorUIDescriptor desc = reg.getOperatorUIDescriptor(operatorName); if (desc != null) { return desc.createOperatorUI(); } desc = OperatorUIRegistry.getInstance().getOperatorUIDescriptor("DefaultUI"); if (desc != null) { return desc.createOperatorUI(); } } return new DefaultUI(); } public static boolean showInGraphBuilder(final String operatorName) { final OperatorUIRegistry reg = OperatorUIRegistry.getInstance(); if (reg != null) { OperatorUIDescriptor desc = reg.getOperatorUIDescriptor(operatorName); if (desc != null) { if(desc.disableFromGraphBuilder()) { SystemUtils.LOG.warning(operatorName + " disabled from GraphBuilder"); } return !desc.disableFromGraphBuilder(); } } return true; } public static <T> Class<T> getClassAttribute(FileObject fileObject, String attributeName, Class<T> expectedType, boolean required) { String className = (String) fileObject.getAttribute(attributeName); if (className == null || className.isEmpty()) { if (required) { throw new IllegalArgumentException(String.format("Missing attribute '%s' of type %s", attributeName, expectedType.getName())); } return null; } Collection<? extends ModuleInfo> modules = Lookup.getDefault().lookupAll(ModuleInfo.class); for (ModuleInfo module : modules) { if (module.isEnabled()) { try { Class<?> implClass = module.getClassLoader().loadClass(className); if (expectedType.isAssignableFrom(implClass)) { //noinspection unchecked return (Class<T>) implClass; } else { throw new IllegalArgumentException(String.format("Value %s of attribute '%s' must be a %s", implClass.getName(), attributeName, expectedType.getName())); } } catch (ClassNotFoundException e) { // it's ok, continue } } } return null; } }
7,703
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SubsetUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/SubsetUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import org.esa.snap.core.datamodel.Product; import org.locationtech.jts.awt.PointShapeFactory.X; import org.locationtech.jts.geom.Coordinate; import org.locationtech.jts.geom.Geometry; import org.locationtech.jts.geom.GeometryFactory; import org.locationtech.jts.geom.LinearRing; import org.locationtech.jts.io.WKTReader; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.graphbuilder.gpf.ui.worldmap.NestWorldMapPane; import org.esa.snap.graphbuilder.gpf.ui.worldmap.WorldMapUI; import org.esa.snap.graphbuilder.rcp.utils.DialogUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AppContext; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Rectangle; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Map; /** * User interface for Subset */ public class SubsetUI extends BaseOperatorUI { private final JList bandList = new JList(); private final JComboBox referenceCombo = new JComboBox(); private final JTextField regionX = new JTextField(""); private final JTextField regionY = new JTextField(""); private final JTextField width = new JTextField(""); private final JTextField height = new JTextField(""); private final JSpinner subSamplingX = new JSpinner(); private final JSpinner subSamplingY = new JSpinner(); private final JCheckBox copyMetadata = new JCheckBox("Copy Metadata", true); private final JRadioButton pixelCoordRadio = new JRadioButton("Pixel Coordinates"); private final JRadioButton geoCoordRadio = new JRadioButton("Geographic Coordinates"); private final JPanel pixelPanel = new JPanel(new GridBagLayout()); private final JPanel geoPanel = new JPanel(new BorderLayout()); private final WorldMapUI worldMapUI = new WorldMapUI(); private final JTextField geoText = new JTextField(""); private final JButton geoUpdateButton = new JButton("Update"); private Geometry geoRegion = null; private static final int MIN_SUBSET_SIZE = 1; private int getRasterReferenceWidth() { int w=1; if(sourceProducts!=null && referenceCombo.getSelectedItem()!=null) { if(sourceProducts[0].isMultiSize()) { w = sourceProducts[0].getBand((String) referenceCombo.getSelectedItem()).getRasterWidth(); } else { w = sourceProducts[0].getSceneRasterWidth(); } } return w; } private int getRasterReferenceHeight() { int h = 1; if(sourceProducts!=null && referenceCombo.getSelectedItem()!=null) { if(sourceProducts[0].isMultiSize()) { h = sourceProducts[0].getBand((String) referenceCombo.getSelectedItem()).getRasterHeight(); } else { h = sourceProducts[0].getSceneRasterHeight(); } } return h; } @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { initializeOperatorUI(operatorName, parameterMap); final JComponent panel = createPanel(); initParameters(); geoText.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateGeoRegion(); } }); geoUpdateButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateGeoRegion(); } }); width.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateROIx(); } }); height.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateROIy(); } }); regionX.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateROIx(); } }); regionY.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateROIy(); } }); //enable or disable referenceCombo depending on sourceProduct referenceCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { if (referenceCombo.isEnabled()) { updateParametersReferenceBand(); } } }); subSamplingX.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { updateParametersSubSamplingX(); } }); subSamplingY.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { updateParametersSubSamplingY(); } }); return new JScrollPane(panel); } @Override public void initParameters() { OperatorUIUtils.initParamList(bandList, getBandNames(), (Object[])paramMap.get("sourceBands")); String _oldSelected = (String) referenceCombo.getSelectedItem(); referenceCombo.removeAllItems(); for (int i = 0 ; i < bandList.getModel().getSize() ; i++) { String string = (String) bandList.getModel().getElementAt(i); referenceCombo.addItem(string); if (string.equals(_oldSelected)) { referenceCombo.setSelectedItem(string); } } final Rectangle region = (Rectangle)paramMap.get("region"); if(region != null) { regionX.setText(String.valueOf(region.x)); regionY.setText(String.valueOf(region.y)); width.setText(String.valueOf(region.width)); height.setText(String.valueOf(region.height)); } if (sourceProducts != null && sourceProducts.length > 0) { if (region == null || region.width == 0) width.setText(String.valueOf(sourceProducts[0].getSceneRasterWidth())); if (region == null || region.height == 0) height.setText(String.valueOf(sourceProducts[0].getSceneRasterHeight())); worldMapUI.getModel().setAutoZoomEnabled(true); worldMapUI.getModel().setProducts(sourceProducts); worldMapUI.getModel().setSelectedProduct(sourceProducts[0]); worldMapUI.getWorlMapPane().zoomToProduct(sourceProducts[0]); } Integer subSamplingXVal = (Integer) paramMap.get("subSamplingX"); if(subSamplingXVal != null) { subSamplingX.setValue(subSamplingXVal); } Integer subSamplingYVal = (Integer) paramMap.get("subSamplingY"); if(subSamplingYVal != null) { subSamplingY.setValue(subSamplingYVal); } geoRegion = (Geometry) paramMap.get("geoRegion"); if (geoRegion != null) { final Coordinate coord[] = geoRegion.getCoordinates(); worldMapUI.setSelectionStart((float) coord[0].y, (float) coord[0].x); worldMapUI.setSelectionEnd((float) coord[2].y, (float) coord[2].x); getGeoRegion(); geoCoordRadio.setSelected(true); pixelPanel.setVisible(false); geoPanel.setVisible(true); } //enable or disable referenceCombo depending on sourceProduct if(sourceProducts == null || sourceProducts.length == 0 || !sourceProducts[0].isMultiSize()) { referenceCombo.setEnabled(false); } else { referenceCombo.setEnabled(true); } } @Override public UIValidation validateParameters() { return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { OperatorUIUtils.updateParamList(bandList, paramMap, "bandNames"); paramMap.remove("referenceBand"); if(sourceProducts != null ) { for (Product prod : sourceProducts) { if (prod.isMultiSize()) { paramMap.put("referenceBand", (String) referenceCombo.getSelectedItem()); break; } } } int x=0, y=0, rasterReferenceWidth=1, rasterReferenceHeight=1,w=1,h=1; if(sourceProducts!=null && referenceCombo.getSelectedItem()!=null) { if(sourceProducts[0].isMultiSize()) { rasterReferenceWidth = sourceProducts[0].getBand((String) referenceCombo.getSelectedItem()).getRasterWidth(); rasterReferenceHeight = sourceProducts[0].getBand((String) referenceCombo.getSelectedItem()).getRasterHeight(); } else { rasterReferenceWidth = sourceProducts[0].getSceneRasterWidth(); rasterReferenceHeight = sourceProducts[0].getSceneRasterHeight(); } } Integer subSamplingXVal = (Integer) paramMap.get("subSamplingX"); Integer subSamplingYVal = (Integer) paramMap.get("subSamplingY"); SpinnerModel subSamplingXmodel = new SpinnerNumberModel(1,1, rasterReferenceWidth/MIN_SUBSET_SIZE+1,1); subSamplingX.setModel(subSamplingXmodel); SpinnerModel subSamplingYmodel = new SpinnerNumberModel(1,1, rasterReferenceHeight/MIN_SUBSET_SIZE+1,1); subSamplingY.setModel(subSamplingYmodel); if(subSamplingXVal != null) { subSamplingX.setValue(subSamplingXVal); } if(subSamplingYVal != null) { subSamplingY.setValue(subSamplingYVal); } final String subSamplingXStr = subSamplingX.getValue().toString(); if (subSamplingXStr != null && !subSamplingXStr.isEmpty()) paramMap.put("subSamplingX", Integer.parseInt(subSamplingXStr)); final String subSamplingYStr = subSamplingY.getValue().toString(); if (subSamplingYStr != null && !subSamplingYStr.isEmpty()) paramMap.put("subSamplingY", Integer.parseInt(subSamplingYStr)); final String regionXStr = regionX.getText(); if (regionXStr != null && !regionXStr.isEmpty()) x = Integer.parseInt(regionXStr); final String regionYStr = regionY.getText(); if (regionYStr != null && !regionYStr.isEmpty()) y = Integer.parseInt(regionYStr); final String widthStr = width.getText(); if (widthStr != null && !widthStr.isEmpty()) w = Integer.parseInt(widthStr); final String heightStr = height.getText(); if (heightStr != null && !heightStr.isEmpty()) h = Integer.parseInt(heightStr); paramMap.remove("geoRegion"); paramMap.remove("region"); getGeoRegion(); if (geoCoordRadio.isSelected() && geoRegion != null) { paramMap.put("geoRegion", geoRegion); } else if(sourceProducts!=null) { paramMap.put("region", new Rectangle(x,y,w,h)); } } public void updateROIorGeoRegion(int x, int y, int w, int h) { paramMap.remove("geoRegion"); paramMap.remove("region"); getGeoRegion(); if (geoCoordRadio.isSelected() && geoRegion != null) { paramMap.put("geoRegion", geoRegion); } else { paramMap.put("region", new Rectangle(x,y,w,h)); } paramMap.put("copyMetadata", copyMetadata.isSelected()); } public void updateParametersSubSamplingX() { final String subSamplingXStr = subSamplingX.getValue().toString(); if (subSamplingXStr != null && !subSamplingXStr.isEmpty()){ paramMap.put("subSamplingX", Integer.parseInt(subSamplingXStr)); } } public void updateParametersSubSamplingY() { final String subSamplingYStr = subSamplingY.getValue().toString(); if (subSamplingYStr != null && !subSamplingYStr.isEmpty()){ paramMap.put("subSamplingY", Integer.parseInt(subSamplingYStr)); } } public void updateROIx() { int rasterRefWidth = getRasterReferenceWidth(); int w = rasterRefWidth; int h = getRasterReferenceHeight(); int x = 0, y=0; final String widthStr = width.getText(); if (widthStr != null && !widthStr.isEmpty()) w = Integer.parseInt(widthStr); final String regionXStr = regionX.getText(); if (regionXStr != null && !regionXStr.isEmpty()) x = Integer.parseInt(regionXStr); if (w < 1) { w = 1; } if (x > w - 2) { x = w - 2; } if(w+x>rasterRefWidth) w=rasterRefWidth-x; width.setText(String.valueOf(w)); regionX.setText(String.valueOf(x)); final String regionYStr = regionY.getText(); if (regionYStr != null && !regionYStr.isEmpty()) y = Integer.parseInt(regionYStr); final String heightStr = height.getText(); if (heightStr != null && !heightStr.isEmpty()) h = Integer.parseInt(heightStr); updateROIorGeoRegion(x,y,w,h); } public void updateROIy() { int rasterRefHeight = getRasterReferenceHeight(); int h = rasterRefHeight; int w = getRasterReferenceWidth(); int y = 0, x = 0; final String heightStr = height.getText(); if (heightStr != null && !heightStr.isEmpty()) h = Integer.parseInt(heightStr); final String regionYStr = regionY.getText(); if (regionYStr != null && !regionYStr.isEmpty()) y = Integer.parseInt(regionYStr); if (h < 1) { h = 1; } if (y > h - 2) { y = h - 2; } if(h+y>rasterRefHeight) h=rasterRefHeight-y; height.setText(String.valueOf(h)); regionY.setText(String.valueOf(y)); final String regionXStr = regionX.getText(); if (regionXStr != null && !regionXStr.isEmpty()) x = Integer.parseInt(regionXStr); final String widthStr = width.getText(); if (widthStr != null && !widthStr.isEmpty()) w = Integer.parseInt(widthStr); updateROIorGeoRegion(x,y,w,h); } public void updateParametersReferenceBand() { paramMap.remove("referenceBand"); if(sourceProducts != null ) { for (Product prod : sourceProducts) { if (prod.isMultiSize()) { paramMap.put("referenceBand", (String) referenceCombo.getSelectedItem()); break; } } } int x=0, y=0, w=1, h=1; if(sourceProducts!=null && referenceCombo.getSelectedItem()!=null) { if(sourceProducts[0].isMultiSize()) { w = sourceProducts[0].getBand((String) referenceCombo.getSelectedItem()).getRasterWidth(); h = sourceProducts[0].getBand((String) referenceCombo.getSelectedItem()).getRasterHeight(); } else { w = sourceProducts[0].getSceneRasterWidth(); h = sourceProducts[0].getSceneRasterHeight(); } } Integer subSamplingXVal = (Integer) paramMap.get("subSamplingX"); Integer subSamplingYVal = (Integer) paramMap.get("subSamplingY"); SpinnerModel subSamplingXmodel = new SpinnerNumberModel(1,1, w/MIN_SUBSET_SIZE+1,1); subSamplingX.setModel(subSamplingXmodel); SpinnerModel subSamplingYmodel = new SpinnerNumberModel(1,1, h/MIN_SUBSET_SIZE+1,1); subSamplingY.setModel(subSamplingYmodel); if(subSamplingXVal != null) { subSamplingX.setValue(subSamplingXVal); } if(subSamplingYVal != null) { subSamplingY.setValue(subSamplingYVal); } paramMap.remove("geoRegion"); paramMap.remove("region"); final String regionXStr = regionX.getText(); if (regionXStr != null && !regionXStr.isEmpty()) x = Integer.parseInt(regionXStr); final String regionYStr = regionY.getText(); if (regionYStr != null && !regionYStr.isEmpty()) y = Integer.parseInt(regionYStr); final String widthStr = width.getText(); if (widthStr != null && !widthStr.isEmpty()) w = Integer.parseInt(widthStr); final String heightStr = height.getText(); if (heightStr != null && !heightStr.isEmpty()) h = Integer.parseInt(heightStr); getGeoRegion(); if (geoCoordRadio.isSelected() && geoRegion != null) { paramMap.put("geoRegion", geoRegion); } else { paramMap.put("region", new Rectangle(x,y,w,h)); } paramMap.put("copyMetadata", copyMetadata.isSelected()); final Rectangle region = (Rectangle)paramMap.get("region"); if(region != null) { regionX.setText(String.valueOf(x)); regionY.setText(String.valueOf(y)); width.setText(String.valueOf(w)); height.setText(String.valueOf(h)); } if (sourceProducts != null && sourceProducts.length > 0) { worldMapUI.getModel().setAutoZoomEnabled(true); worldMapUI.getModel().setProducts(sourceProducts); worldMapUI.getModel().setSelectedProduct(sourceProducts[0]); worldMapUI.getWorlMapPane().zoomToProduct(sourceProducts[0]); } geoRegion = (Geometry) paramMap.get("geoRegion"); if (geoRegion != null) { final Coordinate coord[] = geoRegion.getCoordinates(); worldMapUI.setSelectionStart((float) coord[0].y, (float) coord[0].x); worldMapUI.setSelectionEnd((float) coord[2].y, (float) coord[2].x); getGeoRegion(); geoCoordRadio.setSelected(true); pixelPanel.setVisible(false); geoPanel.setVisible(true); } } private JComponent createPanel() { final JPanel contentPane = new JPanel(new GridBagLayout()); final GridBagConstraints gbc = DialogUtils.createGridBagConstraints(); contentPane.add(new JLabel("Source Bands:"), gbc); gbc.fill = GridBagConstraints.BOTH; gbc.gridx = 1; contentPane.add(new JScrollPane(bandList), gbc); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.gridx = 0; gbc.gridy++; contentPane.add(copyMetadata, gbc); gbc.gridy++; contentPane.add(pixelCoordRadio, gbc); gbc.gridx = 1; contentPane.add(geoCoordRadio, gbc); gbc.gridy++; gbc.gridx = 0; contentPane.add(new JLabel("Reference band:"), gbc); gbc.gridx = 1; contentPane.add(referenceCombo, gbc); pixelCoordRadio.setSelected(true); pixelCoordRadio.setActionCommand("pixelCoordRadio"); geoCoordRadio.setActionCommand("geoCoordRadio"); ButtonGroup group = new ButtonGroup(); group.add(pixelCoordRadio); group.add(geoCoordRadio); RadioListener myListener = new RadioListener(); pixelCoordRadio.addActionListener(myListener); geoCoordRadio.addActionListener(myListener); final GridBagConstraints pixgbc = DialogUtils.createGridBagConstraints(); pixgbc.gridwidth = 1; pixgbc.fill = GridBagConstraints.BOTH; addComponent(pixelPanel, pixgbc, "X:", regionX, 0); addComponent(pixelPanel, pixgbc, "Y:", regionY, 2); pixgbc.gridy++; addComponent(pixelPanel, pixgbc, "Width:", width, 0); addComponent(pixelPanel, pixgbc, "height:", height, 2); pixgbc.gridy++; SpinnerModel subSamplingXmodel = new SpinnerNumberModel(1,1, 2,1); subSamplingX.setModel(subSamplingXmodel); SpinnerModel subSamplingYmodel = new SpinnerNumberModel(1,1, 2,1); subSamplingY.setModel(subSamplingYmodel); addComponent(pixelPanel, pixgbc, "Sub-sampling X:", subSamplingX, 0); addComponent(pixelPanel, pixgbc, "Sub-sampling Y:", subSamplingY, 2); pixelPanel.add(new JPanel(), pixgbc); final NestWorldMapPane worldPane = worldMapUI.getWorlMapPane(); worldPane.setPreferredSize(new Dimension(500, 130)); final JPanel geoTextPanel = new JPanel(new BorderLayout()); geoText.setColumns(45); geoTextPanel.add(geoText, BorderLayout.CENTER); geoTextPanel.add(geoUpdateButton, BorderLayout.EAST); geoPanel.add(worldPane, BorderLayout.CENTER); geoPanel.add(geoTextPanel, BorderLayout.SOUTH); gbc.gridx = 0; gbc.gridwidth = 2; gbc.gridy++; contentPane.add(pixelPanel, gbc); geoPanel.setVisible(false); contentPane.add(geoPanel, gbc); DialogUtils.fillPanel(contentPane, gbc); return contentPane; } public static JLabel addComponent(JPanel contentPane, GridBagConstraints gbc, String text, JComponent component, int pos) { gbc.gridx = pos; gbc.weightx = 0.5; final JLabel label = new JLabel(text); contentPane.add(label, gbc); gbc.gridx = pos+1; gbc.weightx = 2.0; contentPane.add(component, gbc); gbc.gridx = pos; gbc.weightx = 1.0; return label; } private class RadioListener implements ActionListener { public void actionPerformed(ActionEvent e) { if (e.getActionCommand().contains("pixelCoordRadio")) { pixelPanel.setVisible(true); geoPanel.setVisible(false); //reset geoRegion geoRegion = null; paramMap.put("geoRegion", geoRegion); } else { pixelPanel.setVisible(false); geoPanel.setVisible(true); } } } private void getGeoRegion() { geoRegion = null; geoText.setText(""); if (geoCoordRadio.isSelected()) { final GeoPos[] selectionBox = worldMapUI.getSelectionBox(); if (selectionBox != null) { final Coordinate[] coords = new Coordinate[selectionBox.length + 1]; for (int i = 0; i < selectionBox.length; ++i) { coords[i] = new Coordinate(selectionBox[i].getLon(), selectionBox[i].getLat()); } coords[selectionBox.length] = new Coordinate(selectionBox[0].getLon(), selectionBox[0].getLat()); final GeometryFactory geometryFactory = new GeometryFactory(); final LinearRing linearRing = geometryFactory.createLinearRing(coords); geoRegion = geometryFactory.createPolygon(linearRing, null); geoText.setText(geoRegion.toText()); } } } private void updateGeoRegion() { try { geoRegion = new WKTReader().read(geoText.getText()); final Coordinate coord[] = geoRegion.getCoordinates(); worldMapUI.setSelectionStart((float) coord[0].y, (float) coord[0].x); worldMapUI.setSelectionEnd((float) coord[2].y, (float) coord[2].x); worldMapUI.getWorlMapPane().revalidate(); worldMapUI.getWorlMapPane().getLayerCanvas().updateUI(); } catch (Exception e) { SnapApp.getDefault().handleError("UpdateGeoRegion error reading wkt", e); } } }
24,362
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ResamplingUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/ResamplingUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.ComponentAdapter; import com.bc.ceres.swing.binding.internal.ComboBoxAdapter; import org.esa.snap.core.datamodel.Band; import org.esa.snap.core.datamodel.CrsGeoCoding; import org.esa.snap.core.datamodel.GeoCoding; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeGroup; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.datamodel.TiePointGrid; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.common.resample.BandResamplingPreset; import org.esa.snap.core.gpf.common.resample.ResamplingPreset; import org.esa.snap.core.gpf.descriptor.OperatorDescriptor; import org.esa.snap.core.gpf.ui.OperatorParameterSupport; import org.esa.snap.core.gpf.ui.resample.BandsTreeModel; import org.esa.snap.core.gpf.ui.resample.ResamplingRowModel; import org.esa.snap.core.gpf.ui.resample.ResamplingUtils; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.SnapFileFilter; import org.esa.snap.tango.TangoIcons; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.SnapFileChooser; import org.netbeans.swing.outline.DefaultOutlineModel; import org.netbeans.swing.outline.Outline; import org.netbeans.swing.outline.OutlineModel; import javax.swing.*; import javax.swing.border.EmptyBorder; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Map; /** * User interface for Resampling */ public class ResamplingUI extends BaseOperatorUI { private final String REFERENCE_BAND_TOOLTIP_TEXT = "<html>Set the reference band.<br/>" + "All other bands will be resampled to match its size and resolution.</html>"; private final String TARGET_WIDTH_AND_HEIGHT_TOOLTIP_TEXT = "<html>Set explicitly the width and height of the resampled product.<br/>" + "This option is only available when all bands have the same offset.</html>"; private final String TARGET_RESOLUTION_TOOLTIP_TEXT = "<html>Define the target resolution of the resampled product.<br/>" + "This option is only available for products with a geocoding based on a cartographic map CRS.</html>"; private final String UPSAMPLING_METHOD_PARAMETER_NAME = "upsamplingMethod"; private final String DOWNSAMPLING_METHOD_PARAMETER_NAME = "downsamplingMethod"; private final String FLAGDOWNSAMPLING_METHOD_PARAMETER_NAME = "flagDownsamplingMethod"; private final String PYRAMID_LEVELS_PARAMETER_NAME = "resampleOnPyramidLevels"; private final String BAND_RESAMPLINGS_PARAMETER_NAME = "bandResamplings"; private ArrayList<String> listBands = new ArrayList(); int lastProductWidth = 0; int lastProductHeight = 0; private String referenceBandParam=null; private JRadioButton referenceBandButton; private JRadioButton widthAndHeightButton; private JRadioButton resolutionButton; private ReferenceBandNameBoxPanel referenceBandNameBoxPanel; private TargetWidthAndHeightPanel targetWidthAndHeightPanel; private TargetResolutionPanel targetResolutionPanel; private JComboBox upsamplingCombo = new JComboBox(); private JComboBox downsamplingCombo = new JComboBox(); private JComboBox flagDownsamplingCombo = new JComboBox(); private JCheckBox pyramidLevelCheckBox = new JCheckBox("Resample on pyramid levels (for faster imaging)"); private BindingContext bindingContext; private OperatorDescriptor operatorDescriptor; private OperatorParameterSupport parameterSupport; private boolean updatingTargetWidthAndHeight = false; private BandResamplingPreset[] bandResamplingPresets; private OutlineModel mdl = null; private JCheckBox advancedMethodCheckBox; private JPanel advancedMethodDefinitionPanel; private JPanel loadPresetPanel; private ResamplingRowModel resamplingRowModel = null; @Override public JComponent CreateOpTab(String operatorName, Map<String, Object> parameterMap, AppContext appContext) { OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName); if (operatorSpi == null) { throw new IllegalArgumentException("No SPI found for operator name '" + operatorName + "'"); } operatorDescriptor = operatorSpi.getOperatorDescriptor(); parameterSupport = new OperatorParameterSupport(operatorDescriptor); final PropertySet propertySet = parameterSupport.getPropertySet(); bindingContext = new BindingContext(propertySet); if (sourceProducts != null) { for (Band band : sourceProducts[0].getBands()) { listBands.add(band.getName()); } } initializeOperatorUI(operatorName, parameterMap); final JComponent panel = createPanel(); initParameters(); return new JScrollPane(panel); } @Override public void initParameters() { final Integer targetWidthParam = (Integer) paramMap.get("targetWidth"); final Integer targetHeightParam = (Integer) paramMap.get("targetHeight"); final Integer targetResolutionParam = (Integer) paramMap.get("targetResolution"); String referenceBandParamAux = (String) paramMap.get("referenceBand"); if(referenceBandParamAux == null) referenceBandParamAux = (String) paramMap.get("referenceBandName"); referenceBandParam = referenceBandParamAux; String upsamplingParam = (String) paramMap.get("upsampling"); if(upsamplingParam == null) upsamplingParam = (String) paramMap.get(UPSAMPLING_METHOD_PARAMETER_NAME); String downsamplingParam = (String) paramMap.get("downsampling"); if(downsamplingParam == null) downsamplingParam = (String) paramMap.get(DOWNSAMPLING_METHOD_PARAMETER_NAME); String flagDownParam = (String) paramMap.get("flagDownsampling"); if(flagDownParam == null) flagDownParam = (String) paramMap.get(FLAGDOWNSAMPLING_METHOD_PARAMETER_NAME); final Boolean pyramidParam = (Boolean) paramMap.get(PYRAMID_LEVELS_PARAMETER_NAME); if(targetWidthParam!=null && targetHeightParam!=null) { widthAndHeightButton.setSelected(true); referenceBandButton.setSelected(false); resolutionButton.setSelected(false); targetResolutionPanel.setEnabled(false); targetWidthAndHeightPanel.setEnabled(true); referenceBandNameBoxPanel.setEnabled(false); targetWidthAndHeightPanel.widthSpinner.setValue(targetWidthParam); targetWidthAndHeightPanel.heightSpinner.setValue(targetHeightParam); } else if (targetResolutionParam!=null) { widthAndHeightButton.setSelected(false); referenceBandButton.setSelected(false); resolutionButton.setSelected(true); targetResolutionPanel.setEnabled(true); targetWidthAndHeightPanel.setEnabled(false); referenceBandNameBoxPanel.setEnabled(false); targetResolutionPanel.resolutionSpinner.setValue(targetResolutionParam); } else if (referenceBandParam!=null) { widthAndHeightButton.setSelected(false); referenceBandButton.setSelected(true); resolutionButton.setSelected(false); targetResolutionPanel.setEnabled(false); targetWidthAndHeightPanel.setEnabled(false); referenceBandNameBoxPanel.setEnabled(true); referenceBandNameBoxPanel.referenceBandNameBox.setSelectedItem(referenceBandParam); } else { widthAndHeightButton.setSelected(false); referenceBandButton.setSelected(false); resolutionButton.setSelected(true); targetResolutionPanel.setEnabled(true); targetWidthAndHeightPanel.setEnabled(false); referenceBandNameBoxPanel.setEnabled(false); targetResolutionPanel.resolutionSpinner.setValue(100); } upsamplingCombo.setSelectedItem(upsamplingParam); downsamplingCombo.setSelectedItem(downsamplingParam); flagDownsamplingCombo.setSelectedItem(flagDownParam); pyramidLevelCheckBox.setSelected(pyramidParam); updateResamplingPreset(); if (hasSourceProducts()) { reactToSourceProductChange(sourceProducts[0]); referenceBandButton.setEnabled(true); } } @Override public UIValidation validateParameters() { return new UIValidation(UIValidation.State.OK, ""); } @Override public void updateParameters() { updateResamplingPreset(); paramMap.clear(); //if we use always target width and height because this way, there are no errors when changing sources (for example, the name of the band could not be found) if (referenceBandButton.isSelected() /*&& referenceBandNameBoxPanel.referenceBandNameBox.getSelectedItem() != null*/) { if(referenceBandNameBoxPanel.referenceBandNameBox.getSelectedItem() != null) { referenceBandParam = referenceBandNameBoxPanel.referenceBandNameBox.getSelectedItem().toString(); } paramMap.put("referenceBandName", referenceBandParam); paramMap.remove("targetResolution"); paramMap.remove("targetWidth"); paramMap.remove("targetHeight"); } else if (widthAndHeightButton.isSelected()) { paramMap.put("targetWidth", targetWidthAndHeightPanel.widthSpinner.getValue()); paramMap.put("targetHeight", targetWidthAndHeightPanel.heightSpinner.getValue()); paramMap.remove("targetResolution"); paramMap.remove("referenceBandName"); } else if (resolutionButton.isSelected()) { paramMap.put("targetResolution", targetResolutionPanel.resolutionSpinner.getValue()); paramMap.remove("referenceBandName"); paramMap.remove("targetWidth"); paramMap.remove("targetHeight"); } if(advancedMethodCheckBox.isSelected() && hasSourceProducts()) { paramMap.put(BAND_RESAMPLINGS_PARAMETER_NAME, generateBandResamplings (sourceProducts[0])); } else { paramMap.remove(BAND_RESAMPLINGS_PARAMETER_NAME); } paramMap.put(UPSAMPLING_METHOD_PARAMETER_NAME, upsamplingCombo.getSelectedItem()); paramMap.put(DOWNSAMPLING_METHOD_PARAMETER_NAME, downsamplingCombo.getSelectedItem()); paramMap.put(FLAGDOWNSAMPLING_METHOD_PARAMETER_NAME,flagDownsamplingCombo.getSelectedItem()); paramMap.put(PYRAMID_LEVELS_PARAMETER_NAME, pyramidLevelCheckBox.isSelected()); } private String generateBandResamplings(Product sourceProduct) { updateResamplingPreset(); String bandResamplingsString = ""; for(String bandName : sourceProduct.getBandNames()) { for(BandResamplingPreset bandResamplingPreset : bandResamplingPresets) { if(bandResamplingPreset.getBandName().equals(bandName)){ if(!bandResamplingsString.isEmpty()) { bandResamplingsString = bandResamplingsString + ResamplingPreset.STRING_SEPARATOR; } bandResamplingsString = bandResamplingsString + bandResamplingPreset.getBandName() + BandResamplingPreset.SEPARATOR + bandResamplingPreset.getDownsamplingAlias() + BandResamplingPreset.SEPARATOR + bandResamplingPreset.getUpsamplingAlias(); } } } return bandResamplingsString; } private void updateResamplingPreset() { if(bandResamplingPresets == null) { return; } for (BandResamplingPreset bandResamplingPreset : bandResamplingPresets) { bandResamplingPreset.setUpsamplingAlias((String) resamplingRowModel.getValueFor(bandResamplingPreset.getBandName(),0)); bandResamplingPreset.setDownsamplingAlias((String) resamplingRowModel.getValueFor(bandResamplingPreset.getBandName(),1)); } } private JComponent createPanel() { final PropertySet propertySet = bindingContext.getPropertySet(); final TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTableWeightX(1.0); tableLayout.setTablePadding(4, 4); final GridLayout defineTargetResolutionPanelLayout = new GridLayout(3, 2); defineTargetResolutionPanelLayout.setVgap(4); final JPanel defineTargetSizePanel = new JPanel(defineTargetResolutionPanelLayout); defineTargetSizePanel.setBorder(BorderFactory.createTitledBorder("Define size of resampled product")); final ButtonGroup targetSizeButtonGroup = new ButtonGroup(); referenceBandButton = new JRadioButton("By reference band from source product:"); referenceBandButton.setToolTipText(REFERENCE_BAND_TOOLTIP_TEXT); widthAndHeightButton = new JRadioButton("By target width and height:"); widthAndHeightButton.setToolTipText(TARGET_WIDTH_AND_HEIGHT_TOOLTIP_TEXT); resolutionButton = new JRadioButton("By pixel resolution (in m):"); resolutionButton.setToolTipText(TARGET_RESOLUTION_TOOLTIP_TEXT); targetSizeButtonGroup.add(referenceBandButton); targetSizeButtonGroup.add(widthAndHeightButton); targetSizeButtonGroup.add(resolutionButton); defineTargetSizePanel.add(referenceBandButton); referenceBandNameBoxPanel = new ReferenceBandNameBoxPanel(); defineTargetSizePanel.add(referenceBandNameBoxPanel); defineTargetSizePanel.add(widthAndHeightButton); targetWidthAndHeightPanel = new TargetWidthAndHeightPanel(); defineTargetSizePanel.add(targetWidthAndHeightPanel); defineTargetSizePanel.add(resolutionButton); targetResolutionPanel = new TargetResolutionPanel(); defineTargetSizePanel.add(targetResolutionPanel); referenceBandButton.addActionListener(e -> { if (referenceBandButton.isSelected()) { referenceBandNameBoxPanel.setEnabled(true); targetWidthAndHeightPanel.setEnabled(false); targetResolutionPanel.setEnabled(false); } }); widthAndHeightButton.addActionListener(e -> { if (widthAndHeightButton.isSelected()) { referenceBandNameBoxPanel.setEnabled(false); targetWidthAndHeightPanel.setEnabled(true); targetResolutionPanel.setEnabled(false); } }); resolutionButton.addActionListener(e -> { if (resolutionButton.isSelected()) { referenceBandNameBoxPanel.setEnabled(false); targetWidthAndHeightPanel.setEnabled(false); targetResolutionPanel.setEnabled(true); } }); referenceBandButton.setSelected(true); final TableLayout tableLayoutMethodDefinition = new TableLayout(1); tableLayoutMethodDefinition.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayoutMethodDefinition.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayoutMethodDefinition.setTableWeightX(1.0); tableLayoutMethodDefinition.setTablePadding(4, 4); JPanel methodDefinitionPanel = new JPanel(tableLayoutMethodDefinition); methodDefinitionPanel.setBorder(BorderFactory.createTitledBorder("Define resampling algorithm")); JPanel upsamplingMethodPanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorUp = propertySet.getProperty(UPSAMPLING_METHOD_PARAMETER_NAME).getDescriptor(); JLabel upsamplingMethodLabel = new JLabel(descriptorUp.getAttribute("displayName").toString()); upsamplingMethodLabel.setToolTipText(descriptorUp.getAttribute("description").toString()); upsamplingMethodPanel.add(upsamplingMethodLabel); ComponentAdapter adapterUp = new ComboBoxAdapter(upsamplingCombo); bindingContext.bind(descriptorUp.getName(), adapterUp); upsamplingMethodPanel.add(upsamplingCombo); JPanel downsamplingMethodPanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorDown = propertySet.getProperty(DOWNSAMPLING_METHOD_PARAMETER_NAME).getDescriptor(); JLabel downsamplingMethodLabel = new JLabel(descriptorDown.getAttribute("displayName").toString()); downsamplingMethodPanel.setToolTipText(descriptorDown.getAttribute("description").toString()); downsamplingMethodPanel.add(downsamplingMethodLabel); ComponentAdapter adapterDown = new ComboBoxAdapter(downsamplingCombo); bindingContext.bind(descriptorDown.getName(), adapterDown); downsamplingMethodPanel.add(downsamplingCombo); JPanel flagDownsamplingMethodPanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorFlag = propertySet.getProperty(FLAGDOWNSAMPLING_METHOD_PARAMETER_NAME).getDescriptor(); JLabel flagDownsamplingMethodLabel = new JLabel(descriptorFlag.getAttribute("displayName").toString()); flagDownsamplingMethodPanel.setToolTipText(descriptorFlag.getAttribute("description").toString()); flagDownsamplingMethodPanel.add(flagDownsamplingMethodLabel); ComponentAdapter adapterFlag = new ComboBoxAdapter(flagDownsamplingCombo); bindingContext.bind(descriptorFlag.getName(), adapterFlag); flagDownsamplingMethodPanel.add(flagDownsamplingCombo); advancedMethodDefinitionPanel = new JPanel(tableLayoutMethodDefinition); if(hasSourceProducts()) { BandsTreeModel myModel = new BandsTreeModel(sourceProducts[0]); bandResamplingPresets = new BandResamplingPreset[myModel.getTotalRows()]; for(int i = 0 ; i < myModel.getTotalRows() ; i++) { bandResamplingPresets[i] = new BandResamplingPreset(myModel.getRows()[i], (String) paramMap.get(DOWNSAMPLING_METHOD_PARAMETER_NAME), (String) paramMap.get(UPSAMPLING_METHOD_PARAMETER_NAME)); } //Create the Outline's model, consisting of the TreeModel and the RowModel, resamplingRowModel = new ResamplingRowModel(bandResamplingPresets, myModel); mdl = DefaultOutlineModel.createOutlineModel( myModel, resamplingRowModel, true, "Bands"); //Initialize the Outline object: Outline outline1 = new Outline(); //By default, the root is shown, while here that isn't necessary: outline1.setRootVisible(false); //Assign the model to the Outline object: outline1.setModel(mdl); ResamplingUtils.setUpUpsamplingColumn(outline1,outline1.getColumnModel().getColumn(1), descriptorUp.getDefaultValue().toString()); ResamplingUtils.setUpDownsamplingColumn(outline1,outline1.getColumnModel().getColumn(2), descriptorDown.getDefaultValue().toString()); JScrollPane tableContainer = new JScrollPane(outline1); advancedMethodDefinitionPanel.add(tableContainer); advancedMethodDefinitionPanel.setVisible(false); } //panel load and save button loadPresetPanel = createLoadSavePresetPanel(); methodDefinitionPanel.add(upsamplingMethodPanel); methodDefinitionPanel.add(tableLayout.createVerticalSpacer()); methodDefinitionPanel.add(downsamplingMethodPanel); methodDefinitionPanel.add(tableLayout.createVerticalSpacer()); methodDefinitionPanel.add(flagDownsamplingMethodPanel); methodDefinitionPanel.add(tableLayout.createVerticalSpacer()); methodDefinitionPanel.add(createAdvancedCheckBoxPanel()); methodDefinitionPanel.add(advancedMethodDefinitionPanel); methodDefinitionPanel.add(loadPresetPanel); JPanel resampleOnPyramidLevelsPanel = new JPanel(new GridLayout(1, 2)); PropertyDescriptor descriptorResampleOnPyramidLevels = propertySet.getProperty(PYRAMID_LEVELS_PARAMETER_NAME).getDescriptor(); pyramidLevelCheckBox.setSelected((boolean) descriptorResampleOnPyramidLevels.getAttribute("defaultValue")); pyramidLevelCheckBox.setText(descriptorResampleOnPyramidLevels.getAttribute("displayName").toString()); pyramidLevelCheckBox.setToolTipText(descriptorResampleOnPyramidLevels.getAttribute("description").toString()); resampleOnPyramidLevelsPanel.add(pyramidLevelCheckBox); final JPanel parametersPanel = new JPanel(tableLayout); parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); parametersPanel.add(defineTargetSizePanel); //parametersPanel.add(upsamplingMethodPanel); //parametersPanel.add(downsamplingMethodPanel); //parametersPanel.add(flagDownsamplingMethodPanel); parametersPanel.add(methodDefinitionPanel); parametersPanel.add(resampleOnPyramidLevelsPanel); parametersPanel.add(tableLayout.createVerticalSpacer()); return parametersPanel; } private void reactToSourceProductChange(Product product) { if(product != null && hasChangedProductListBand(product)) { BandsTreeModel myModel = new BandsTreeModel(product); boolean changebandResamplingPresets = false; if (bandResamplingPresets == null ){ changebandResamplingPresets = true; } else { if(bandResamplingPresets.length != myModel.getTotalRows()) { changebandResamplingPresets = true; } for(String row : myModel.getRows()) { if(row.equals("Bands") || product.getAutoGrouping().contains(row)) { continue; } boolean found = false; for(BandResamplingPreset bandResamplingPreset : bandResamplingPresets) { if (bandResamplingPreset.getBandName().equals(row) ) { found = true; break; } } if(!found) { changebandResamplingPresets = true; break; } } } advancedMethodDefinitionPanel.removeAll(); if (changebandResamplingPresets) { bandResamplingPresets = new BandResamplingPreset[myModel.getTotalRows()]; for (int i = 0; i < myModel.getTotalRows(); i++) { bandResamplingPresets[i] = new BandResamplingPreset(myModel.getRows()[i], (String) paramMap.get(DOWNSAMPLING_METHOD_PARAMETER_NAME), (String) paramMap.get(UPSAMPLING_METHOD_PARAMETER_NAME)); } } resamplingRowModel = new ResamplingRowModel(bandResamplingPresets, myModel); mdl = DefaultOutlineModel.createOutlineModel(myModel, resamplingRowModel, true, "Products"); //Initialize the Outline object: Outline outline1 = new Outline(); outline1.setRootVisible(false); outline1.setModel(mdl); ResamplingUtils.setUpUpsamplingColumn(outline1, outline1.getColumnModel().getColumn(1),null); ResamplingUtils.setUpDownsamplingColumn(outline1, outline1.getColumnModel().getColumn(2),null); for(BandResamplingPreset bandResamplingPreset : bandResamplingPresets) { resamplingRowModel.setValueFor(bandResamplingPreset.getBandName(),0,bandResamplingPreset.getUpsamplingAlias()); resamplingRowModel.setValueFor(bandResamplingPreset.getBandName(),1,bandResamplingPreset.getDownsamplingAlias()); advancedMethodDefinitionPanel.repaint(); } JScrollPane tableContainer = new JScrollPane(outline1); advancedMethodDefinitionPanel.add(tableContainer); advancedMethodDefinitionPanel.revalidate(); advancedMethodDefinitionPanel.setVisible(advancedMethodCheckBox.isSelected()); } if(hasChangedProductListBand(product)) { updateListBands(product); referenceBandNameBoxPanel.reactToSourceProductChange(product); } if(hasChangedProductSize(product)) { updateProductSize(product); targetWidthAndHeightPanel.reactToSourceProductChange(product); targetResolutionPanel.reactToSourceProductChange(product); } if (product != null) { referenceBandButton.setEnabled(product.getBandNames().length > 0); final ProductNodeGroup<Band> productBands = product.getBandGroup(); final ProductNodeGroup<TiePointGrid> productTiePointGrids = product.getTiePointGridGroup(); double xOffset = Double.NaN; double yOffset = Double.NaN; if (productBands.getNodeCount() > 0) { xOffset = productBands.get(0).getImageToModelTransform().getTranslateX(); yOffset = productBands.get(0).getImageToModelTransform().getTranslateY(); } else if (productTiePointGrids.getNodeCount() > 0) { xOffset = productTiePointGrids.get(0).getImageToModelTransform().getTranslateX(); yOffset = productTiePointGrids.get(0).getImageToModelTransform().getTranslateY(); } boolean allowToSetWidthAndHeight = true; if (!Double.isNaN(xOffset) && !Double.isNaN(yOffset)) { allowToSetWidthAndHeight = allOffsetsAreEqual(productBands, xOffset, yOffset) && allOffsetsAreEqual(productTiePointGrids, xOffset, yOffset); } widthAndHeightButton.setEnabled(allowToSetWidthAndHeight); final GeoCoding sceneGeoCoding = product.getSceneGeoCoding(); boolean resolutionEnable = sceneGeoCoding != null && sceneGeoCoding instanceof CrsGeoCoding; resolutionButton.setEnabled(resolutionEnable); if(resolutionButton.isSelected() && !resolutionEnable) { targetResolutionPanel.setEnabled(false); targetWidthAndHeightPanel.setEnabled(true); widthAndHeightButton.setSelected(true); } } } private RasterDataNode getAnyRasterDataNode(Product product) { RasterDataNode node = null; if (product != null) { final ProductNodeGroup<Band> bandGroup = product.getBandGroup(); if (bandGroup.getNodeCount() == 0) { final ProductNodeGroup<TiePointGrid> tiePointGridGroup = product.getTiePointGridGroup(); if (tiePointGridGroup.getNodeCount() > 0) { node = tiePointGridGroup.get(0); } } else { node = bandGroup.get(0); } } return node; } private boolean allOffsetsAreEqual(ProductNodeGroup productNodeGroup, double xOffset, double yOffset) { for (int i = 0; i < productNodeGroup.getNodeCount(); i++) { final double nodeXOffset = ((RasterDataNode) productNodeGroup.get(i)).getImageToModelTransform().getTranslateX(); final double nodeYOffset = ((RasterDataNode) productNodeGroup.get(i)).getImageToModelTransform().getTranslateY(); if (Math.abs(nodeXOffset - xOffset) > 1e-8 || Math.abs(nodeYOffset - yOffset) > 1e-8) { return false; } } return true; } private class TargetResolutionPanel extends JPanel { private JSpinner resolutionSpinner; private JLabel targetResolutionTargetWidthLabel; private JLabel targetResolutionTargetHeightLabel; private final JLabel targetResolutionTargetWidthNameLabel; private final JLabel targetResolutionNameTargetHeightLabel; TargetResolutionPanel() { setToolTipText(TARGET_RESOLUTION_TOOLTIP_TEXT); resolutionSpinner = new JSpinner(new SpinnerNumberModel(1, 1, Integer.MAX_VALUE, 1)); resolutionSpinner.setEnabled(false); resolutionSpinner.addChangeListener(e -> updateTargetResolutionTargetWidthAndHeight()); final GridLayout layout = new GridLayout(3, 1); layout.setVgap(2); setLayout(layout); JPanel targetResolutionTargetWidthPanel = new JPanel(new GridLayout(1, 2)); targetResolutionTargetWidthNameLabel = new JLabel("Resulting target width: "); targetResolutionTargetWidthNameLabel.setEnabled(false); targetResolutionTargetWidthPanel.add(targetResolutionTargetWidthNameLabel); targetResolutionTargetWidthLabel = new JLabel(); targetResolutionTargetWidthLabel.setEnabled(false); targetResolutionTargetWidthPanel.add(targetResolutionTargetWidthLabel); JPanel targetResolutionTargetHeightPanel = new JPanel(new GridLayout(1, 2)); targetResolutionNameTargetHeightLabel = new JLabel("Resulting target height: "); targetResolutionNameTargetHeightLabel.setEnabled(false); targetResolutionTargetHeightPanel.add(targetResolutionNameTargetHeightLabel); targetResolutionTargetHeightLabel = new JLabel(); targetResolutionTargetHeightLabel.setEnabled(false); targetResolutionTargetHeightPanel.add(targetResolutionTargetHeightLabel); add(resolutionSpinner); add(targetResolutionTargetWidthPanel); add(targetResolutionTargetHeightPanel); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); resolutionSpinner.setEnabled(enabled); targetResolutionTargetWidthLabel.setEnabled(enabled); targetResolutionTargetHeightLabel.setEnabled(enabled); targetResolutionTargetWidthNameLabel.setEnabled(enabled); targetResolutionNameTargetHeightLabel.setEnabled(enabled); if (enabled) { updateTargetResolutionTargetWidthAndHeight(); } } private void updateTargetResolutionTargetWidthAndHeight() { if (hasSourceProducts()) { final Product selectedProduct = sourceProducts[0]; final RasterDataNode node = getAnyRasterDataNode(selectedProduct); int targetWidth = 0; int targetHeight = 0; if (node != null) { final int resolution = Integer.parseInt(resolutionSpinner.getValue().toString()); final double nodeResolution = node.getImageToModelTransform().getScaleX(); targetWidth = (int) (node.getRasterWidth() * (nodeResolution / resolution)); targetHeight = (int) (node.getRasterHeight() * (nodeResolution / resolution)); } targetResolutionTargetWidthLabel.setText("" + targetWidth); targetResolutionTargetHeightLabel.setText("" + targetHeight); } } private void reactToSourceProductChange(Product product) { if (product != null && !paramMap.containsKey("targetResolution")) { resolutionSpinner.setValue(determineResolutionFromProduct(product)); } else if(product == null) { resolutionSpinner.setValue(0); } } private int determineResolutionFromProduct(Product product) { final RasterDataNode node = getAnyRasterDataNode(product); if (node != null) { return (int) node.getImageToModelTransform().getScaleX(); } return 1; } } private class TargetWidthAndHeightPanel extends JPanel { private JSpinner widthSpinner; private JSpinner heightSpinner; private double targetWidthHeightRatio; private final JLabel targetWidthNameLabel; private final JLabel targetHeightNameLabel; private final JLabel widthHeightRatioNameLabel; private JLabel widthHeightRatioLabel; TargetWidthAndHeightPanel() { setToolTipText(TARGET_WIDTH_AND_HEIGHT_TOOLTIP_TEXT); targetWidthHeightRatio = 1.0; final GridLayout layout = new GridLayout(3, 2); layout.setVgap(2); setLayout(layout); targetWidthNameLabel = new JLabel("Target width:"); targetWidthNameLabel.setEnabled(false); add(targetWidthNameLabel); widthSpinner = new JSpinner(new SpinnerNumberModel(100, 0, 1000000, 1)); widthSpinner.setEnabled(false); add(widthSpinner); targetHeightNameLabel = new JLabel("Target height:"); targetHeightNameLabel.setEnabled(false); add(targetHeightNameLabel); heightSpinner = new JSpinner(new SpinnerNumberModel(100, 0, 1000000, 1)); heightSpinner.setEnabled(false); add(heightSpinner); widthHeightRatioNameLabel = new JLabel("Width / height ratio: "); widthHeightRatioNameLabel.setEnabled(false); add(widthHeightRatioNameLabel); widthHeightRatioLabel = new JLabel(); widthHeightRatioLabel.setEnabled(false); add(widthHeightRatioLabel); widthSpinner.addChangeListener(e -> updateTargetWidth()); heightSpinner.addChangeListener(e -> updateTargetHeight()); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); widthSpinner.setEnabled(enabled); heightSpinner.setEnabled(enabled); widthHeightRatioLabel.setEnabled(enabled); targetWidthNameLabel.setEnabled(enabled); targetHeightNameLabel.setEnabled(enabled); widthHeightRatioNameLabel.setEnabled(enabled); } private void updateTargetWidth() { if (!updatingTargetWidthAndHeight) { updatingTargetWidthAndHeight = true; final int targetWidth = Integer.parseInt(widthSpinner.getValue().toString()); final int targetHeight = (int) (targetWidth / targetWidthHeightRatio); heightSpinner.setValue(targetHeight); updatingTargetWidthAndHeight = false; } } private void updateTargetHeight() { if (!updatingTargetWidthAndHeight) { updatingTargetWidthAndHeight = true; final int targetHeight = Integer.parseInt(heightSpinner.getValue().toString()); final int targetWidth = (int) (targetHeight * targetWidthHeightRatio); widthSpinner.setValue(targetWidth); updatingTargetWidthAndHeight = false; } } private void reactToSourceProductChange(Product product) { if (product != null && !(paramMap.containsKey("targetWidth") && paramMap.containsKey("targetHeight"))) { targetWidthHeightRatio = product.getSceneRasterWidth() / (double) product.getSceneRasterHeight(); widthSpinner.setValue(product.getSceneRasterWidth()); heightSpinner.setValue(product.getSceneRasterHeight()); } else if(product == null) { targetWidthHeightRatio = 1.0; widthSpinner.setValue(0); heightSpinner.setValue(0); } widthHeightRatioLabel.setText(String.format("%.5f", targetWidthHeightRatio)); } } private class ReferenceBandNameBoxPanel extends JPanel { private JComboBox<String> referenceBandNameBox; private JLabel referenceBandTargetWidthLabel; private JLabel referenceBandTargetHeightLabel; private final JLabel referenceBandTargetHeightNameLabel; private final JLabel referenceBandTargetWidthNameLabel; ReferenceBandNameBoxPanel() { setToolTipText(REFERENCE_BAND_TOOLTIP_TEXT); referenceBandNameBox = new JComboBox<>(); referenceBandNameBox.addActionListener(e -> { updateReferenceBandTargetWidthAndHeight(); }); final GridLayout referenceBandNameBoxPanelLayout = new GridLayout(3, 1); referenceBandNameBoxPanelLayout.setVgap(2); setLayout(referenceBandNameBoxPanelLayout); add(referenceBandNameBox); JPanel referenceBandNameTargetWidthPanel = new JPanel(new GridLayout(1, 2)); referenceBandTargetWidthNameLabel = new JLabel("Resulting target width: "); referenceBandNameTargetWidthPanel.add(referenceBandTargetWidthNameLabel); referenceBandTargetWidthLabel = new JLabel(); referenceBandNameTargetWidthPanel.add(referenceBandTargetWidthLabel); JPanel referenceBandNameTargetHeightPanel = new JPanel(new GridLayout(1, 2)); referenceBandTargetHeightNameLabel = new JLabel("Resulting target height: "); referenceBandNameTargetHeightPanel.add(referenceBandTargetHeightNameLabel); referenceBandTargetHeightLabel = new JLabel(); referenceBandNameTargetHeightPanel.add(referenceBandTargetHeightLabel); add(referenceBandNameTargetWidthPanel); add(referenceBandNameTargetHeightPanel); referenceBandNameBox.addActionListener(e -> updateReferenceBandName()); } @Override public void setEnabled(boolean enabled) { super.setEnabled(enabled); referenceBandNameBox.setEnabled(enabled); referenceBandTargetWidthLabel.setEnabled(enabled); referenceBandTargetHeightLabel.setEnabled(enabled); referenceBandTargetWidthNameLabel.setEnabled(enabled); referenceBandTargetHeightNameLabel.setEnabled(enabled); if (enabled) { updateReferenceBandName(); } } private void updateReferenceBandTargetWidthAndHeight() { if (referenceBandNameBox.getSelectedItem() != null) { final String bandName = referenceBandNameBox.getSelectedItem().toString(); final Band band = sourceProducts[0].getBand(bandName); referenceBandTargetWidthLabel.setText("" + band.getRasterWidth()); referenceBandTargetHeightLabel.setText("" + band.getRasterHeight()); } } private void updateReferenceBandName() { //updateParameters(); } private void reactToSourceProductChange(Product product) { Object selected = referenceBandNameBox.getSelectedItem(); referenceBandNameBox.removeAllItems(); String[] bandNames = new String[0]; if (product != null) { bandNames = product.getBandNames(); } referenceBandNameBox.setModel(new DefaultComboBoxModel<>(bandNames)); referenceBandNameBox.setEditable(false); if(selected != null) { referenceBandNameBox.setSelectedItem(selected); } updateReferenceBandTargetWidthAndHeight(); } } private boolean hasChangedProductSize(Product product) { return !(product.getSceneRasterWidth() == lastProductWidth && product.getSceneRasterHeight() == lastProductHeight); } private boolean hasChangedProductListBand(Product product) { if(product.getBands().length != listBands.size()) { return true; } for(String bandName : listBands) { if(product.getBand(bandName) == null) { return true; } } return false; } private void updateListBands(Product product) { listBands.clear(); if(product == null) { return; } for(Band band : product.getBands()) { listBands.add(band.getName()); } } private void updateProductSize(Product product) { if(product == null) { lastProductWidth = 0; lastProductHeight = 0; return; } lastProductWidth = product.getSceneRasterWidth(); lastProductHeight = product.getSceneRasterHeight(); } private JPanel createAdvancedCheckBoxPanel() { advancedMethodCheckBox = new JCheckBox("Advanced Method Definition by Band", false); advancedMethodCheckBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { if(e.getStateChange() == ItemEvent.SELECTED) { advancedMethodDefinitionPanel.setVisible(true); advancedMethodDefinitionPanel.validate(); loadPresetPanel.setVisible(true); upsamplingCombo.setEnabled(false); downsamplingCombo.setEnabled(false); flagDownsamplingCombo.setEnabled(false); } else { advancedMethodDefinitionPanel.setVisible(false); advancedMethodDefinitionPanel.validate(); loadPresetPanel.setVisible(false); upsamplingCombo.setEnabled(true); downsamplingCombo.setEnabled(true); flagDownsamplingCombo.setEnabled(true); } } }); final JPanel propertyPanel = new JPanel(new GridLayout(1, 1)); propertyPanel.add(advancedMethodCheckBox); return propertyPanel; } private JPanel createLoadSavePresetPanel() { final TableLayout tableLayoutMethodDefinition = new TableLayout(2); tableLayoutMethodDefinition.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayoutMethodDefinition.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayoutMethodDefinition.setTableWeightX(1.0); tableLayoutMethodDefinition.setTablePadding(4, 4); JPanel panel = new JPanel(tableLayoutMethodDefinition); //Add Load preset button final ImageIcon loadIcon = TangoIcons.actions_document_open(TangoIcons.Res.R22); JButton loadButton = new JButton("Import Preset...", loadIcon); loadButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SnapFileChooser fileChooser = new SnapFileChooser(SystemUtils.getAuxDataPath().resolve(ResamplingUtils.RESAMPLING_PRESET_FOLDER).toFile()); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setDialogTitle("Select resampling preset"); SnapFileFilter fileFilter = new SnapFileFilter("ResPreset", ".res", "Resampling preset files"); fileChooser.addChoosableFileFilter(fileFilter); fileChooser.setFileFilter(fileFilter); fileChooser.setDialogType(SnapFileChooser.OPEN_DIALOG); File selectedFile; while (true) { int i = fileChooser.showDialog(panel, null); if (i == SnapFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); try { ResamplingPreset resamplingPreset = ResamplingPreset.loadResamplingPreset(selectedFile); //check that bands corresponds with opened product if(!resamplingPreset.isCompatibleWithProduct(sourceProducts[0])) { AbstractDialog.showWarningDialog(panel, "Resampling preset incompatible with selected input product.", "Resampling preset incompatibility"); break; } //todo check upsampling and resampling method exist BandResamplingPreset[] bandResamplingPresetsLoaded = resamplingPreset.getBandResamplingPresets().toArray(new BandResamplingPreset[resamplingPreset.getBandResamplingPresets().size()]); for(BandResamplingPreset loaded : bandResamplingPresetsLoaded) { for(BandResamplingPreset bandResamplingPreset : bandResamplingPresets) { if(bandResamplingPreset.getBandName().equals(loaded.getBandName())) { bandResamplingPreset.setUpsamplingAlias(loaded.getUpsamplingAlias()); bandResamplingPreset.setDownsamplingAlias(loaded.getDownsamplingAlias()); } } } for(BandResamplingPreset bandResamplingPreset : resamplingPreset.getBandResamplingPresets()) { resamplingRowModel.setValueFor(bandResamplingPreset.getBandName(),0,bandResamplingPreset.getUpsamplingAlias()); resamplingRowModel.setValueFor(bandResamplingPreset.getBandName(),1,bandResamplingPreset.getDownsamplingAlias()); advancedMethodDefinitionPanel.repaint(); } } catch (IOException e1) { AbstractDialog.showWarningDialog(panel, "Cannot load resampling preset.", "Cannot load resampling preset."); } break; } else { // Canceled selectedFile = null; break; } } } }); panel.add(loadButton); //Add Save preset button final ImageIcon saveIcon = TangoIcons.actions_document_save_as(TangoIcons.Res.R22); JButton saveButton = new JButton("Save Preset", saveIcon); saveButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { SnapFileChooser fileChooser = new SnapFileChooser(SystemUtils.getAuxDataPath().resolve(ResamplingUtils.RESAMPLING_PRESET_FOLDER).toFile()); fileChooser.setAcceptAllFileFilterUsed(true); fileChooser.setDialogTitle("Select resampling preset"); SnapFileFilter fileFilter = new SnapFileFilter("ResPreset", ".res", "Resampling preset files"); fileChooser.addChoosableFileFilter(fileFilter); fileChooser.setFileFilter(fileFilter); fileChooser.setDialogType(SnapFileChooser.SAVE_DIALOG); File selectedFile; while (true) { int i = fileChooser.showDialog(panel, null); if (i == SnapFileChooser.APPROVE_OPTION) { selectedFile = fileChooser.getSelectedFile(); if (!selectedFile.exists()) { break; } i = JOptionPane.showConfirmDialog(panel, "The file\n" + selectedFile + "\nalready exists.\nOverwrite?", "File exists", JOptionPane.YES_NO_CANCEL_OPTION); if (i == JOptionPane.CANCEL_OPTION) { // Canceled selectedFile = null; break; } else if (i == JOptionPane.YES_OPTION) { // Overwrite existing file break; } } else { // Canceled selectedFile = null; break; } } if(selectedFile != null) { updateResamplingPreset(); ResamplingPreset auxPreset = new ResamplingPreset(selectedFile.getName(),bandResamplingPresets); auxPreset.saveToFile(selectedFile, sourceProducts[0]); } } }); panel.add(saveButton); panel.setVisible(false); return panel; } }
49,905
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
UIValidation.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/UIValidation.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui; /** * Created by IntelliJ IDEA. * User: lveci * Date: Feb 13, 2008 * To change this template use File | Settings | File Templates. */ public class UIValidation { private State state = State.OK; private String msg = ""; public enum State {OK, ERROR, WARNING} public UIValidation(State theState, String theMessage) { state = theState; msg = theMessage; } public State getState() { return state; } public String getMsg() { return msg; } }
1,280
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
NestWorldMapPaneDataModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/worldmap/NestWorldMapPaneDataModel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui.worldmap; 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 org.esa.snap.core.util.ProductUtils; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class NestWorldMapPaneDataModel { 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_SELECTED_GEO_BOUNDARIES = "selectedGeoBoundaries"; 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 final List<Product> productList = new ArrayList<>(); private Boundary[] additionalGeoBoundaryList; private Boundary[] selectedGeoBoundaryList; private final GeoPos selectionBoxStart = new GeoPos(); private final GeoPos selectionBoxEnd = new GeoPos(); public NestWorldMapPaneDataModel() { 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 void setSelectionBoxStart(final double lat, final double lon) { selectionBoxStart.setLocation(lat, lon); } public void setSelectionBoxEnd(final double lat, final double lon) { selectionBoxEnd.setLocation(lat, lon); } public GeoPos[] getSelectionBox() { final GeoPos[] selectionBox = new GeoPos[5]; selectionBox[0] = selectionBoxStart; selectionBox[1] = new GeoPos(selectionBoxStart.getLat(), selectionBoxEnd.getLon()); selectionBox[2] = selectionBoxEnd; selectionBox[3] = new GeoPos(selectionBoxEnd.getLat(), selectionBoxStart.getLon()); selectionBox[4] = selectionBoxStart; return selectionBox; } public Boundary getSelectionBoundary() { return new Boundary(getSelectionBox()); } 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 Boundary[] getAdditionalGeoBoundaries() { if (additionalGeoBoundaryList == null) { additionalGeoBoundaryList = new Boundary[0]; } return additionalGeoBoundaryList; } public void setAdditionalGeoBoundaries(final List<GeoPos[]> geoBoundaries) { final Boundary[] oldGeoBoundaries = getAdditionalGeoBoundaries(); if (geoBoundaries != null) { final List<Boundary> boundaryList = new ArrayList<>(); for (GeoPos[] geoBoundary : geoBoundaries) { boundaryList.add(new Boundary(geoBoundary)); } additionalGeoBoundaryList = boundaryList.toArray(new Boundary[boundaryList.size()]); } firePropertyChange(PROPERTY_ADDITIONAL_GEO_BOUNDARIES, oldGeoBoundaries, additionalGeoBoundaryList); } public Boundary[] getSelectedGeoBoundaries() { if (selectedGeoBoundaryList == null) { selectedGeoBoundaryList = new Boundary[0]; } return selectedGeoBoundaryList; } public void setSelectedGeoBoundaries(final List<GeoPos[]> geoBoundaries) { final Boundary[] oldGeoBoundaries = getSelectedGeoBoundaries(); if (geoBoundaries != null) { final List<Boundary> boundaryList = new ArrayList<>(); for (GeoPos[] geoBoundary : geoBoundaries) { boundaryList.add(new Boundary(geoBoundary)); } selectedGeoBoundaryList = boundaryList.toArray(new Boundary[boundaryList.size()]); } firePropertyChange(PROPERTY_SELECTED_GEO_BOUNDARIES, oldGeoBoundaries, selectedGeoBoundaryList); } 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 isAutoZommEnabled() { return autoZoomEnabled; } public void setAutoZoomEnabled(boolean autoZoomEnabled) { final boolean oldAutoZommEnabled = isAutoZommEnabled(); 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); } } public static class Boundary { public final boolean isClosed; public final GeoPos[] geoBoundary; public Boundary(final GeoPos[] geoBoundary) { ProductUtils.normalizeGeoPolygon(geoBoundary); this.geoBoundary = geoBoundary; this.isClosed = isClosedPath(geoBoundary); } private static boolean isClosedPath(final GeoPos[] geoBoundary) { return geoBoundary.length > 0 && geoBoundary[0].equals(geoBoundary[geoBoundary.length - 1]); } } }
8,163
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
NestWorldMapPane.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/worldmap/NestWorldMapPane.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui.worldmap; 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.Rendering; import com.bc.ceres.grender.Viewport; import org.apache.commons.math3.util.FastMath; 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.util.GeoUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.ButtonOverlayControl; import org.esa.snap.ui.UIUtils; import org.geotools.referencing.crs.DefaultGeographicCRS; import javax.swing.*; import javax.swing.event.MouseInputAdapter; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.GeneralPath; import java.awt.geom.PathIterator; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.List; /** * This class displays a world map specified by the {@link NestWorldMapPaneDataModel}. * * @author Marco Peters */ public class NestWorldMapPane extends JPanel { private LayerCanvas layerCanvas; private Layer worldMapLayer; private final NestWorldMapPaneDataModel dataModel; private boolean navControlShown; private WakefulComponent navControlWrapper; private final static Color transWhiteColor = new Color(255, 255, 255, 5); private final static Color borderWhiteColor = new Color(255, 255, 255, 100); private final static Color transRedColor = new Color(255, 0, 0, 30); private final static Color borderRedColor = new Color(255, 0, 0, 100); private final static Color selectionFillColor = new Color(255, 255, 0, 70); private final static Color selectionBorderColor = new Color(255, 255, 0, 255); public NestWorldMapPane(NestWorldMapPaneDataModel dataModel) { this.dataModel = dataModel; try { layerCanvas = new LayerCanvas(); layerCanvas.getModel().getViewport().setModelYAxisDown(false); layerCanvas.setInitiallyZoomingAll(false); installLayerCanvasNavigation(layerCanvas, dataModel); layerCanvas.addOverlay(new BoundaryOverlay()); final Layer rootLayer = layerCanvas.getLayer(); final Dimension dimension = new Dimension(400, 150); final Viewport viewport = layerCanvas.getViewport(); viewport.setViewBounds(new Rectangle(dimension)); setPreferredSize(dimension); setSize(dimension); setLayout(new BorderLayout()); add(layerCanvas, BorderLayout.CENTER); dataModel.addModelChangeListener(new ModelChangeListener()); worldMapLayer = dataModel.getWorldMapLayer(new WorldMapLayerContext(rootLayer)); layerCanvas.getLayer().getChildren().add(worldMapLayer); layerCanvas.getViewport().zoom(worldMapLayer.getModelBounds()); if(layerCanvas.getViewport().getZoomFactor() < 2) { layerCanvas.getViewport().setZoomFactor(2.0f); } setNavControlVisible(true); } catch (Exception e) { SnapApp.getDefault().handleError("Error in worldmap initialization", e); } } public LayerCanvas getLayerCanvas() { return layerCanvas; } @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) layerCanvas.getViewport().getZoomFactor(); } public void setScale(final float scale) { if (getScale() != scale) { final float oldValue = getScale(); layerCanvas.getViewport().setZoomFactor(scale); firePropertyChange("scale", oldValue, scale); } } public void zoomToProduct(Product product) { final NestWorldMapPaneDataModel.Boundary[] selGeoBoundaries = dataModel.getSelectedGeoBoundaries(); final GeneralPath[] generalPaths; if (product != null && product.getSceneGeoCoding() != null) { generalPaths = getGeoBoundaryPaths(product); } else if (selGeoBoundaries.length > 0) { generalPaths = assemblePathList(selGeoBoundaries[0].geoBoundary);//selGeoBoundaries[0].boundaryPaths; } else { return; } Rectangle2D modelArea = new Rectangle2D.Double(); final Viewport viewport = layerCanvas.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); } /** * 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 ButtonOverlayControl navControl = new ButtonOverlayControl(new ZoomAllAction(), new ZoomToSelectedAction());//, new ZoomToLocationAction()); navControlWrapper = new WakefulComponent(navControl); navControlWrapper.setMinAlpha(0.5f); layerCanvas.add(navControlWrapper); } else { layerCanvas.remove(navControlWrapper); navControlWrapper = null; } validate(); this.navControlShown = navControlShown; } } private void updateUiState(PropertyChangeEvent evt) { if (NestWorldMapPaneDataModel.PROPERTY_LAYER.equals(evt.getPropertyName())) { exchangeWorldMapLayer(); } if (NestWorldMapPaneDataModel.PROPERTY_PRODUCTS.equals(evt.getPropertyName())) { repaint(); } if (NestWorldMapPaneDataModel.PROPERTY_SELECTED_PRODUCT.equals(evt.getPropertyName()) || NestWorldMapPaneDataModel.PROPERTY_AUTO_ZOOM_ENABLED.equals(evt.getPropertyName())) { final Product selectedProduct = dataModel.getSelectedProduct(); if (selectedProduct != null && dataModel.isAutoZommEnabled()) { zoomToProduct(selectedProduct); } else { repaint(); } } if (NestWorldMapPaneDataModel.PROPERTY_ADDITIONAL_GEO_BOUNDARIES.equals(evt.getPropertyName()) || NestWorldMapPaneDataModel.PROPERTY_SELECTED_GEO_BOUNDARIES.equals(evt.getPropertyName())) { repaint(); } } private void exchangeWorldMapLayer() { final List<Layer> children = layerCanvas.getLayer().getChildren(); for (Layer child : children) { child.dispose(); } children.clear(); final Layer rootLayer = layerCanvas.getLayer(); worldMapLayer = dataModel.getWorldMapLayer(new WorldMapLayerContext(rootLayer)); children.add(worldMapLayer); layerCanvas.getViewport().zoom(worldMapLayer.getModelBounds()); } private Rectangle2D cropToMaxModelBounds(Rectangle2D modelBounds) { final Rectangle2D maxModelBounds = worldMapLayer.getModelBounds(); if (modelBounds.getWidth() >= maxModelBounds.getWidth() - 1 || modelBounds.getHeight() >= maxModelBounds.getHeight() - 1) { modelBounds = maxModelBounds; } return modelBounds; } public static GeneralPath[] getGeoBoundaryPaths(Product product) { final int step = Math.max(16, (product.getSceneRasterWidth() + product.getSceneRasterHeight()) / 250); return GeoUtils.createGeoBoundaryPaths(product, null, step); } private PixelPos getProductCenter(final Product product) { final GeoCoding geoCoding = product.getSceneGeoCoding(); PixelPos centerPos = null; if (geoCoding != null) { final float pixelX = (float) Math.floor(0.5f * product.getSceneRasterWidth()) + 0.5f; final float pixelY = (float) 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((float) point2D.getX(), (float) point2D.getY()); } return centerPos; } private static void installLayerCanvasNavigation(final LayerCanvas layerCanvas, final NestWorldMapPaneDataModel dataModel) { MouseHandler mouseHandler = new MouseHandler(layerCanvas, dataModel); 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); } } public static class MouseHandler extends MouseInputAdapter { private final LayerCanvas layerCanvas; private final NestWorldMapPaneDataModel dataModel; private Point p0; private Point.Float selectionStart = new Point.Float(); private Point.Float selectionEnd = new Point.Float(); private boolean leftButtonDown = false; private MouseHandler(final LayerCanvas layerCanvas, final NestWorldMapPaneDataModel dataModel) { this.layerCanvas = layerCanvas; this.dataModel = dataModel; } @Override public void mousePressed(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { leftButtonDown = true; final AffineTransform viewToModelTransform = layerCanvas.getViewport().getViewToModelTransform(); viewToModelTransform.transform(e.getPoint(), selectionStart); dataModel.setSelectionBoxStart(selectionStart.y, selectionStart.x); dataModel.setSelectionBoxEnd(selectionStart.y, selectionStart.x); layerCanvas.updateUI(); } else { p0 = e.getPoint(); } } @Override public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { leftButtonDown = false; } } @Override public void mouseDragged(MouseEvent e) { final Point p = e.getPoint(); if (leftButtonDown) { final AffineTransform viewToModelTransform = layerCanvas.getViewport().getViewToModelTransform(); viewToModelTransform.transform(e.getPoint(), selectionEnd); dataModel.setSelectionBoxEnd(selectionEnd.y, selectionEnd.x); layerCanvas.updateUI(); } else if (p0 != null) { 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 mouseWheelMoved(MouseWheelEvent e) { final int wheelRotation = e.getWheelRotation(); double newZoomFactor = layerCanvas.getViewport().getZoomFactor() * FastMath.pow(1.1, wheelRotation); newZoomFactor = capZoom(newZoomFactor); layerCanvas.getViewport().setZoomFactor(newZoomFactor); } } private static double capZoom(double newZoomFactor) { if(newZoomFactor < 2) newZoomFactor = 2.0f; if(newZoomFactor > 2000) newZoomFactor = 2000.0f; return newZoomFactor; } 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 BoundaryOverlay implements LayerCanvas.Overlay { @Override public void paintOverlay(LayerCanvas canvas, Rendering rendering) { for (final NestWorldMapPaneDataModel.Boundary extraGeoBoundary : dataModel.getAdditionalGeoBoundaries()) { drawGeoBoundary(rendering.getGraphics(), assemblePathList(extraGeoBoundary.geoBoundary), extraGeoBoundary.isClosed, transWhiteColor, borderWhiteColor); } for (final NestWorldMapPaneDataModel.Boundary selectGeoBoundary : dataModel.getSelectedGeoBoundaries()) { drawGeoBoundary(rendering.getGraphics(), assemblePathList(selectGeoBoundary.geoBoundary), selectGeoBoundary.isClosed, transRedColor, borderRedColor); } final Product selectedProduct = dataModel.getSelectedProduct(); for (final Product product : dataModel.getProducts()) { if (product != null && selectedProduct != product) { drawProduct(rendering.getGraphics(), product, transWhiteColor, Color.WHITE); } } if (selectedProduct != null) { drawProduct(rendering.getGraphics(), selectedProduct, transWhiteColor, Color.RED); } final NestWorldMapPaneDataModel.Boundary selectionBox = dataModel.getSelectionBoundary(); drawGeoBoundary(rendering.getGraphics(), assemblePathList(selectionBox.geoBoundary),//selectionBox.boundaryPaths, selectionBox.isClosed, selectionFillColor, selectionBorderColor); } private boolean isClosedPath(final GeoPos[] geoBoundary) { return geoBoundary[0].equals(geoBoundary[geoBoundary.length - 1]); } private void drawProduct(final Graphics2D g2d, final Product product, final Color fillColor, final Color borderColor) { final GeoCoding geoCoding = product.getSceneGeoCoding(); if (geoCoding == null) { return; } GeneralPath[] boundaryPaths = getGeoBoundaryPaths(product); final String text = String.valueOf(product.getRefNo()); final PixelPos textCenter = getProductCenter(product); drawGeoBoundaryPath(g2d, boundaryPaths, fillColor, borderColor); drawText(g2d, text, textCenter, 0.0f); } private void drawGeoBoundaryPath(final Graphics2D g2d, final GeneralPath[] boundaryPaths, final Color fillColor, final Color borderColor) { final AffineTransform transform = layerCanvas.getViewport().getModelToViewTransform(); for (GeneralPath boundaryPath : boundaryPaths) { boundaryPath.transform(transform); g2d.setColor(fillColor); g2d.fill(boundaryPath); g2d.setColor(borderColor); g2d.draw(boundaryPath); } } private void drawGeoBoundary(final Graphics2D g2d, final GeneralPath[] boundaryPaths, final boolean fill, final Color fillColor, final Color borderColor) { final AffineTransform transform = layerCanvas.getViewport().getModelToViewTransform(); for (GeneralPath boundaryPath : boundaryPaths) { boundaryPath.transform(transform); if (fill) { g2d.setColor(fillColor); g2d.fill(boundaryPath); } g2d.setColor(borderColor); g2d.draw(boundaryPath); } } 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, (int) textCenter.x - fontMetrics.stringWidth(text) / 2.0f, (int) 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 class ZoomAllAction extends AbstractAction { private ZoomAllAction() { putValue(LARGE_ICON_KEY, UIUtils.loadImageIcon("icons/ZoomAll24.gif")); } @Override public void actionPerformed(ActionEvent e) { layerCanvas.getViewport().zoom(worldMapLayer.getModelBounds()); double newZoomFactor = capZoom(layerCanvas.getViewport().getZoomFactor()); layerCanvas.getViewport().setZoomFactor(newZoomFactor); } } private class ZoomToSelectedAction extends AbstractAction { private ZoomToSelectedAction() { putValue(LARGE_ICON_KEY, UIUtils.loadImageIcon("icons/ZoomTo24.gif")); } @Override public void actionPerformed(ActionEvent e) { zoomToProduct(getSelectedProduct()); } } private class ZoomToLocationAction extends AbstractAction { private ZoomToLocationAction() { putValue(LARGE_ICON_KEY, UIUtils.loadImageIcon("/org/esa/nest/icons/define-location-24.png", this.getClass())); } @Override public void actionPerformed(ActionEvent e) { zoomToProduct(getSelectedProduct()); } } public static GeneralPath[] assemblePathList(GeoPos[] geoPoints) { final GeneralPath path = new GeneralPath(GeneralPath.WIND_NON_ZERO, geoPoints.length + 8); final ArrayList<GeneralPath> pathList = new ArrayList<>(16); if (geoPoints.length > 1) { double lon, lat; double minLon = 0, maxLon = 0; boolean first = true; for (GeoPos gp : geoPoints) { lon = gp.getLon(); lat = gp.getLat(); if (first) { minLon = lon; maxLon = lon; path.moveTo(lon, lat); first = false; } if (lon < minLon) { minLon = lon; } if (lon > maxLon) { maxLon = lon; } path.lineTo(lon, lat); } //path.closePath(); int runIndexMin = (int) Math.floor((minLon + 180) / 360); int runIndexMax = (int) Math.floor((maxLon + 180) / 360); if (runIndexMin == 0 && runIndexMax == 0) { // the path is completely within [-180, 180] longitude pathList.add(path); return pathList.toArray(new GeneralPath[pathList.size()]); } final Area pathArea = new Area(path); final GeneralPath pixelPath = new GeneralPath(GeneralPath.WIND_NON_ZERO); for (int k = runIndexMin; k <= runIndexMax; k++) { final Area currentArea = new Area(new Rectangle2D.Float(k * 360.0f - 180.0f, -90.0f, 360.0f, 180.0f)); currentArea.intersect(pathArea); if (!currentArea.isEmpty()) { pathList.add(areaToPath(currentArea, -k * 360.0, pixelPath)); } } } return pathList.toArray(new GeneralPath[pathList.size()]); } private static GeneralPath areaToPath(final Area negativeArea, final double deltaX, final GeneralPath pixelPath) { final float[] floats = new float[6]; // move to correct rectangle final AffineTransform transform = AffineTransform.getTranslateInstance(deltaX, 0.0); final PathIterator iterator = negativeArea.getPathIterator(transform); while (!iterator.isDone()) { final int segmentType = iterator.currentSegment(floats); if (segmentType == PathIterator.SEG_LINETO) { pixelPath.lineTo(floats[0], floats[1]); } else if (segmentType == PathIterator.SEG_MOVETO) { pixelPath.moveTo(floats[0], floats[1]); } else if (segmentType == PathIterator.SEG_CLOSE) { pixelPath.closePath(); } iterator.next(); } return pixelPath; } }
26,003
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WorldMapUI.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/gpf/ui/worldmap/WorldMapUI.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.gpf.ui.worldmap; import org.esa.snap.core.datamodel.GeoPos; import javax.swing.event.MouseInputAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; /** */ public class WorldMapUI { private final NestWorldMapPaneDataModel worldMapDataModel; private final NestWorldMapPane worlMapPane; private final List<WorldMapUIListener> listenerList = new ArrayList<>(1); public WorldMapUI() { worldMapDataModel = new NestWorldMapPaneDataModel(); worlMapPane = new NestWorldMapPane(worldMapDataModel); worlMapPane.getLayerCanvas().addMouseListener(new MouseHandler()); } public GeoPos[] getSelectionBox() { return worldMapDataModel.getSelectionBox(); } public void setSelectionStart(final double lat, final double lon) { worldMapDataModel.setSelectionBoxStart(lat, lon); } public void setSelectionEnd(final double lat, final double lon) { worldMapDataModel.setSelectionBoxEnd(lat, lon); } public void setAdditionalGeoBoundaries(final List<GeoPos[]> geoBoundaries) { worldMapDataModel.setAdditionalGeoBoundaries(geoBoundaries); } public void setSelectedGeoBoundaries(final List<GeoPos[]> geoBoundaries) { worldMapDataModel.setSelectedGeoBoundaries(geoBoundaries); } public NestWorldMapPane getWorlMapPane() { return worlMapPane; } public NestWorldMapPaneDataModel getModel() { return worldMapDataModel; } public void addListener(final WorldMapUIListener listener) { if (!listenerList.contains(listener)) { listenerList.add(listener); } } public void removeListener(final WorldMapUIListener listener) { listenerList.remove(listener); } private void notifyQuery() { for (final WorldMapUIListener listener : listenerList) { listener.notifyNewMapSelectionAvailable(); } } public interface WorldMapUIListener { void notifyNewMapSelectionAvailable(); } private class MouseHandler extends MouseInputAdapter { @Override public void mouseReleased(MouseEvent e) { if (e.getButton() == MouseEvent.BUTTON1) { notifyQuery(); } } } }
3,056
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LabelBarProgressMonitor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/progress/LabelBarProgressMonitor.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.progress; import com.bc.ceres.core.Assert; import com.bc.ceres.core.ProgressMonitor; import javax.swing.JLabel; import javax.swing.JProgressBar; import javax.swing.SwingUtilities; import java.util.ArrayList; import java.util.List; /** * A {@link com.bc.ceres.core.ProgressMonitor} which uses a * Swing's {@link javax.swing.ProgressMonitor} to display progress. */ public class LabelBarProgressMonitor implements ProgressMonitor { public static final String stopCommand = "stop"; public static final String updateCommand = "update"; private final JProgressBar progressBar; private final JLabel messageLabel; private double currentWork; private double totalWork; private int totalWorkUI; private int currentWorkUI; private int lastWorkUI; private boolean cancelRequested; private final List<ProgressBarListener> listenerList = new ArrayList<>(1); public LabelBarProgressMonitor(JProgressBar progressBar) { this(progressBar, null); } public LabelBarProgressMonitor(JProgressBar progressBar, JLabel messageLabel) { this.progressBar = progressBar; this.messageLabel = messageLabel; } /** * Notifies that the main task is beginning. This must only be called once * on a given progress monitor instance. * * @param name the name (or description) of the main task * @param totalWork the total number of work units into which * the main task is been subdivided. If the value is <code>UNKNOWN</code> * the implementation is free to indicate progress in a way which * doesn't require the total number of work units in advance. */ public void beginTask(String name, int totalWork) { Assert.notNull(name, "name"); currentWork = 0.0; this.totalWork = totalWork; currentWorkUI = 0; lastWorkUI = 0; totalWorkUI = totalWork; if (messageLabel != null) { messageLabel.setText(name); } cancelRequested = false; setDescription(name); progressBar.setMaximum(totalWork); } /** * Notifies that the work is done; that is, either the main task is completed * or the user canceled it. This method may be called more than once * (implementations should be prepared to handle this case). */ public void done() { runInUI(new Runnable() { public void run() { if (progressBar != null) { progressBar.setValue(progressBar.getMaximum()); for (final ProgressBarListener listener : listenerList) { listener.notifyProgressDone(); } } if (messageLabel != null) { messageLabel.setText(""); } } }); } /** * Internal method to handle scaling correctly. This method * must not be called by a client. Clients should * always use the method </code>worked(int)</code>. * * @param work the amount of work done */ public void internalWorked(double work) { currentWork += work; currentWorkUI = (int) (totalWorkUI * currentWork / totalWork); if (currentWorkUI > lastWorkUI) { runInUI(new Runnable() { public void run() { if (progressBar != null) { int progress = progressBar.getMinimum() + currentWorkUI; progressBar.setValue(progress); for (final ProgressBarListener listener : listenerList) { listener.notifyProgressStart(); } } lastWorkUI = currentWorkUI; } }); } } /** * Returns whether cancelation of current operation has been requested. * Long-running operations should poll to see if cancelation * has been requested. * * @return <code>true</code> if cancellation has been requested, * and <code>false</code> otherwise * @see #setCanceled(boolean) */ public boolean isCanceled() { return cancelRequested; } /** * Sets the cancel state to the given value. * * @param canceled <code>true</code> indicates that cancelation has * been requested (but not necessarily acknowledged); * <code>false</code> clears this flag * @see #isCanceled() */ public void setCanceled(boolean canceled) { cancelRequested = canceled; if (canceled) { done(); } } /** * Sets the task name to the given value. This method is used to * restore the task label after a nested operation was executed. * Normally there is no need for clients to call this method. * * @param name the name (or description) of the main task * @see #beginTask(String, int) */ public void setTaskName(final String name) { runInUI(new Runnable() { public void run() { if (messageLabel != null) { messageLabel.setText(name); } } }); } /** * Notifies that a subtask of the main task is beginning. * Subtasks are optional; the main task might not have subtasks. * * @param name the name (or description) of the subtask */ public void setSubTaskName(final String name) { if (messageLabel != null) { messageLabel.setText(name); } } /** * Notifies that a given number of work unit of the main task * has been completed. Note that this amount represents an * installment, as opposed to a cumulative amount of work done * to date. * * @param work the number of work units just completed */ public void worked(int work) { internalWorked(work); } //////////////////////////////////////////////////////////////////////// // Stuff to be performed in Swing's event-dispatching thread private static void runInUI(Runnable task) { if (SwingUtilities.isEventDispatchThread()) { task.run(); } else { SwingUtilities.invokeLater(task); } } private void setDescription(final String description) { if (messageLabel != null) { messageLabel.setText(description); } } public void addListener(final ProgressBarListener listener) { if (!listenerList.contains(listener)) { listenerList.add(listener); } } public void removeListener(final ProgressBarListener listener) { listenerList.remove(listener); } public interface ProgressBarListener { void notifyProgressStart(); void notifyProgressDone(); } }
7,732
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StatusProgress.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/progress/StatusProgress.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.graphbuilder.rcp.progress; import org.esa.snap.core.dataop.downloadable.ProgressMonitorList; import org.esa.snap.core.dataop.downloadable.StatusProgressMonitor; import org.esa.snap.core.util.SystemUtils; import org.openide.awt.StatusLineElementProvider; import org.openide.util.lookup.ServiceProvider; import javax.swing.JPanel; import java.awt.Component; import java.util.HashMap; import java.util.Map; @ServiceProvider(service = StatusLineElementProvider.class, position = 1) public class StatusProgress implements StatusLineElementProvider, ProgressMonitorList.Listener { private final JPanel statusPanel = new JPanel(); private final Map<StatusProgressMonitor, StatusProgressPanel> progressPanelMap = new HashMap<>(); public StatusProgress() { ProgressMonitorList.instance().addListener(this); } @Override public Component getStatusLineElement() { return statusPanel; } public void notifyMsg(final ProgressMonitorList.Notification msg, final StatusProgressMonitor pm) { try { if (msg.equals(ProgressMonitorList.Notification.ADD)) { final StatusProgressPanel progressPanel = new StatusProgressPanel(pm); progressPanelMap.put(pm, progressPanel); statusPanel.add(progressPanel); } else if (msg.equals(ProgressMonitorList.Notification.REMOVE)) { final StatusProgressPanel progressPanel = progressPanelMap.get(pm); if(progressPanel != null) { statusPanel.remove(progressPanel); } progressPanelMap.remove(pm); } } catch (Exception e) { SystemUtils.LOG.severe("StatusProgress "+e.getMessage()); } } }
2,509
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
StatusProgressPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/progress/StatusProgressPanel.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.graphbuilder.rcp.progress; import org.esa.snap.core.dataop.downloadable.StatusProgressMonitor; import org.netbeans.api.progress.ProgressHandle; import org.netbeans.api.progress.ProgressHandleFactory; import javax.swing.JPanel; import javax.swing.SwingUtilities; public class StatusProgressPanel extends JPanel implements StatusProgressMonitor.Listener { private final StatusProgressMonitor pm; private final ProgressHandle p; private boolean active; public StatusProgressPanel(final StatusProgressMonitor pm) { this.pm = pm; if(pm != null) { p = ProgressHandleFactory.createHandle(pm.getName()); p.start(100); p.switchToDeterminate(100); active = true; pm.addListener(this); } else { p = null; active = false; } } private void update() { runInUI(new Runnable() { public void run() { if (active) { p.progress(pm.getText(), pm.getPercentComplete()); } } }); } private void runInUI(Runnable task) { if (SwingUtilities.isEventDispatchThread()) { task.run(); } else { SwingUtilities.invokeLater(task); } } public void notifyMsg(final StatusProgressMonitor.Notification msg) { if (msg.equals(StatusProgressMonitor.Notification.UPDATE)) { update(); } else if (msg.equals(StatusProgressMonitor.Notification.DONE)) { active = false; p.finish(); } } }
2,353
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
DialogUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/utils/DialogUtils.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.utils; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.tool.ToolButtonFactory; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.GridLayout; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.beans.PropertyChangeListener; import java.text.NumberFormat; import java.util.HashSet; import java.util.Set; /** * Common functions for working with dialog controls */ public final class DialogUtils { public enum ButtonStyle { Text, Icon, TextAndIcon, FramedButton } public static void enableComponents(JComponent label, JComponent field, boolean flag) { label.setVisible(flag); field.setVisible(flag); } public static void addComponent(JPanel contentPane, GridBagConstraints gbc, JLabel label, JComponent component) { gbc.gridx = 0; contentPane.add(label, gbc); gbc.gridx = 1; contentPane.add(component, gbc); gbc.gridx = 0; } public static JLabel addComponent(JPanel contentPane, GridBagConstraints gbc, String text, JComponent component) { gbc.gridx = 0; final JLabel label = new JLabel(text); contentPane.add(label, gbc); gbc.gridx = 1; contentPane.add(component, gbc); gbc.gridx = 0; return label; } public static void addInnerPanel(JPanel contentPane, GridBagConstraints gbc, JLabel label, JComponent component1, JComponent component2) { contentPane.add(label, gbc); final JPanel innerPane = new JPanel(new GridBagLayout()); final GridBagConstraints gbc2 = DialogUtils.createGridBagConstraints(); innerPane.add(component1, gbc2); gbc2.gridx = 1; innerPane.add(component2, gbc2); gbc.gridx = 1; contentPane.add(innerPane, gbc); } public static JFormattedTextField createFormattedTextField(final NumberFormat numFormat, final Object value, final PropertyChangeListener propListener) { final JFormattedTextField field = new JFormattedTextField(numFormat); field.setValue(value); field.setColumns(10); if (propListener != null) field.addPropertyChangeListener("value", propListener); return field; } public static void fillPanel(final JPanel panel, final GridBagConstraints gbc) { gbc.fill = GridBagConstraints.BOTH; gbc.gridx = 0; gbc.gridwidth = 2; gbc.weightx = 1.0; gbc.weighty = 1.0; panel.add(new JPanel(), gbc); } public static AbstractButton createIconButton(final String name, final String text, final ImageIcon icon, final boolean toggle) { return createButton(name, text, icon, null, ButtonStyle.Icon, toggle); } public static AbstractButton createButton(final String name, final String text, final ImageIcon icon, final JPanel panel, final ButtonStyle style) { return createButton(name, text, icon, panel, style, false); } public static AbstractButton createButton(final String name, final String text, final ImageIcon icon, final JPanel panel, final ButtonStyle style, final boolean toggle) { final AbstractButton button; if (icon == null || style == ButtonStyle.TextAndIcon) { button = new JButton(); button.setText(text); } else if (style == ButtonStyle.FramedButton) { button = new JButton(); } else { button = ToolButtonFactory.createButton(icon, toggle); } button.setName(name); button.setIcon(icon); if(panel != null) { button.setBackground(panel.getBackground()); } button.setToolTipText(text); button.setActionCommand(name); return button; } public static boolean contains(final JComboBox<String> comboBox, final Object item) { final Set<Object> items = new HashSet<>(); for (int i = 0; i < comboBox.getItemCount(); i++) { items.add(comboBox.getItemAt(i)); } return items.contains(item); } public static class ComponentListPanel extends JPanel { private final JPanel labelPanel; private final JPanel fieldPanel; public ComponentListPanel() { final GridLayout grid = new GridLayout(0, 1); grid.setVgap(5); labelPanel = new JPanel(grid); fieldPanel = new JPanel(new GridLayout(0, 1)); this.add(labelPanel, BorderLayout.CENTER); this.add(fieldPanel, BorderLayout.LINE_END); } public void addComponent(final String labelStr, final JComponent component) { labelPanel.add(new JLabel(labelStr)); fieldPanel.add(component); } } public static GridBagConstraints createGridBagConstraints() { final GridBagConstraints gbc = GridBagUtils.createDefaultConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; gbc.insets.top = 1; gbc.insets.bottom = 1; gbc.insets.right = 1; gbc.insets.left = 1; gbc.gridx = 0; gbc.gridy = 0; return gbc; } public static class TextAreaKeyListener implements KeyListener { private boolean changedByUser = false; public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { changedByUser = true; } public void keyTyped(KeyEvent e) { } public boolean isChangedByUser() { return changedByUser; } } }
6,843
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ClipboardUtils.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/utils/ClipboardUtils.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.utils; import org.esa.snap.core.util.SystemUtils; import java.awt.Toolkit; import java.awt.datatransfer.Clipboard; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.File; import java.io.IOException; import java.util.List; /** * Utils for using the clipboard */ public class ClipboardUtils { /** * Copies the given text to the system clipboard. * * @param text the text to copy */ public static void copyToClipboard(final String text) { final StringSelection selection = new StringSelection(text == null ? "" : text); final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard != null) { clipboard.setContents(selection, selection); } else { SystemUtils.LOG.severe("failed to obtain clipboard instance"); } } /** * Retrieves text from the system clipboard. * * @return string */ public static String getClipboardString() throws IOException, UnsupportedFlavorException { final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard != null) { return (String) clipboard.getData(DataFlavor.stringFlavor); } return null; } /** * Copies the given file list to the system clipboard. * * @param fileList the list to copy */ public static void copyToClipboard(final File[] fileList) { final FileListSelection selection = new FileListSelection(fileList); final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard != null) { clipboard.setContents(selection, selection); } else { SystemUtils.LOG.severe("failed to obtain clipboard instance"); } } /** * Retrieves a list of files from the system clipboard. * * @return file[] list */ public static File[] getClipboardFileList() throws IOException, UnsupportedFlavorException { final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); if (clipboard != null) { final List<File> fileList = (List<File>) clipboard.getData(DataFlavor.javaFileListFlavor); return fileList.toArray(new File[fileList.size()]); } return new File[0]; } }
3,218
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FileListSelection.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/utils/FileListSelection.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.utils; import com.bc.ceres.swing.selection.AbstractSelection; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * File list selection */ public class FileListSelection extends AbstractSelection implements Transferable { private static final DataFlavor[] flavors = { DataFlavor.stringFlavor, DataFlavor.javaFileListFlavor }; private final List<File> fileList = new ArrayList<>(); public FileListSelection(File[] fileList) { this.fileList.addAll(Arrays.asList(fileList)); } @Override public File getSelectedValue() { return fileList.get(0); } @Override public File[] getSelectedValues() { return fileList.toArray(new File[fileList.size()]); } /** * Returns an array of flavors in which this <code>Transferable</code> * can provide the data. <code>DataFlavor.stringFlavor</code> * * @return an array of flavors */ public DataFlavor[] getTransferDataFlavors() { return flavors; } public boolean isDataFlavorSupported(final DataFlavor flavor) { for (DataFlavor f : flavors) { if (flavor.equals(f)) { return true; } } return false; } /** * Returns the <code>Transferable</code>'s data in the requested <code>DataFlavor</code> if possible. * * @param flavor the requested flavor for the data * @return the data in the requested flavor, as outlined above * @throws java.awt.datatransfer.UnsupportedFlavorException if the requested data flavor not supported */ public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException { if (flavor.equals(DataFlavor.javaFileListFlavor)) { return fileList; } else if (flavor.equals(DataFlavor.stringFlavor)) { return null; } else { throw new UnsupportedFlavorException(flavor); } } }
2,934
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OperatorAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/actions/OperatorAction.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.actions; import org.esa.snap.core.gpf.ui.DefaultOperatorAction; import org.esa.snap.graphbuilder.rcp.dialogs.SingleOperatorDialog; import org.esa.snap.ui.ModelessDialog; import org.esa.snap.ui.UIUtils; import javax.swing.*; import java.awt.event.ActionEvent; import java.util.Arrays; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * <p>An action which creates a default dialog for an operator given by the * action property action property {@code operatorName}.</p> * <p>Optionally the dialog title can be set via the {@code dialogTitle} property and * the ID of the help page can be given using the {@code helpId} property. If not given the * name of the operator will be used instead. Also optional the * file name suffix for the target product can be given via the {@code targetProductNameSuffix} property.</p> */ public class OperatorAction extends DefaultOperatorAction { public static ImageIcon esaIcon = UIUtils.loadImageIcon("/org/esa/snap/graphbuilder/icons/esa.png", OperatorAction.class); public static ImageIcon rstbIcon = UIUtils.loadImageIcon("/org/esa/snap/graphbuilder/icons/csa.png", OperatorAction.class); public static ImageIcon esaPlanetIcon = UIUtils.loadImageIcon("/org/esa/snap/graphbuilder/icons/esa-planet.png", OperatorAction.class); public static ImageIcon geoAusIcon = UIUtils.loadImageIcon("/org/esa/snap/graphbuilder/icons/geo_aus.png", OperatorAction.class); protected static final Set<String> KNOWN_KEYS = new HashSet<>(Arrays.asList("displayName", "operatorName", "dialogTitle", "targetProductNameSuffix", "helpId", "icon")); private ModelessDialog dialog; public static OperatorAction create(Map<String, Object> properties) { OperatorAction action = new OperatorAction(); for (Map.Entry<String, Object> entry : properties.entrySet()) { if (KNOWN_KEYS.contains(entry.getKey())) { action.putValue(entry.getKey(), entry.getValue()); } } return action; } @Override public void actionPerformed(ActionEvent event) { ModelessDialog dialog = createOperatorDialog(); dialog.show(); } public String getPropertyString(final String key) { Object value = getValue(key); if (value instanceof String) { return (String) value; } return null; } public String getIcon() { return getPropertyString("icon"); } protected ModelessDialog createOperatorDialog() { setHelpId(getPropertyString("helpId")); final SingleOperatorDialog productDialog = new SingleOperatorDialog(getOperatorName(), getAppContext(), getDialogTitle(), getHelpId()); if (getTargetProductNameSuffix() != null) { productDialog.setTargetProductNameSuffix(getTargetProductNameSuffix()); } addIcon(productDialog); return productDialog; } protected void addIcon(final ModelessDialog dlg) { String iconName = getIcon(); if (iconName == null) { //setIcon(dlg, IconUtils.esaPlanetIcon); } else if (iconName.equals("esaIcon")) { setIcon(dlg, esaPlanetIcon); } else if (iconName.equals("rstbIcon")) { setIcon(dlg, rstbIcon); } else if (iconName.equals("geoAusIcon")) { setIcon(dlg, geoAusIcon); } else { final ImageIcon icon = UIUtils.loadImageIcon(iconName, OperatorAction.class); if (icon != null) setIcon(dlg, icon); } } private static void setIcon(final ModelessDialog dlg, final ImageIcon ico) { if (ico == null) return; dlg.getJDialog().setIconImage(ico.getImage()); } }
4,736
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BatchProcessingAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/actions/BatchProcessingAction.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.actions; import org.esa.snap.graphbuilder.rcp.dialogs.BatchGraphDialog; import org.esa.snap.rcp.SnapApp; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle; import javax.swing.AbstractAction; import java.awt.event.ActionEvent; @ActionID( category = "Tools", id = "BatchProcessingAction" ) @ActionRegistration( displayName = "#CTL_BatchProcessingAction_MenuText", popupText = "#CTL_BatchProcessingAction_MenuText", iconBase = "org/esa/snap/graphbuilder/icons/batch.png", lazy = true ) @ActionReferences({ @ActionReference(path = "Menu/Tools", position = 320, separatorAfter = 399), @ActionReference(path = "Toolbars/Processing", position = 20) }) @NbBundle.Messages({ "CTL_BatchProcessingAction_MenuText=Batch Processing", "CTL_BatchProcessingAction_ShortDescription=Batch process several products" }) public class BatchProcessingAction extends AbstractAction { @Override public void actionPerformed(final ActionEvent event) { final BatchGraphDialog dialog = new BatchGraphDialog(SnapApp.getDefault().getAppContext(), "Batch Processing", "batchProcessing", false); dialog.show(); } }
2,111
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/actions/GraphAction.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.actions; import org.esa.snap.graphbuilder.rcp.dialogs.GraphBuilderDialog; import org.esa.snap.ui.ModelessDialog; import java.io.File; import java.util.Arrays; import java.util.Map; /** * <p>An action which creates a graph builder dialog for a graph given by the * action property action property {@code graphFile}.</p> * <p>Optionally the dialog title can be set via the {@code dialogTitle} property and * the ID of the help page can be given using the {@code helpId} property. If not given the * name of the operator will be used instead. Also optional the * file name suffix for the target product can be given via the {@code targetProductNameSuffix} property.</p> */ public class GraphAction extends OperatorAction { static { KNOWN_KEYS.addAll(Arrays.asList("graphFile", "enableEditing")); } public static GraphAction create(Map<String, Object> properties) { GraphAction action = new GraphAction(); for (Map.Entry<String, Object> entry : properties.entrySet()) { if (KNOWN_KEYS.contains(entry.getKey())) { action.putValue(entry.getKey(), entry.getValue()); } } return action; } public String getGraphFileName() { return getPropertyString("graphFile"); } public boolean isEditingEnabled() { final String enableEditingStr = getPropertyString("enableEditing"); return enableEditingStr != null && enableEditingStr.equalsIgnoreCase("true"); } @Override protected ModelessDialog createOperatorDialog() { setHelpId(getPropertyString("helpId")); final GraphBuilderDialog dialog = new GraphBuilderDialog(getAppContext(), getDialogTitle(), getHelpId(), isEditingEnabled()); dialog.show(); final File graphPath = GraphBuilderDialog.getInternalGraphFolder(); final File graphFile = new File(graphPath, getGraphFileName()); addIcon(dialog); dialog.loadGraph(graphFile); return dialog; } }
2,769
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
OpenGraphBuilderAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/actions/OpenGraphBuilderAction.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.graphbuilder.rcp.actions; import org.esa.snap.graphbuilder.rcp.dialogs.GraphBuilderDialog; import org.esa.snap.rcp.SnapApp; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle; import javax.swing.AbstractAction; import java.awt.event.ActionEvent; import java.io.InputStream; @ActionID( category = "Tools", id = "GraphBuilderAction" ) @ActionRegistration( displayName = "#CTL_GraphBuilderAction_MenuText", popupText = "#CTL_GraphBuilderAction_MenuText", iconBase = "org/esa/snap/graphbuilder/icons/graph.png", lazy = true ) @ActionReferences({ @ActionReference(path = "Menu/Tools",position = 310, separatorBefore = 300), @ActionReference(path = "Toolbars/Processing", position = 10) }) @NbBundle.Messages({ "CTL_GraphBuilderAction_MenuText=GraphBuilder", "CTL_GraphBuilderAction_ShortDescription=Create a custom processing graph" }) public class OpenGraphBuilderAction extends AbstractAction { public OpenGraphBuilderAction() { super("GraphBuilder"); } public void actionPerformed(ActionEvent event) { final GraphBuilderDialog dialog = new GraphBuilderDialog(SnapApp.getDefault().getAppContext(), "Graph Builder", "graph_builder"); //dialog.getJDialog().setIconImage(IconUtils.esaPlanetIcon.getImage()); dialog.show(); InputStream graphFileStream = getClass().getClassLoader().getResourceAsStream("graphs/ReadWriteGraph.xml"); dialog.loadGraph(graphFileStream, null); dialog.enableInitialInstructions(true); } }
2,450
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AbstractInstructPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/AbstractInstructPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.wizards; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; /** * Instructions Panel */ public abstract class AbstractInstructPanel extends WizardPanel { private final String title; protected BufferedImage image = null; protected int imgPosX = 0; protected int imgPosY = 0; public AbstractInstructPanel(final String title) { super("Instructions"); this.title = title; createPanel(); } public void returnFromLaterStep() { } public boolean canRedisplayNextPanel() { return true; } public boolean hasNextPanel() { return true; } public boolean canFinish() { return false; } public abstract WizardPanel getNextPanel(); public boolean validateInput() { return true; } protected abstract String getDescription(); protected abstract String getInstructions(); private void createPanel() { final JPanel instructPanel1 = new JPanel(new BorderLayout(2, 2)); instructPanel1.setBorder(BorderFactory.createTitledBorder(title)); final JTextPane desciptionPane = new JTextPane(); desciptionPane.setBackground(instructPanel1.getBackground()); desciptionPane.setText(getDescription()); instructPanel1.add(desciptionPane, BorderLayout.NORTH); this.add(instructPanel1, BorderLayout.NORTH); final JPanel instructPanel2 = new JPanel(new BorderLayout(2, 2)); instructPanel2.setBorder(BorderFactory.createTitledBorder("Instructions")); final JTextPane instructionPane = new JTextPane(); instructionPane.setBackground(instructPanel2.getBackground()); instructionPane.setText(getInstructions()); instructPanel2.add(instructionPane, BorderLayout.CENTER); this.add(instructPanel2, BorderLayout.CENTER); } @Override public void paint(final Graphics g) { super.paint(g); if (image != null) { g.drawImage(image, imgPosX, imgPosY, null); } } }
2,818
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WizardDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/WizardDialog.java
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ----------------- * WizardDialog.java * ----------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: WizardDialog.java,v 1.6 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.esa.snap.graphbuilder.rcp.wizards; import org.esa.snap.ui.help.HelpDisplayer; import org.jfree.ui.L1R3ButtonPanel; import org.openide.util.HelpCtx; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JDialog; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.Container; import java.awt.Dimension; import java.awt.Frame; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; /** * A dialog that presents the user with a sequence of steps for completing a task. The dialog * contains "Next" and "Previous" buttons, allowing the user to navigate through the task. * <p/> * When the user backs up by one or more steps, the dialog keeps the completed steps so that * they can be reused if the user doesn't change anything - this handles the cases where the user * backs up a few steps just to review what has been completed. * <p/> * But if the user changes some options in an earlier step, then the dialog may have to discard * the later steps and have them repeated. * <p/> * * @author David Gilbert */ public class WizardDialog extends JDialog implements ActionListener { /** * The end result of the wizard sequence. */ private Object result; /** * The current step in the wizard process (starting at step zero). */ private int step; /** * A reference to the current panel. */ private WizardPanel currentPanel; private String wizardName = ""; /** * A list of references to the panels the user has already seen - used for navigating through * the steps that have already been completed. */ private List<WizardPanel> panels; /** * A handy reference to the "previous" button. */ private JButton previousButton; /** * A handy reference to the "next" button. */ private JButton nextButton; /** * A handy reference to the "finish" button. */ private JButton finishButton; /** * A handy reference to the "help" button. */ private JButton helpButton; // Java help support private String helpId; /** * Standard constructor - builds and returns a new WizardDialog. * * @param owner the owner. * @param modal modal? * @param title the title. * @param helpID the help id * @param firstPanel the first panel. */ public WizardDialog(final JDialog owner, final boolean modal, final String title, final String helpID, final WizardPanel firstPanel) { super(owner, title, modal); init(title, helpID, firstPanel); setLocation(owner.getSize()); } /** * Standard constructor - builds a new WizardDialog owned by the specified JFrame. * * @param owner the owner. * @param modal modal? * @param title the title. * @param helpID the help id * @param firstPanel the first panel. */ public WizardDialog(final Frame owner, final boolean modal, final String title, final String helpID, final WizardPanel firstPanel) { super(owner, title, modal); init(title, helpID, firstPanel); setLocation(owner.getSize()); } private void init(final String title, final String helpID, final WizardPanel firstPanel) { this.wizardName = title; this.result = null; this.currentPanel = firstPanel; this.currentPanel.setOwner(this); this.step = 0; this.panels = new ArrayList<>(4); this.panels.add(firstPanel); setContentPane(createContent()); setTitle(createTitle()); setHelpID(helpID); super.setDefaultCloseOperation(DISPOSE_ON_CLOSE); } private void setLocation(final Dimension ownerDim) { final int size = 500; final int half = size / 2; this.setLocation((int) (ownerDim.getWidth() / 2) - half, (int) (ownerDim.getHeight() / 2) - half); this.setMinimumSize(new Dimension(size, size)); } public void setIcon(final ImageIcon ico) { if (ico == null) return; this.setIconImage(ico.getImage()); } /** * 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(); } private void updateHelpID() { if (helpId == null) { return; } if (getContentPane() instanceof JComponent) { HelpCtx.setHelpIDString((JComponent)getContentPane(), helpId); } if (helpButton != null) { HelpCtx.setHelpIDString(helpButton, helpId); } } /** * Returns the result of the wizard sequence. * * @return the result. */ public Object getResult() { return this.result; } /** * Returns the total number of steps in the wizard sequence, if this number is known. Otherwise * this method returns zero. Subclasses should override this method unless the number of steps * is not known. * * @return the number of steps. */ public int getStepCount() { return 0; } /** * Returns true if it is possible to back up to the previous panel, and false otherwise. * * @return boolean. */ public boolean canDoPreviousPanel() { return (this.step > 0); } /** * Returns true if there is a 'next' panel, and false otherwise. * * @return boolean. */ public boolean canDoNextPanel() { return this.currentPanel.hasNextPanel(); } /** * Returns true if it is possible to finish the sequence at this point (possibly with defaults * for the remaining entries). * * @return boolean. */ public boolean canFinish() { return this.currentPanel.canFinish(); } /** * Returns the panel for the specified step (steps are numbered from zero). * * @param step the current step. * @return the panel. */ public WizardPanel getWizardPanel(final int step) { if (step < this.panels.size()) { return this.panels.get(step); } else { return null; } } /** * Handles events. * * @param event the event. */ public void actionPerformed(final ActionEvent event) { final String command = event.getActionCommand(); if (command.equals("nextButton")) { next(); } else if (command.equals("previousButton")) { previous(); } else if (command.equals("finishButton")) { finish(); } } private String createTitle() { String stepStr = ""; if (step != 0) stepStr = "Step " + this.step + ' '; return wizardName + " : " + stepStr + currentPanel.getPanelTitle(); } /** * Handles a click on the "previous" button, by displaying the previous panel in the sequence. */ public void previous() { if (this.step > 0) { final WizardPanel previousPanel = getWizardPanel(this.step - 1); // tell the panel that we are returning previousPanel.returnFromLaterStep(); final Container content = getContentPane(); content.remove(this.currentPanel); content.add(previousPanel); this.step = this.step - 1; this.currentPanel = previousPanel; setTitle(createTitle()); enableButtons(); pack(); repaint(); } } /** * Displays the next step in the wizard sequence. */ public void next() { if (!this.currentPanel.validateInput()) { return; } WizardPanel nextPanel = getWizardPanel(this.step + 1); if (nextPanel != null) { if (!this.currentPanel.canRedisplayNextPanel()) { nextPanel = this.currentPanel.getNextPanel(); } } else { nextPanel = this.currentPanel.getNextPanel(); } this.step = this.step + 1; if (this.step < this.panels.size()) { this.panels.set(this.step, nextPanel); } else { this.panels.add(nextPanel); } final Container content = getContentPane(); content.remove(this.currentPanel); content.add(nextPanel); this.currentPanel = nextPanel; this.currentPanel.setOwner(this); setTitle(createTitle()); enableButtons(); pack(); repaint(); } /** * Finishes the wizard. */ public void finish() { this.currentPanel.finish(); } /** * Enables/disables the buttons according to the current step. A good idea would be to ask the * panels to return the status... */ private void enableButtons() { this.previousButton.setEnabled(this.step > 0); this.nextButton.setEnabled(canDoNextPanel()); this.finishButton.setEnabled(canFinish()); this.helpButton.setEnabled(helpId != null); } public void updateState() { enableButtons(); repaint(); } /** * Checks, whether the user cancelled the dialog. * * @return false. */ public boolean isCancelled() { return false; } /** * Creates a panel containing the user interface for the dialog. * * @return the panel. */ public JPanel createContent() { final JPanel content = new JPanel(new BorderLayout()); content.setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4)); content.add(this.panels.get(0)); final L1R3ButtonPanel buttons = new L1R3ButtonPanel("Help", "Previous", "Next", "Finish"); this.helpButton = buttons.getLeftButton(); this.helpButton.addActionListener(e -> { HelpDisplayer.show(helpId); }); this.helpButton.setEnabled(false); this.previousButton = buttons.getRightButton1(); this.previousButton.setActionCommand("previousButton"); this.previousButton.addActionListener(this); this.previousButton.setEnabled(false); this.nextButton = buttons.getRightButton2(); this.nextButton.setActionCommand("nextButton"); this.nextButton.addActionListener(this); this.nextButton.setEnabled(true); this.finishButton = buttons.getRightButton3(); this.finishButton.setActionCommand("finishButton"); this.finishButton.addActionListener(this); this.finishButton.setEnabled(false); buttons.setBorder(BorderFactory.createEmptyBorder(4, 0, 0, 0)); content.add(buttons, BorderLayout.SOUTH); return content; } }
12,884
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AbstractMultipleInputPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/AbstractMultipleInputPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.wizards; import org.esa.snap.graphbuilder.rcp.dialogs.ProductSetPanel; import org.esa.snap.graphbuilder.rcp.dialogs.support.FileTable; import org.esa.snap.rcp.SnapApp; import javax.swing.*; import java.awt.*; import java.io.File; /** * Input Panel */ public abstract class AbstractMultipleInputPanel extends WizardPanel { protected ProductSetPanel productSetPanel; public AbstractMultipleInputPanel() { super("Input"); createPanel(); } public void returnFromLaterStep() { } public boolean canRedisplayNextPanel() { return false; } public boolean hasNextPanel() { return true; } public boolean canFinish() { return false; } public boolean validateInput() { final File[] fileList = productSetPanel.getFileList(); if (fileList.length == 0 || (fileList.length == 1 && !fileList[0].exists())) { showErrorMsg("Please add some products to the table"); return false; } return true; } public abstract WizardPanel getNextPanel(); protected String getInstructions() { return "Browse for input products with the Add button, use the Add All Open button to add every product opened " + "or drag and drop products into the table.\n" + "Specify the target folder where the products will be written to.\n"; } private void createPanel() { final JPanel textPanel = createTextPanel("Instructions", getInstructions()); this.add(textPanel, BorderLayout.NORTH); // productSetPanel = new ProductSetPanel(SnapApp.getDefault().getAppContext(), null, new FileTable(), false, true); productSetPanel = new ProductSetPanel(SnapApp.getDefault().getAppContext(), null, new FileTable(), true, true); this.add(productSetPanel, BorderLayout.CENTER); } }
2,644
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AbstractMapPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/AbstractMapPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.wizards; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.GeoUtils; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.engine_utilities.gpf.CommonReaders; import org.esa.snap.graphbuilder.gpf.ui.worldmap.WorldMapUI; import javax.swing.*; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Map Panel */ public abstract class AbstractMapPanel extends WizardPanel { protected final File[] productFileList; protected final File targetFolder; public AbstractMapPanel(final File[] productFileList, final File targetFolder) { super("Viewing the footprint"); this.productFileList = productFileList; this.targetFolder = targetFolder; createPanel(productFileList); } public void returnFromLaterStep() { } public boolean canRedisplayNextPanel() { return false; } public boolean hasNextPanel() { return true; } public boolean canFinish() { return false; } public abstract WizardPanel getNextPanel(); public boolean validateInput() { return true; } protected String getInstructions() { return "View the footprint of the input products on the world map\n" + "Use the mouse wheel to zoom in and out. Hold and drag the right mouse button to pan\n"; } private void createPanel(final File[] productFileList) { final JPanel textPanel = createTextPanel("Instructions", getInstructions()); this.add(textPanel, BorderLayout.NORTH); final WorldMapUI worldMapUI = new WorldMapUI(); this.add(worldMapUI.getWorlMapPane(), BorderLayout.CENTER); final List<GeoPos[]> geoBoundariesList = getGeoBoundaries(productFileList); worldMapUI.setAdditionalGeoBoundaries(geoBoundariesList); } private List<GeoPos[]> getGeoBoundaries(final File[] productFileList) { final List<GeoPos[]> geoBoundaryList = new ArrayList<>(); for(File file : productFileList) { try { final Product product = CommonReaders.readProduct(file); final int step = Math.max(30, (product.getSceneRasterWidth() + product.getSceneRasterHeight()) / 10); GeoPos[] geoPoints = GeoUtils.createGeoBoundary(product, null, step, true); geoBoundaryList.add(geoPoints); } catch (Exception e) { SystemUtils.LOG.severe("Unable to load " + file); } } return geoBoundaryList; } }
3,372
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WizardPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/WizardPanel.java
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------- * WizardPanel.java * ---------------- * (C) Copyright 2000-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: WizardPanel.java,v 1.5 2007/11/02 17:50:36 taqua Exp $ * * Changes (from 26-Oct-2001) * -------------------------- * 26-Oct-2001 : Changed package to com.jrefinery.ui.*; * 14-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.esa.snap.graphbuilder.rcp.wizards; import org.esa.snap.graphbuilder.rcp.dialogs.BatchGraphDialog; import org.esa.snap.graphbuilder.rcp.dialogs.GraphBuilderDialog; import org.esa.snap.rcp.util.Dialogs; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JTextArea; import java.awt.BorderLayout; import java.awt.Dimension; import java.io.File; /** * A panel that provides the user interface for a single step in a WizardDialog. * * @author David Gilbert */ public abstract class WizardPanel extends JPanel { /** * The owner. */ private WizardDialog owner; private final String panelTitle; protected final static File wizardGraphPath = new File(GraphBuilderDialog.getInternalGraphFolder(), "wizards"); protected boolean finishing = false; private File[] targetFileList = new File[0]; /** * Creates a new panel. * * @param name the panel name. */ protected WizardPanel(final String name) { super(new BorderLayout(1, 1)); this.panelTitle = name; this.setPreferredSize(new Dimension(500, 500)); } public String getPanelTitle() { return panelTitle; } /** * Returns a reference to the dialog that owns the panel. * * @return the owner. */ public WizardDialog getOwner() { return this.owner; } /** * Sets the reference to the dialog that owns the panel (this is called automatically by * the dialog when the panel is added to the dialog). * * @param owner the owner. */ public void setOwner(final WizardDialog owner) { this.owner = owner; } public void finish() { } protected static void showErrorMsg(String msg) { Dialogs.showError("Oops!", msg); } protected static JPanel createTextPanel(final String title, final String text) { final JPanel textPanel = new JPanel(new BorderLayout(2, 2)); textPanel.setBorder(BorderFactory.createTitledBorder(title)); final JTextArea textPane = new JTextArea(); textPane.setBackground(textPanel.getBackground()); textPane.setText(text); textPanel.add(textPane, BorderLayout.NORTH); return textPanel; } public abstract boolean validateInput(); /** * This method is called when the dialog redisplays this panel as a result of the user clicking * the "Previous" button. Inside this method, subclasses should make a note of their current * state, so that they can decide what to do when the user hits "Next". */ public abstract void returnFromLaterStep(); /** * Returns true if it is OK to redisplay the last version of the next panel, or false if a new * version is required. * * @return boolean. */ public abstract boolean canRedisplayNextPanel(); /** * Returns true if there is a next panel. * * @return boolean. */ public abstract boolean hasNextPanel(); /** * Returns true if it is possible to finish from this panel. * * @return boolean. */ public abstract boolean canFinish(); /** * Returns the next panel in the sequence, given the current user input. Returns null if this * panel is the last one in the sequence. * * @return the next panel in the sequence. */ public abstract WizardPanel getNextPanel(); public File[] getTargetFileList() { return targetFileList; } public class GraphProcessListener implements GraphBuilderDialog.ProcessingListener { public void notifyMSG(final MSG msg, final String text) { if (msg.equals(MSG.DONE)) { getOwner().updateState(); if (finishing) { getOwner().dispose(); } } } public void notifyMSG(final MSG msg, final File[] fileList) { if (msg.equals(MSG.DONE)) { targetFileList = fileList; getOwner().updateState(); if (finishing) { getOwner().dispose(); } } } } public class MyBatchProcessListener implements BatchGraphDialog.BatchProcessListener { public void notifyMSG(final BatchMSG msg, final File[] inputFileList, final File[] outputFileList) { if (msg.equals(BatchMSG.DONE)) { targetFileList = outputFileList; getOwner().updateState(); } } public void notifyMSG(final BatchMSG msg, final String text) { if (msg.equals(BatchMSG.UPDATE)) { } } } }
6,411
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AbstractInputPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/AbstractInputPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.wizards; import org.esa.snap.core.datamodel.Product; import org.esa.snap.graphbuilder.rcp.dialogs.SourceProductPanel; import org.esa.snap.rcp.SnapApp; import javax.swing.*; import java.awt.*; /** */ public abstract class AbstractInputPanel extends WizardPanel { protected SourceProductPanel sourcePanel; public AbstractInputPanel() { super("Input"); createPanel(); } public void returnFromLaterStep() { } public boolean canRedisplayNextPanel() { return false; } public boolean hasNextPanel() { return true; } public boolean canFinish() { return false; } public boolean validateInput() { final Product product = sourcePanel.getSelectedSourceProduct(); if (product == null) { showErrorMsg("Please select a source product"); return false; } return true; } public abstract WizardPanel getNextPanel(); protected abstract String getInstructions(); private void createPanel() { final JPanel textPanel = createTextPanel("Instructions", getInstructions()); this.add(textPanel, BorderLayout.NORTH); sourcePanel = new SourceProductPanel(SnapApp.getDefault().getAppContext()); sourcePanel.initProducts(); this.add(sourcePanel, BorderLayout.CENTER); } }
2,123
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WizardAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/wizards/WizardAction.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.wizards; import org.esa.snap.graphbuilder.rcp.actions.OperatorAction; import org.esa.snap.rcp.SnapApp; import org.openide.modules.ModuleInfo; import org.openide.util.Lookup; import java.awt.event.ActionEvent; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * <p>An action which creates a default dialog for an operator given by the * action property action property {@code operatorName}.</p> * <p>Optionally the dialog title can be set via the {@code dialogTitle} property and * the ID of the help page can be given using the {@code helpId} property. If not given the * name of the operator will be used instead. Also optional the * file name suffix for the target product can be given via the {@code targetProductNameSuffix} property.</p> */ public class WizardAction extends OperatorAction { protected static final Set<String> KNOWN_KEYS = new HashSet<>(Arrays.asList("wizardPanelClass")); static { KNOWN_KEYS.addAll(OperatorAction.KNOWN_KEYS); } public String getWizardPanelClass() { return getPropertyString("wizardPanelClass"); } public static OperatorAction create(Map<String, Object> properties) { WizardAction action = new WizardAction(); for (Map.Entry<String, Object> entry : properties.entrySet()) { if (KNOWN_KEYS.contains(entry.getKey())) { action.putValue(entry.getKey(), entry.getValue()); } } return action; } @Override public void actionPerformed(ActionEvent event) { try { Class<?> wizardClass = getClass(getWizardPanelClass()); final WizardPanel wizardPanel = (WizardPanel) wizardClass.newInstance(); final WizardDialog dialog = new WizardDialog(SnapApp.getDefault().getMainFrame(), false, getDialogTitle(), getHelpId(), wizardPanel); dialog.setVisible(true); } catch (Exception e) { SnapApp.getDefault().handleError("Unable to create wizard", e); } } private static Class<?> getClass(String className) { Collection<? extends ModuleInfo> modules = Lookup.getDefault().lookupAll(ModuleInfo.class); for (ModuleInfo module : modules) { if (module.isEnabled()) { try { Class<?> implClass = module.getClassLoader().loadClass(className); if (WizardPanel.class.isAssignableFrom(implClass)) { //noinspection unchecked return (Class<?>) implClass; } } catch (ClassNotFoundException e) { // it's ok, continue } } } return null; } }
3,605
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
MultiGraphDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/MultiGraphDialog.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorException; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.engine_utilities.gpf.CommonReaders; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphExecuter; import org.esa.snap.graphbuilder.rcp.progress.LabelBarProgressMonitor; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.ModelessDialog; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JTabbedPane; import javax.swing.SwingWorker; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; /** * Provides the dialog for excuting multiple graph from one user interface */ public abstract class MultiGraphDialog extends ModelessDialog implements LabelBarProgressMonitor.ProgressBarListener { protected final AppContext appContext; protected final IOPanel ioPanel; protected final List<GraphExecuter> graphExecuterList = new ArrayList<>(3); private final JPanel mainPanel; protected final JTabbedPane tabbedPane; private final JLabel statusLabel; private final JPanel progressPanel; private final JProgressBar progressBar; private LabelBarProgressMonitor progBarMonitor = null; private boolean isProcessing = false; protected static final String TMP_FILENAME = "tmp_intermediate"; public MultiGraphDialog(final AppContext theAppContext, final String title, final String helpID, final boolean useSourceSelector) { super(theAppContext.getApplicationWindow(), title, ID_APPLY_CLOSE_HELP, helpID); appContext = theAppContext; mainPanel = new JPanel(new BorderLayout(4, 4)); tabbedPane = new JTabbedPane(); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(final ChangeEvent e) { validateAllNodes(); } }); mainPanel.add(tabbedPane, BorderLayout.CENTER); ioPanel = new IOPanel(appContext, tabbedPane, useSourceSelector); // status statusLabel = new JLabel(""); statusLabel.setForeground(new Color(255, 0, 0)); mainPanel.add(statusLabel, BorderLayout.NORTH); // progress Bar progressBar = new JProgressBar(); progressBar.setName(getClass().getName() + "progressBar"); progressBar.setStringPainted(true); progressPanel = new JPanel(); progressPanel.setLayout(new BorderLayout(2, 2)); progressPanel.add(progressBar, BorderLayout.CENTER); progBarMonitor = new LabelBarProgressMonitor(progressBar); progBarMonitor.addListener(this); final JButton progressCancelBtn = new JButton("Cancel"); progressCancelBtn.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { cancelProcessing(); } }); progressPanel.add(progressCancelBtn, BorderLayout.EAST); progressPanel.setVisible(false); mainPanel.add(progressPanel, BorderLayout.SOUTH); getButton(ID_APPLY).setText("Run"); super.getJDialog().setMinimumSize(new Dimension(500, 300)); } @Override public int show() { ioPanel.initProducts(); setContent(mainPanel); initGraphs(); return super.show(); } @Override public void hide() { ioPanel.releaseProducts(); super.hide(); } @Override protected void onApply() { if (isProcessing) return; ioPanel.onApply(); try { doProcessing(); } catch (Exception e) { statusLabel.setText(e.getMessage()); } } @Override protected void onClose() { cancelProcessing(); super.onClose(); } private void initGraphs() { try { deleteGraphs(); createGraphs(); } catch (Exception e) { statusLabel.setText(e.getMessage()); } } /** * Validates the input and then call the GPF to execute the graph * */ private void doProcessing() { if (validateAllNodes()) { SystemUtils.freeAllMemory(); progressBar.setValue(0); final SwingWorker processThread = new ProcessThread(progBarMonitor); processThread.execute(); } else { showErrorDialog(statusLabel.getText()); } } public void notifyProgressStart() { progressPanel.setVisible(true); } public void notifyProgressDone() { progressPanel.setVisible(false); } private void cancelProcessing() { if (progBarMonitor != null) progBarMonitor.setCanceled(true); } private void deleteGraphs() { for (GraphExecuter gex : graphExecuterList) { gex.clearGraph(); } graphExecuterList.clear(); } /** * Loads a new graph from a file * * @param executer the GraphExcecuter * @param file the graph file to load */ public void loadGraph(final GraphExecuter executer, final File file) { try { executer.loadGraph(new FileInputStream(file), file, true, true); } catch (Exception e) { showErrorDialog(e.getMessage()); } } abstract void createGraphs() throws GraphException; abstract void assignParameters() throws GraphException; abstract void cleanUpTempFiles(); private boolean validateAllNodes() { if (isProcessing) return false; if (ioPanel == null || graphExecuterList.isEmpty()) return false; boolean result; statusLabel.setText(""); try { // check the all files have been saved final Product srcProduct = ioPanel.getSelectedSourceProduct(); if (srcProduct != null && (srcProduct.isModified() || srcProduct.getFileLocation() == null)) { throw new OperatorException("The source product has been modified. Please save it before using it in " + getTitle()); } assignParameters(); // first graph must pass result = graphExecuterList.get(0).initGraph(); } catch (Exception e) { statusLabel.setText(e.getMessage()); result = false; } return result; } private void openTargetProducts(final List<File> fileList) { if (!fileList.isEmpty()) { for (File file : fileList) { try { final Product product = CommonReaders.readProduct(file); if (product != null) { appContext.getProductManager().addProduct(product); } } catch (Exception e) { showErrorDialog(e.getMessage()); } } } } protected IOPanel getIOPanel() { return ioPanel; } public void setTargetProductNameSuffix(final String suffix) { ioPanel.setTargetProductNameSuffix(suffix); } /** * For running graphs in unit tests * * @throws Exception when failing validation */ public void testRunGraph() throws Exception { ioPanel.initProducts(); initGraphs(); if (validateAllNodes()) { for (GraphExecuter graphEx : graphExecuterList) { final String desc = graphEx.getGraphDescription(); if (desc != null && !desc.isEmpty()) System.out.println("Processing " + graphEx.getGraphDescription()); graphEx.initGraph(); graphEx.executeGraph(ProgressMonitor.NULL); graphEx.disposeGraphContext(); } cleanUpTempFiles(); } else { throw new OperatorException(statusLabel.getText()); } } ///// private class ProcessThread extends SwingWorker<Boolean, Object> { private final ProgressMonitor pm; private Date executeStartTime = null; private boolean errorOccured = false; public ProcessThread(final ProgressMonitor pm) { this.pm = pm; } @Override protected Boolean doInBackground() throws Exception { pm.beginTask("Processing Graph...", 100 * graphExecuterList.size()); try { executeStartTime = Calendar.getInstance().getTime(); isProcessing = true; for (GraphExecuter graphEx : graphExecuterList) { final String desc = graphEx.getGraphDescription(); if (desc != null && !desc.isEmpty()) statusLabel.setText("Processing " + graphEx.getGraphDescription()); graphEx.initGraph(); graphEx.executeGraph(SubProgressMonitor.create(pm, 100)); graphEx.disposeGraphContext(); } } catch (Exception e) { System.out.print(e.getMessage()); if (e.getMessage() != null && !e.getMessage().isEmpty()) statusLabel.setText(e.getMessage()); else statusLabel.setText(e.toString()); errorOccured = true; } finally { isProcessing = false; pm.done(); if (SnapApp.getDefault().getPreferences().getBoolean(GPF.BEEP_AFTER_PROCESSING_PROPERTY, false)) { Toolkit.getDefaultToolkit().beep(); } } return true; } @Override public void done() { if (!errorOccured) { final Date now = Calendar.getInstance().getTime(); final long diff = (now.getTime() - executeStartTime.getTime()) / 1000; if (diff > 120) { final float minutes = diff / 60f; statusLabel.setText("Processing completed in " + minutes + " minutes"); } else { statusLabel.setText("Processing completed in " + diff + " seconds"); } SystemUtils.freeAllMemory(); if (ioPanel.isOpenInAppSelected()) { final GraphExecuter graphEx = graphExecuterList.get(graphExecuterList.size() - 1); openTargetProducts(graphEx.getProductsToOpenInDAT()); } } cleanUpTempFiles(); } } }
11,937
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
IOPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/IOPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.selection.AbstractSelectionChangeListener; import com.bc.ceres.swing.selection.SelectionChangeEvent; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.ui.SourceProductSelector; import org.esa.snap.core.gpf.ui.TargetProductSelector; import org.esa.snap.core.gpf.ui.TargetProductSelectorModel; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.SaveProductAsAction; import org.esa.snap.ui.AppContext; import javax.swing.JPanel; import javax.swing.JTabbedPane; import java.io.File; import java.util.ArrayList; import java.util.List; /** * IO Panel to handle source and target selection * User: lveci * Date: Feb 5, 2009 */ public class IOPanel { private final TargetProductSelector targetProductSelector; private final boolean useSourceSelector; private final List<SourceProductSelector> sourceProductSelectorList = new ArrayList<>(3); private String targetProductNameSuffix = ""; IOPanel(final AppContext theAppContext, final JTabbedPane tabbedPane, boolean createSourceSelector) { this.useSourceSelector = createSourceSelector; targetProductSelector = new TargetProductSelector(); final String homeDirPath = SystemUtils.getUserHomeDir().getPath(); final String saveDir = SnapApp.getDefault().getPreferences().get(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, homeDirPath); targetProductSelector.getModel().setProductDir(new File(saveDir)); targetProductSelector.getOpenInAppCheckBox().setText("Open in " + theAppContext.getApplicationName()); final TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTableWeightX(1.0); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setTablePadding(1, 1); final JPanel ioParametersPanel = new JPanel(tableLayout); if (useSourceSelector) { // Fetch source products sourceProductSelectorList.add(new SourceProductSelector(theAppContext)); for (SourceProductSelector selector : sourceProductSelectorList) { ioParametersPanel.add(selector.createDefaultPanel()); } ioParametersPanel.add(tableLayout.createVerticalSpacer()); sourceProductSelectorList.get(0).addSelectionChangeListener(new AbstractSelectionChangeListener() { public void selectionChanged(SelectionChangeEvent event) { final Product selectedProduct = (Product) event.getSelection().getSelectedValue(); if (selectedProduct != null) { final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel(); targetProductSelectorModel.setProductName(selectedProduct.getName() + getTargetProductNameSuffix()); } } }); } ioParametersPanel.add(targetProductSelector.createDefaultPanel()); if (useSourceSelector) { tabbedPane.add("I/O Parameters", ioParametersPanel); } else { tabbedPane.add("Target Product", ioParametersPanel); } } public void setTargetProductName(final String name) { final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel(); targetProductSelectorModel.setProductName(name + getTargetProductNameSuffix()); } void initProducts() { if (useSourceSelector) { for (SourceProductSelector sourceProductSelector : sourceProductSelectorList) { sourceProductSelector.initProducts(); } } } void releaseProducts() { if (!useSourceSelector) { for (SourceProductSelector sourceProductSelector : sourceProductSelectorList) { sourceProductSelector.releaseProducts(); } } } public void onApply() { final String productDir = targetProductSelector.getModel().getProductDir().getAbsolutePath(); SnapApp.getDefault().getPreferences().put(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, productDir); } Product getSelectedSourceProduct() { if (useSourceSelector) return sourceProductSelectorList.get(0).getSelectedProduct(); return null; } public File getTargetFile() { return targetProductSelector.getModel().getProductFile(); } public String getTargetFormat() { return targetProductSelector.getModel().getFormatName(); } String getTargetProductNameSuffix() { return targetProductNameSuffix; } public void setTargetProductNameSuffix(final String suffix) { targetProductNameSuffix = suffix; } boolean isOpenInAppSelected() { return targetProductSelector.getModel().isOpenInAppSelected(); } }
5,799
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SourceProductPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/SourceProductPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.ui.SourceProductSelector; import org.esa.snap.ui.AppContext; import javax.swing.JPanel; import java.util.ArrayList; import java.util.List; /** * Source product selection panel */ public class SourceProductPanel extends JPanel { private final List<SourceProductSelector> sourceProductSelectorList = new ArrayList<>(3); public SourceProductPanel(final AppContext appContext) { final TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTableWeightX(1.0); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setTablePadding(1, 1); setLayout(tableLayout); // Fetch source products sourceProductSelectorList.add(new SourceProductSelector(appContext)); for (SourceProductSelector selector : sourceProductSelectorList) { add(selector.createDefaultPanel()); } add(tableLayout.createVerticalSpacer()); } public void initProducts() { for (SourceProductSelector sourceProductSelector : sourceProductSelectorList) { sourceProductSelector.initProducts(); } } public void releaseProducts() { for (SourceProductSelector sourceProductSelector : sourceProductSelectorList) { sourceProductSelector.releaseProducts(); } } public Product getSelectedSourceProduct() { return sourceProductSelectorList.get(0).getSelectedProduct(); } }
2,384
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductSetPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/ProductSetPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.ui.TargetProductSelectorModel; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.engine_utilities.util.ProductFunctions; import org.esa.snap.graphbuilder.rcp.dialogs.support.FileTable; import org.esa.snap.graphbuilder.rcp.dialogs.support.FileTableModel; import org.esa.snap.graphbuilder.rcp.dialogs.support.TargetFolderSelector; import org.esa.snap.graphbuilder.rcp.utils.DialogUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.OpenProductAction; import org.esa.snap.rcp.actions.file.SaveProductAsAction; import org.esa.snap.rcp.util.ProgressHandleMonitor; import org.esa.snap.tango.TangoIcons; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.FileChooserFactory; import org.esa.snap.ui.GridLayout2; import org.netbeans.api.progress.ProgressUtils; import javax.swing.AbstractButton; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.event.TableModelEvent; import javax.swing.event.TableModelListener; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.util.ArrayList; /** * ProductSet Panel to handle source and target selection * User: lveci * Date: Feb 5, 2009 */ public class ProductSetPanel extends JPanel implements TableModelListener { private final FileTable productSetTable; private final TargetFolderSelector targetProductSelector; private final AppContext appContext; private String targetProductNameSuffix = ""; private JPanel buttonPanel = null; private AbstractButton addButton = null, addAllOpenButton = null, removeButton = null; private AbstractButton moveTopButton = null, moveUpButton = null, moveDownButton = null, moveBottomButton = null; private AbstractButton refreshButton = null, clearButton = null; private final JLabel countLabel = new JLabel(); private static final ImageIcon addIcon = TangoIcons.actions_list_add(TangoIcons.Res.R22); private static final ImageIcon addOpenedIcon = new ImageIcon(ProductSetPanel.class.getClassLoader(). getResource("org/esa/snap/graphbuilder/icons/add-opened22.png")); private static final ImageIcon removeIcon = TangoIcons.actions_list_remove(TangoIcons.Res.R22); private static final ImageIcon searchIcon = TangoIcons.actions_system_search(TangoIcons.Res.R22); private static final ImageIcon moveTopIcon = TangoIcons.actions_go_top(TangoIcons.Res.R22); private static final ImageIcon moveUpIcon = TangoIcons.actions_go_up(TangoIcons.Res.R22); private static final ImageIcon moveDownIcon = TangoIcons.actions_go_down(TangoIcons.Res.R22); private static final ImageIcon moveBottomIcon = TangoIcons.actions_go_bottom(TangoIcons.Res.R22); private static final ImageIcon refreshIcon = TangoIcons.actions_view_refresh(TangoIcons.Res.R22); private static final ImageIcon clearIcon = TangoIcons.actions_edit_clear(TangoIcons.Res.R22); // Number of products to populate the table details with. More than this may slow down the user's experience private static final int AUTO_POPULATE_DETAILS_LIMIT = 100; public ProductSetPanel(final AppContext theAppContext, final String title) { this(theAppContext, title, new FileTable(), false, false); } public ProductSetPanel(final AppContext theAppContext, final String title, final FileTableModel fileModel) { this(theAppContext, title, new FileTable(fileModel), false, false); } public ProductSetPanel(final AppContext theAppContext, final String title, final FileTable fileTable, final boolean incTrgProduct, final boolean incButtonPanel) { super(new BorderLayout()); this.appContext = theAppContext; this.productSetTable = fileTable; setBorderTitle(title); final JPanel productSetContent = createComponent(productSetTable); if (incButtonPanel) { buttonPanel = createButtonPanel(productSetTable); productSetContent.add(buttonPanel, BorderLayout.EAST); } this.add(productSetContent, BorderLayout.CENTER); if (incTrgProduct) { targetProductSelector = new TargetFolderSelector(); final String homeDirPath = SystemUtils.getUserHomeDir().getPath(); final String saveDir = SnapApp.getDefault().getPreferences().get(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, homeDirPath); targetProductSelector.getModel().setProductDir(new File(saveDir)); targetProductSelector.getOpenInAppCheckBox().setText("Open in " + theAppContext.getApplicationName()); targetProductSelector.getOpenInAppCheckBox().setVisible(false); this.add(targetProductSelector.createPanel(), BorderLayout.SOUTH); } else { targetProductSelector = null; } fileTable.getModel().addTableModelListener(this); updateComponents(); } protected void setBorderTitle(final String title) { if (title != null) setBorder(BorderFactory.createTitledBorder(title)); } protected JPanel getButtonPanel() { return buttonPanel; } private static JPanel createComponent(final FileTable table) { final JPanel fileListPanel = new JPanel(new BorderLayout(4, 4)); final JScrollPane scrollPane = new JScrollPane(table); fileListPanel.add(scrollPane, BorderLayout.CENTER); return fileListPanel; } protected void updateComponents() { final int rowCount = getFileCount(); final boolean enableButtons = (rowCount > 0); if (removeButton != null) removeButton.setEnabled(enableButtons); if (moveTopButton != null) moveTopButton.setEnabled(rowCount > 1); if (moveUpButton != null) moveUpButton.setEnabled(rowCount > 1); if (moveDownButton != null) moveDownButton.setEnabled(rowCount > 1); if (moveBottomButton != null) moveBottomButton.setEnabled(rowCount > 1); if (refreshButton != null) refreshButton.setEnabled(rowCount > 1); if (clearButton != null) clearButton.setEnabled(enableButtons); if (addAllOpenButton != null) { addAllOpenButton.setEnabled(SnapApp.getDefault().getProductManager().getProducts().length > 0); } String cntMsg; if (rowCount == 1) { cntMsg = rowCount + " Product"; } else { cntMsg = rowCount + " Products"; } countLabel.setText(cntMsg); } private JPanel createButtonPanel(final FileTable table) { final FileTableModel tableModel = table.getModel(); final JPanel panel = new JPanel(new GridLayout2(20, 1)); addButton = DialogUtils.createButton("addButton", "Add", addIcon, panel, DialogUtils.ButtonStyle.Icon); addButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { final File[] files = getFilePath(addButton, "Add Product"); if (files != null) { addProducts(tableModel, files); } } }); addAllOpenButton = DialogUtils.createButton("addAllOpenButton", "Add Opened", addOpenedIcon, panel, DialogUtils.ButtonStyle.Icon); addAllOpenButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { addAllOpenProducts(tableModel); } }); removeButton = DialogUtils.createButton("removeButton", "Remove", removeIcon, panel, DialogUtils.ButtonStyle.Icon); removeButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { final int rowCount = getFileCount(); if (rowCount == 1) { tableModel.clear(); return; } final int[] selRows = table.getSelectedRows(); final java.util.List<File> filesToRemove = new ArrayList<>(selRows.length); for (int row : selRows) { filesToRemove.add(tableModel.getFileAt(row)); } for (File file : filesToRemove) { int index = tableModel.getIndexOf(file); tableModel.removeFile(index); } } }); moveTopButton = DialogUtils.createButton("moveTopButton", "Move Top", moveTopIcon, panel, DialogUtils.ButtonStyle.Icon); moveTopButton.addActionListener(new MoveButtonActionListener(table, tableModel, MOVE.TOP)); moveUpButton = DialogUtils.createButton("moveUpButton", "Move Up", moveUpIcon, panel, DialogUtils.ButtonStyle.Icon); moveUpButton.addActionListener(new MoveButtonActionListener(table, tableModel, MOVE.UP)); moveDownButton = DialogUtils.createButton("moveDownButton", "Move Down", moveDownIcon, panel, DialogUtils.ButtonStyle.Icon); moveDownButton.addActionListener(new MoveButtonActionListener(table, tableModel, MOVE.DOWN)); moveBottomButton = DialogUtils.createButton("moveBottomButton", "Move Bottom", moveBottomIcon, panel, DialogUtils.ButtonStyle.Icon); moveBottomButton.addActionListener(new MoveButtonActionListener(table, tableModel, MOVE.BOTTOM)); refreshButton = DialogUtils.createButton("refreshButton", "Refresh", refreshIcon, panel, DialogUtils.ButtonStyle.Icon); refreshButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { tableModel.refresh(); } }); clearButton = DialogUtils.createButton("clearButton", "Clear", clearIcon, panel, DialogUtils.ButtonStyle.Icon); clearButton.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { tableModel.clear(); } }); panel.add(addButton); panel.add(addAllOpenButton); panel.add(removeButton); panel.add(moveTopButton); panel.add(moveUpButton); panel.add(moveDownButton); panel.add(moveBottomButton); panel.add(refreshButton); panel.add(clearButton); panel.add(countLabel); return panel; } private static void addProducts(final FileTableModel tableModel, final File[] files) { final ProgressHandleMonitor pm = ProgressHandleMonitor.create("Populating table"); Runnable operation = () -> { pm.beginTask("Populating table...", files.length); for (File file : files) { if (ProductFunctions.isValidProduct(file)) { tableModel.addFile(file); } pm.worked(1); } if(files.length < AUTO_POPULATE_DETAILS_LIMIT) { tableModel.refresh(); } pm.done(); }; ProgressUtils.runOffEventThreadWithProgressDialog(operation, "Adding Products", pm.getProgressHandle(), true, 50, 1000); } private static void addAllOpenProducts(final FileTableModel tableModel) { final ProgressHandleMonitor pm = ProgressHandleMonitor.create("Populating table"); Runnable operation = () -> { final Product[] products = SnapApp.getDefault().getProductManager().getProducts(); pm.beginTask("Populating table...", products.length); for (Product prod : products) { final File file = prod.getFileLocation(); if (file != null && file.exists()) { tableModel.addFile(file); } pm.worked(1); } if(products.length < AUTO_POPULATE_DETAILS_LIMIT) { tableModel.refresh(); } pm.done(); }; ProgressUtils.runOffEventThreadWithProgressDialog(operation, "Adding Products", pm.getProgressHandle(), true, 50, 1000); } /** * This fine grain notification tells listeners the exact range * of cells, rows, or columns that changed. */ public void tableChanged(TableModelEvent e) { updateComponents(); } private static File[] getFilePath(Component component, String title) { File[] files = null; final File openDir = new File(SnapApp.getDefault().getPreferences(). get(OpenProductAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, ".")); final JFileChooser chooser = FileChooserFactory.getInstance().createFileChooser(openDir); chooser.setMultiSelectionEnabled(true); chooser.setDialogTitle(title); if (chooser.showDialog(component, "OK") == JFileChooser.APPROVE_OPTION) { files = chooser.getSelectedFiles(); SnapApp.getDefault().getPreferences(). put(OpenProductAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, chooser.getCurrentDirectory().getAbsolutePath()); } return files; } public void setTargetProductName(final String name) { if (targetProductSelector != null) { final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel(); targetProductSelectorModel.setProductName(name + getTargetProductNameSuffix()); } } public void onApply() { if (targetProductSelector != null) { final String productDir = targetProductSelector.getModel().getProductDir().getAbsolutePath(); SnapApp.getDefault().getPreferences().put(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, productDir); } } String getTargetProductNameSuffix() { return targetProductNameSuffix; } public void setTargetProductNameSuffix(final String suffix) { targetProductNameSuffix = suffix; } public File getTargetFolder() { if (targetProductSelector != null) { final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel(); return targetProductSelectorModel.getProductDir(); } return null; } public String getTargetFormat() { if (targetProductSelector != null) { final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel(); return targetProductSelectorModel.getFormatName(); } return null; } public void setTargetFolder(final File path) { if (targetProductSelector != null) { final TargetProductSelectorModel targetProductSelectorModel = targetProductSelector.getModel(); targetProductSelectorModel.setProductDir(path); } } public int getFileCount() { return productSetTable.getFileCount(); } public File[] getFileList() { return productSetTable.getFileList(); } public File[] getSelectedFiles() { return productSetTable.getModel().getFilesAt(productSetTable.getSelectedRows()); } public Object getValueAt(final int r, final int c) { return productSetTable.getModel().getValueAt(r, c); } public void setProductFileList(final File[] productFileList) { productSetTable.setFiles(productFileList); if(productFileList.length < AUTO_POPULATE_DETAILS_LIMIT) { productSetTable.getModel().refresh(); } } private enum MOVE { UP, DOWN, TOP, BOTTOM } private static class MoveButtonActionListener implements ActionListener { private final FileTable table; private final FileTableModel tableModel; private final MOVE movement; MoveButtonActionListener(FileTable table, FileTableModel tableModel, MOVE movement) { this.table = table; this.tableModel = tableModel; this.movement = movement; } public void actionPerformed(final ActionEvent e) { final int[] selRows = table.getSelectedRows(); final java.util.List<File> filesToMove = new ArrayList<>(selRows.length); for (int row : selRows) { filesToMove.add(tableModel.getFileAt(row)); } int pos = 0; for (File file : filesToMove) { int index = tableModel.getIndexOf(file); if (index > 0 && movement.equals(MOVE.TOP)) { tableModel.move(index, pos++); } else if (index > 0 && movement.equals(MOVE.UP)) { tableModel.move(index, index - 1); } else if (index < tableModel.getRowCount() && movement.equals(MOVE.DOWN)) { tableModel.move(index, index + 1); } else if (index < tableModel.getRowCount() && movement.equals(MOVE.BOTTOM)) { tableModel.move(index, tableModel.getRowCount()-1); } } } } }
18,032
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphBuilderDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/GraphBuilderDialog.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import com.bc.ceres.binding.ConverterRegistry; import com.bc.ceres.core.ProgressMonitor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.common.ReadOp; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.converters.JtsGeometryConverter; import org.esa.snap.core.util.converters.RectangleConverter; import org.esa.snap.core.util.io.SnapFileFilter; import org.esa.snap.engine_utilities.gpf.CommonReaders; import org.esa.snap.engine_utilities.util.ProductFunctions; import org.esa.snap.engine_utilities.util.ResourceUtils; import org.esa.snap.graphbuilder.gpf.ui.ProductSetReaderOpUI; import org.esa.snap.graphbuilder.gpf.ui.SourceUI; import org.esa.snap.graphbuilder.gpf.ui.UIValidation; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphDialog; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphExecuter; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphNode; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphPanel; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphStruct; import org.esa.snap.graphbuilder.rcp.dialogs.support.GraphsMenu; import org.esa.snap.graphbuilder.rcp.progress.LabelBarProgressMonitor; import org.esa.snap.graphbuilder.rcp.utils.DialogUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.tango.TangoIcons; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.ModelessDialog; import org.esa.snap.ui.help.HelpDisplayer; import org.openide.util.HelpCtx; import javax.swing.AbstractButton; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.SwingWorker; import javax.swing.plaf.basic.BasicBorders; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Rectangle; import java.awt.Toolkit; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Observable; import java.util.Observer; /** * Provides the User Interface for creating, loading and saving Graphs */ public class GraphBuilderDialog extends ModelessDialog implements Observer, GraphDialog, LabelBarProgressMonitor.ProgressBarListener, HelpCtx.Provider { static { registerConverters(); } private static final ImageIcon processIcon = TangoIcons.actions_media_playback_start(TangoIcons.Res.R22); private static final ImageIcon saveIcon = TangoIcons.actions_document_save_as(TangoIcons.Res.R22); private static final ImageIcon loadIcon = TangoIcons.actions_document_open(TangoIcons.Res.R22); private static final ImageIcon clearIcon = TangoIcons.actions_edit_clear(TangoIcons.Res.R22); private static final ImageIcon helpIcon = TangoIcons.apps_help_browser(TangoIcons.Res.R22); private static final ImageIcon infoIcon = TangoIcons.apps_accessories_text_editor(TangoIcons.Res.R22); private final AppContext appContext; private GraphPanel graphPanel = null; private JLabel statusLabel = null; private String lastWarningMsg = ""; private JPanel progressPanel = null; private JProgressBar progressBar = null; private LabelBarProgressMonitor progBarMonitor = null; private JLabel progressMsgLabel = null; private boolean initGraphEnabled = true; private final GraphExecuter graphEx; private boolean isProcessing = false; private boolean allowGraphBuilding = true; private final List<ProcessingListener> listenerList = new ArrayList<>(1); private Map<String, Object> selectedConfiguration = null; private List<GraphStruct> previousConfiguration = new ArrayList<>(); private String selectedId = null; public final static String LAST_GRAPH_PATH = "graphbuilder.last_graph_path"; private JTabbedPane tabbedPanel = null; private GraphNode selectedNode; public GraphBuilderDialog(final AppContext theAppContext, final String title, final String helpID) { this(theAppContext, title, helpID, true); } public GraphBuilderDialog(final AppContext theAppContext, final String title, final String helpID, final boolean allowGraphBuilding) { super(theAppContext.getApplicationWindow(), title, 0, helpID); this.allowGraphBuilding = allowGraphBuilding; appContext = theAppContext; graphEx = new GraphExecuter(); graphEx.addObserver(this); String lastDir = SnapApp.getDefault().getPreferences().get(LAST_GRAPH_PATH, ResourceUtils.getGraphFolder("").toFile().getAbsolutePath()); if (new File(lastDir).exists()) { SnapApp.getDefault().getPreferences().put(LAST_GRAPH_PATH, lastDir); } initUI(); } @Override public HelpCtx getHelpCtx() { return new HelpCtx("addLandCoverBand"); } /** * Initializes the dialog components */ private void initUI() { if (this.allowGraphBuilding) { super.getJDialog().setMinimumSize(new Dimension(700, 750)); } else { super.getJDialog().setMinimumSize(new Dimension(700, 550)); } final JPanel mainPanel = new JPanel(new BorderLayout(4, 4)); // mid panel final JPanel midPanel = new JPanel(new BorderLayout(4, 4)); tabbedPanel = new JTabbedPane(); //tabbedPanel.setTabPlacement(JTabbedPane.LEFT); tabbedPanel.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); tabbedPanel.addChangeListener(e -> tabChanged()); statusLabel = new JLabel(""); statusLabel.setForeground(new Color(255, 0, 0)); midPanel.add(tabbedPanel, BorderLayout.CENTER); midPanel.add(statusLabel, BorderLayout.SOUTH); if (allowGraphBuilding) { graphPanel = new GraphPanel(graphEx); graphPanel.setBackground(Color.WHITE); graphPanel.setPreferredSize(new Dimension(1500, 1000)); final JScrollPane scrollPane = new JScrollPane(graphPanel); scrollPane.setPreferredSize(new Dimension(300, 300)); final JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scrollPane, midPanel); splitPane.setOneTouchExpandable(true); splitPane.setResizeWeight(0.4); if(!allowGraphBuilding) { splitPane.setDividerLocation(0); } splitPane.setBorder(new BasicBorders.MarginBorder()); mainPanel.add(splitPane, BorderLayout.CENTER); } else { mainPanel.add(midPanel, BorderLayout.CENTER); } // south panel final JPanel southPanel = new JPanel(new BorderLayout(4, 4)); final JPanel buttonPanel = new JPanel(); initButtonPanel(buttonPanel); southPanel.add(buttonPanel, BorderLayout.CENTER); // progress Bar progressBar = new JProgressBar(); progressBar.setName(getClass().getName() + "progressBar"); progressBar.setStringPainted(true); progressPanel = new JPanel(); progressPanel.setLayout(new BorderLayout(2, 2)); progressMsgLabel = new JLabel(); progressPanel.add(progressMsgLabel, BorderLayout.NORTH); progressPanel.add(progressBar, BorderLayout.CENTER); progBarMonitor = new LabelBarProgressMonitor(progressBar, progressMsgLabel); progBarMonitor.addListener(this); final JButton progressCancelBtn = new JButton("Cancel"); progressCancelBtn.addActionListener(e -> cancelProcessing()); progressPanel.add(progressCancelBtn, BorderLayout.EAST); progressPanel.setVisible(false); southPanel.add(progressPanel, BorderLayout.SOUTH); mainPanel.add(southPanel, BorderLayout.SOUTH); if (getJDialog().getJMenuBar() == null && allowGraphBuilding) { final GraphsMenu operatorMenu = new GraphsMenu(getJDialog(), this); getJDialog().setJMenuBar(operatorMenu.createDefaultMenu()); } setContent(mainPanel); } private void tabChanged() { if (changesAreDetected()) { validateAllNodes(); } } private static boolean equals(Map<String, Object> a, Map<String, Object> b){ if (a == null && b == null) return true; if (a == null || b == null) return false; if (a.keySet().size() == b.keySet().size()) { for (String key : a.keySet()) { if (!b.containsKey(key)) return false; Object objA = a.get(key); Object objB = b.get(key); if (objA != null && objB != null) { if (!objA.toString().equals(objB.toString())) return false; } if (objA == null ^ objB == null) return false; } return true; } return false; } private boolean changesAreDetected() { boolean result = false; List<GraphStruct> currentStruct = GraphStruct.copyGraphStruct(this.graphEx.getGraphNodes()); if (this.selectedId != null) { if (GraphStruct.deepEqual(currentStruct, previousConfiguration)) { result = !equals(this.selectedConfiguration, this.selectedNode.getOperatorUIParameterMap()); } else { // the graph has changed and so you need to reverify result = true; } } this.previousConfiguration = currentStruct; if (this.tabbedPanel.getSelectedIndex() >= 0){ this.selectedId = this.tabbedPanel.getTitleAt(this.tabbedPanel.getSelectedIndex()); for (GraphNode n: this.graphEx.getGraphNodes()) { if (n.getID().equals(this.selectedId)) { this.selectedNode = (n); this.selectedConfiguration = new HashMap<>(n.getOperatorUIParameterMap()); } } if (this.selectedConfiguration == null) { System.err.println("WARNING [org.snap.graphbuilder.rcp.dialogs.GraphBuilderDialog]: Node `"+selectedId+"`not found"); this.selectedId = null; } } else { this.selectedId = null; } return result; } private void initButtonPanel(final JPanel panel) { panel.setLayout(new GridBagLayout()); final GridBagConstraints gbc = new GridBagConstraints(); gbc.fill = GridBagConstraints.HORIZONTAL; gbc.anchor = GridBagConstraints.NORTHWEST; final AbstractButton processButton = DialogUtils.createButton("processButton", "Run", processIcon, panel, DialogUtils.ButtonStyle.TextAndIcon); processButton.addActionListener(e -> doProcessing()); final AbstractButton saveButton = DialogUtils.createButton("saveButton", "Save", saveIcon, panel, DialogUtils.ButtonStyle.TextAndIcon); saveButton.addActionListener(e -> saveGraph()); final AbstractButton loadButton = DialogUtils.createButton("loadButton", "Load", loadIcon, panel, DialogUtils.ButtonStyle.TextAndIcon); loadButton.addActionListener(e -> loadGraph()); final AbstractButton clearButton = DialogUtils.createButton("clearButton", "Clear", clearIcon, panel, DialogUtils.ButtonStyle.TextAndIcon); clearButton.addActionListener(e -> clearGraph()); final AbstractButton infoButton = DialogUtils.createButton("infoButton", "Note", infoIcon, panel, DialogUtils.ButtonStyle.TextAndIcon); infoButton.addActionListener(e -> OnInfo()); //getClass().getName() + name final AbstractButton helpButton = DialogUtils.createButton("helpButton", "Help", helpIcon, panel, DialogUtils.ButtonStyle.TextAndIcon); helpButton.addActionListener(e -> OnHelp()); gbc.weightx = 0; if (allowGraphBuilding) { panel.add(loadButton, gbc); panel.add(clearButton, gbc); panel.add(infoButton, gbc); } panel.add(saveButton, gbc); panel.add(helpButton, gbc); panel.add(processButton, gbc); } /** * Validates the input and then call the GPF to execute the graph */ public void doProcessing() { if (validateAllNodes()) { if (!checkIfOutputExists()) { return; } SystemUtils.freeAllMemory(); progressBar.setValue(0); final ProcessThread processThread = new ProcessThread(progBarMonitor); processThread.execute(); } else { showErrorDialog(statusLabel.getText()); } } public void notifyProgressStart() { progressPanel.setVisible(true); } public void notifyProgressDone() { progressPanel.setVisible(false); } private boolean checkIfOutputExists() { final File[] files = graphEx.getPotentialOutputFiles(); for (File file : files) { if (file.exists()) { final int answer = JOptionPane.showOptionDialog(getJDialog(), "File " + file.getPath() + " already exists.\nWould you like to overwrite?", "Overwrite?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, null, null); if (answer == JOptionPane.NO_OPTION) { return false; } } } return true; } private void cancelProcessing() { if (progBarMonitor != null) progBarMonitor.setCanceled(true); } private boolean initGraph() { boolean result = true; try { if (initGraphEnabled) { result = graphEx.initGraph(); } if (!result && allowGraphBuilding) { statusLabel.setText("Graph is incomplete"); } } catch (Exception e) { if (e.getMessage() != null) { statusLabel.setText("Error: " + e.getMessage()); } else { statusLabel.setText("Error: " + e.toString()); } result = false; } return result; } public boolean canSaveGraphs() { return true; } /** * Validates the input and then saves the current graph to a file */ public void saveGraph() { try { final File file = graphEx.saveGraph(); if (file != null) { setTitle(file.getName()); } } catch (GraphException e) { showErrorDialog(e.getMessage()); } } @Override public void setTitle(final String title) { super.setTitle("Graph Builder : " + title); } /** * Loads a new graph from a file */ public void loadGraph() { final SnapFileFilter fileFilter = new SnapFileFilter("XML", "xml", "Graph"); final File graphFile = Dialogs.requestFileForOpen("Load Graph", false, fileFilter, LAST_GRAPH_PATH); if (graphFile == null) return; loadGraph(graphFile); } /** * Loads a new graph from a file * * @param file the graph file to load */ public void loadGraph(final File file) { try { loadGraph(new FileInputStream(file), file); if (allowGraphBuilding) { setTitle(file.getName()); } } catch (IOException e) { SnapApp.getDefault().handleError("Unable to load graph " + file.toString(), e); } } /** * Loads a new graph from a file * * @param fileStream the graph file to load */ public void loadGraph(final InputStream fileStream, final File file) { try { initGraphEnabled = false; tabbedPanel.removeAll(); graphEx.loadGraph(fileStream, file, true, true); if (allowGraphBuilding) { graphPanel.showRightClickHelp(false); refreshGraph(); } initGraphEnabled = true; } catch (GraphException e) { showErrorDialog(e.getMessage()); } } private void refreshGraph() { if(graphPanel != null) { graphPanel.repaint(); } } public String getGraphAsString() throws GraphException, IOException { return graphEx.getGraphAsString(); } public void enableInitialInstructions(final boolean flag) { if (this.allowGraphBuilding) { graphPanel.showRightClickHelp(flag); } } /** * Removes all tabs and clears the graph */ private void clearGraph() { initGraphEnabled = false; tabbedPanel.removeAll(); graphEx.clearGraph(); refreshGraph(); initGraphEnabled = true; statusLabel.setText(""); } /** * pass in a file list for a ProductSetReader * * @param productFileList the product files */ public void setInputFiles(final File[] productFileList) { final GraphNode productSetNode = graphEx.getGraphNodeList().findGraphNodeByOperator("ProductSet-Reader"); if (productSetNode != null) { ProductSetReaderOpUI ui = (ProductSetReaderOpUI) productSetNode.getOperatorUI(); ui.setProductFileList(productFileList); } } /** * pass in a file list for a ProductSetReader * * @param product the product files */ public void setInputFile(final Product product) { final GraphNode readerNode = graphEx.getGraphNodeList().findGraphNodeByOperator( ReadOp.Spi.getOperatorAlias(ReadOp.class)); if (readerNode != null) { SourceUI ui = (SourceUI) readerNode.getOperatorUI(); ui.setSourceProduct(product); validateAllNodes(); } } /** * Call Help */ private void OnHelp() { HelpDisplayer.show(getHelpID()); } /** * Call description dialog */ private void OnInfo() { final PromptDialog dlg = new PromptDialog("Graph Description", "Description", graphEx.getGraphDescription(), PromptDialog.TYPE.TEXTAREA); dlg.show(); if (dlg.IsOK()) { try { graphEx.setGraphDescription(dlg.getValue("Description")); } catch (Exception ex) { Dialogs.showError(ex.getMessage()); } } } public boolean isProcessing() { return isProcessing; } /** * lets all operatorUIs validate their parameters * If parameter validation fails then a list of the failures is presented to the user * * @return true if validation passes */ private boolean validateAllNodes() { if (isProcessing) return false; boolean isValid = true; final StringBuilder errorMsg = new StringBuilder(100); final StringBuilder warningMsg = new StringBuilder(100); for (GraphNode n : graphEx.getGraphNodes()) { try { final UIValidation validation = n.validateParameterMap(); if (validation.getState() == UIValidation.State.ERROR) { isValid = false; errorMsg.append(validation.getMsg()).append('\n'); } else if (validation.getState() == UIValidation.State.WARNING) { warningMsg.append(validation.getMsg()).append('\n'); } } catch (Exception e) { isValid = false; errorMsg.append(e.getMessage()).append('\n'); } } statusLabel.setForeground(new Color(255, 0, 0)); statusLabel.setText(""); final String warningStr = warningMsg.toString(); if (!isValid) { statusLabel.setText(errorMsg.toString()); return false; } else if (!warningStr.isEmpty()) { if (warningStr.length() > 100 && !warningStr.equals(lastWarningMsg)) { Dialogs.showWarning(warningStr); lastWarningMsg = warningStr; } else { statusLabel.setForeground(new Color(0, 100, 255)); statusLabel.setText("Warning: " + warningStr); } } return initGraph(); } public void addListener(final ProcessingListener listener) { if (!listenerList.contains(listener)) { listenerList.add(listener); } } public void removeListener(final ProcessingListener listener) { listenerList.remove(listener); } private void notifyMSG(final ProcessingListener.MSG msg, final String text) { for (final ProcessingListener listener : listenerList) { listener.notifyMSG(msg, text); } } private void notifyMSG(final ProcessingListener.MSG msg, final File[] fileList) { for (final ProcessingListener listener : listenerList) { listener.notifyMSG(msg, fileList); } } /** * Implements the functionality of Observer participant of Observer Design Pattern to define a one-to-many * dependency between a Subject object and any number of Observer objects so that when the * Subject object changes state, all its Observer objects are notified and updated automatically. * <p> * Defines an updating interface for objects that should be notified of changes in a subject. * * @param subject The Observerable subject * @param data optional data */ public void update(Observable subject, Object data) { try { final GraphExecuter.GraphEvent event = (GraphExecuter.GraphEvent) data; final GraphNode node = (GraphNode) event.getData(); final GraphExecuter.events eventType = event.getEventType(); switch(eventType) { case ADD_EVENT: tabbedPanel.addTab(node.getID(), null, createOperatorTab(node), node.getID() + " Operator"); refreshGraph(); break; case REMOVE_EVENT: tabbedPanel.remove(tabbedPanel.indexOfTab(node.getID())); refreshGraph(); break; case SELECT_EVENT: int newTabIndex = tabbedPanel.indexOfTab(node.getID()); if(tabbedPanel.getSelectedIndex() != newTabIndex) { tabbedPanel.setSelectedIndex(newTabIndex); } break; case CONNECT_EVENT: validateAllNodes(); break; case REFRESH_EVENT: refreshGraph(); break; default: throw new Exception("Unhandled GraphExecuter event " + eventType.name()); } } catch (Exception e) { String msg = e.getMessage(); if (msg == null || msg.isEmpty()) { msg = e.toString(); } statusLabel.setText(msg); } } private JComponent createOperatorTab(final GraphNode node) { return node.getOperatorUI().CreateOpTab(node.getOperatorName(), node.getParameterMap(), appContext); } private class ProcessThread extends SwingWorker<GraphExecuter, Object> { private final ProgressMonitor pm; private Date executeStartTime = null; private boolean errorOccured = false; ProcessThread(final ProgressMonitor pm) { this.pm = pm; } @Override protected GraphExecuter doInBackground() { pm.beginTask("Processing Graph...", 10); try { executeStartTime = Calendar.getInstance().getTime(); isProcessing = true; graphEx.executeGraph(pm); } catch (Throwable e) { System.out.print(e.getMessage()); if (e.getMessage() != null && !e.getMessage().isEmpty()) statusLabel.setText(e.getMessage()); else statusLabel.setText(e.getCause().toString()); errorOccured = true; } finally { isProcessing = false; graphEx.disposeGraphContext(); // free cache SystemUtils.freeAllMemory(); pm.done(); } return graphEx; } @Override public void done() { if (!errorOccured) { final Date now = Calendar.getInstance().getTime(); final long totalSeconds = (now.getTime() - executeStartTime.getTime()) / 1000; statusLabel.setText(ProductFunctions.getProcessingStatistics(totalSeconds)); final List<File> fileList = graphEx.getProductsToOpenInDAT(); final File[] files = fileList.toArray(new File[0]); notifyMSG(ProcessingListener.MSG.DONE, files); ProcessingStats stats = openTargetProducts(files); statusLabel.setText(ProductFunctions.getProcessingStatistics(totalSeconds, stats.totalBytes, stats.totalPixels)); if (SnapApp.getDefault().getPreferences().getBoolean(GPF.BEEP_AFTER_PROCESSING_PROPERTY, false)) { Toolkit.getDefaultToolkit().beep(); } } } } private ProcessingStats openTargetProducts(final File[] fileList) { ProcessingStats stats = new ProcessingStats(); if (fileList.length != 0) { for (File file : fileList) { try { final Product product = CommonReaders.readProduct(file); if (product != null) { appContext.getProductManager().addProduct(product); stats.totalBytes += ProductFunctions.getRawStorageSize(product); stats.totalPixels = ProductFunctions.getTotalPixels(product); } } catch (IOException e) { showErrorDialog(e.getMessage()); } } } return stats; } private static class ProcessingStats { long totalBytes = 0; long totalPixels = 0; } public static File getInternalGraphFolder() { return ResourceUtils.getGraphFolder("internal").toFile(); } public static File getStandardGraphFolder() { return ResourceUtils.getGraphFolder("Standard Graphs").toFile(); } public interface ProcessingListener { enum MSG {DONE, UPDATE} void notifyMSG(final MSG msg, final File[] fileList); void notifyMSG(final MSG msg, final String text); } private static void registerConverters() { final ConverterRegistry converterRegistry = ConverterRegistry.getInstance(); JtsGeometryConverter.registerConverter(); RectangleConverter rectConverter = new RectangleConverter(); converterRegistry.setConverter(Rectangle.class, rectConverter); } }
28,593
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PromptDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/PromptDialog.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import org.esa.snap.graphbuilder.rcp.utils.DialogUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.GridBagUtils; import org.esa.snap.ui.ModalDialog; import javax.swing.*; import javax.swing.text.JTextComponent; import java.awt.*; import java.util.HashMap; import java.util.Map; /** * Created by IntelliJ IDEA. * User: lveci * Date: Jun 5, 2008 * To change this template use File | Settings | File Templates. */ public class PromptDialog extends ModalDialog { private boolean ok = false; private final Map<String, JComponent> componentMap = new HashMap<>(); public enum TYPE { TEXTFIELD, TEXTAREA, CHECKBOX, PASSWORD } public PromptDialog(final String title, final String label, final String defaultValue, final TYPE type) { this(title, new Descriptor[] {new Descriptor(label, defaultValue, type)}); } public PromptDialog(final String title, final Descriptor[] descriptorList) { super(SnapApp.getDefault().getMainFrame(), title, ModalDialog.ID_OK_CANCEL, null); final JPanel content = GridBagUtils.createPanel(); final GridBagConstraints gbc = DialogUtils.createGridBagConstraints(); gbc.insets.right = 4; gbc.insets.top = 2; for(Descriptor descriptor : descriptorList) { final JComponent prompt = addComponent(content, gbc, descriptor.label, descriptor.defaultValue, descriptor.type); componentMap.put(descriptor.label, prompt); gbc.gridy++; } getJDialog().setMinimumSize(new Dimension(400, 100)); setContent(content); } private static JComponent addComponent(final JPanel content, final GridBagConstraints gbc, final String label, final String defaultValue, final TYPE type) { if (type.equals(TYPE.CHECKBOX)) { final JCheckBox checkBox = new JCheckBox(label); checkBox.setSelected(!defaultValue.isEmpty()); content.add(checkBox, gbc); return checkBox; } JTextComponent textComp; if (type.equals(TYPE.TEXTAREA)) { final JTextArea textArea = new JTextArea(defaultValue); textArea.setColumns(50); textArea.setRows(7); textComp = textArea; } else { gbc.gridx = 0; content.add(new JLabel(label), gbc); gbc.weightx = 2; gbc.gridx = 1; if (type.equals(TYPE.PASSWORD)) { textComp = new JPasswordField(defaultValue); ((JPasswordField)textComp).setEchoChar('*'); } else { textComp = new JTextField(defaultValue); } gbc.weightx = 1; } textComp.setEditable(true); content.add(textComp, gbc); gbc.gridx = 0; return textComp; } public String getValue(final String label) throws Exception { final JComponent component = componentMap.get(label); if(component instanceof JTextComponent) { final JTextComponent textComponent = (JTextComponent) component; return textComponent.getText(); } throw new Exception(label + " is not a JTextComponent"); } public boolean isSelected(final String label) throws Exception { final JComponent component = componentMap.get(label); if(component instanceof JCheckBox) { final JCheckBox checkBox = (JCheckBox) component; return checkBox.isSelected(); } throw new Exception(label + " is not a JCheckBox"); } protected void onOK() { ok = true; hide(); } public boolean IsOK() { return ok; } public static class Descriptor { public final String label; final String defaultValue; public final TYPE type; public Descriptor(final String label, final String defaultValue, final TYPE type) { this.label = label; this.defaultValue = defaultValue; this.type = type; } } }
4,851
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CheckListDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/CheckListDialog.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import org.esa.snap.rcp.SnapApp; import org.esa.snap.ui.ModalDialog; import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Generic Check List Dialog */ public class CheckListDialog extends ModalDialog { private final List<JToggleButton> toggleList = new ArrayList<>(3); protected final Map<String, Boolean> items; private final boolean singleSelection; private boolean ok = false; public CheckListDialog(final String title) { this(title, new HashMap<>(3), false); } public CheckListDialog(final String title, final Map<String, Boolean> items, final boolean singleSelection) { super(SnapApp.getDefault().getMainFrame(), title, ModalDialog.ID_OK, null); this.items = items; this.singleSelection = singleSelection; initContent(); } protected void initContent() { final JPanel content = new JPanel(); content.setLayout(new BoxLayout(content, BoxLayout.Y_AXIS)); final ButtonGroup group = new ButtonGroup(); for (String name : items.keySet()) { final JToggleButton btn; if (singleSelection) { btn = new JRadioButton(name); group.add(btn); } else { btn = new JCheckBox(name); } toggleList.add(btn); content.add(btn); btn.setSelected(items.get(name)); } getJDialog().setMinimumSize(new Dimension(200, 100)); setContent(content); } protected void onOK() { for (JToggleButton btn : toggleList) { items.put(btn.getText(), btn.isSelected()); } ok = true; hide(); } public boolean IsOK() { return ok; } }
2,608
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SingleOperatorDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/SingleOperatorDialog.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.PropertySet; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueSet; import com.bc.ceres.core.SubProgressMonitor; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import com.bc.ceres.swing.selection.AbstractSelectionChangeListener; import com.bc.ceres.swing.selection.Selection; import com.bc.ceres.swing.selection.SelectionChangeEvent; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNodeEvent; import org.esa.snap.core.datamodel.ProductNodeListener; import org.esa.snap.core.datamodel.RasterDataNode; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.Operator; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.common.WriteOp; import org.esa.snap.core.gpf.descriptor.OperatorDescriptor; import org.esa.snap.core.gpf.internal.OperatorExecutor; import org.esa.snap.core.gpf.internal.OperatorProductReader; import org.esa.snap.core.gpf.internal.RasterDataNodeValues; import org.esa.snap.core.gpf.ui.DefaultIOParametersPanel; import org.esa.snap.core.gpf.ui.OperatorMenu; import org.esa.snap.core.gpf.ui.OperatorParameterSupport; import org.esa.snap.core.gpf.ui.ParameterUpdater; import org.esa.snap.core.gpf.ui.SingleTargetProductDialog; import org.esa.snap.core.gpf.ui.SourceProductSelector; import org.esa.snap.core.gpf.ui.TargetProductSelectorModel; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.engine_utilities.gpf.CommonReaders; import org.esa.snap.engine_utilities.util.ProductFunctions; import org.esa.snap.graphbuilder.gpf.ui.OperatorUI; import org.esa.snap.graphbuilder.gpf.ui.OperatorUIRegistry; import org.esa.snap.graphbuilder.gpf.ui.UIValidation; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.actions.file.SaveProductAsAction; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.UIUtils; import javax.media.jai.JAI; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.JTabbedPane; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; /** */ public class SingleOperatorDialog extends SingleTargetProductDialog { private final OperatorUI opUI; private JLabel statusLabel; private JComponent parametersPanel; private final String operatorName; private final OperatorDescriptor operatorDescriptor; private DefaultIOParametersPanel ioParametersPanel; private final OperatorParameterSupport parameterSupport; private final BindingContext bindingContext; private JTabbedPane form; private PropertyDescriptor[] rasterDataNodeTypeProperties; private String targetProductNameSuffix; private ProductChangedHandler productChangedHandler; public SingleOperatorDialog(String operatorName, AppContext appContext, String title, String helpID) { super(appContext, title, ID_APPLY_CLOSE, helpID); this.operatorName = operatorName; targetProductNameSuffix = ""; OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(operatorName); if (operatorSpi == null) { throw new IllegalArgumentException("No SPI found for operator name '" + operatorName + "'"); } operatorDescriptor = operatorSpi.getOperatorDescriptor(); ioParametersPanel = new DefaultIOParametersPanel(getAppContext(), operatorDescriptor, getTargetProductSelector()); parameterSupport = new OperatorParameterSupport(operatorDescriptor, null, null, new GraphBuilderParameterUpdater()); final ArrayList<SourceProductSelector> sourceProductSelectorList = ioParametersPanel.getSourceProductSelectorList(); final PropertySet propertySet = parameterSupport.getPropertySet(); bindingContext = new BindingContext(propertySet); if (propertySet.getProperties().length > 0) { if (!sourceProductSelectorList.isEmpty()) { Property[] properties = propertySet.getProperties(); List<PropertyDescriptor> rdnTypeProperties = new ArrayList<>(properties.length); for (Property property : properties) { PropertyDescriptor parameterDescriptor = property.getDescriptor(); if (parameterDescriptor.getAttribute(RasterDataNodeValues.ATTRIBUTE_NAME) != null) { rdnTypeProperties.add(parameterDescriptor); } } rasterDataNodeTypeProperties = rdnTypeProperties.toArray( new PropertyDescriptor[rdnTypeProperties.size()]); } } productChangedHandler = new ProductChangedHandler(); if (!sourceProductSelectorList.isEmpty()) { sourceProductSelectorList.get(0).addSelectionChangeListener(productChangedHandler); } opUI = OperatorUIRegistry.CreateOperatorUI(operatorName); addParameters(); getJDialog().setMinimumSize(new Dimension(450, 450)); statusLabel = new JLabel(""); statusLabel.setForeground(new Color(255, 0, 0)); this.getJDialog().getContentPane().add(statusLabel, BorderLayout.NORTH); } @Override public int show() { ioParametersPanel.initSourceProductSelectors(); if (form == null) { initForm(); if (getJDialog().getJMenuBar() == null) { final OperatorMenu operatorMenu = createDefaultMenuBar(); getJDialog().setJMenuBar(operatorMenu.createDefaultMenu()); } } setContent(form); return super.show(); } @Override public void hide() { productChangedHandler.releaseProduct(); ioParametersPanel.releaseSourceProductSelectors(); super.hide(); } @Override protected Product createTargetProduct() { if (validateUI()) { SystemUtils.freeAllMemory(); opUI.updateParameters(); final HashMap<String, Product> sourceProducts = ioParametersPanel.createSourceProductsMap(); return GPF.createProduct(operatorName, parameterSupport.getParameterMap(), sourceProducts); } return null; } public String getTargetProductNameSuffix() { return targetProductNameSuffix; } public void setTargetProductNameSuffix(String suffix) { targetProductNameSuffix = suffix; } private void initForm() { form = new JTabbedPane(); form.add("I/O Parameters", ioParametersPanel); //if (bindingContext.getPropertySet().getProperties().length > 0) { // final PropertyPane parametersPane = new PropertyPane(bindingContext); // final JPanel parametersPanel = parametersPane.createPanel(); // parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); // form.add("Processing Parameters", new JScrollPane(parametersPanel)); // updateSourceProduct(); //} parametersPanel = opUI.CreateOpTab(operatorName, parameterSupport.getParameterMap(), appContext); parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); form.add("Processing Parameters", new JScrollPane(parametersPanel)); } private OperatorMenu createDefaultMenuBar() { return new OperatorMenu(getJDialog(), operatorDescriptor, parameterSupport, getAppContext(), getHelpID()); } private void updateSourceProduct() { try { Property property = bindingContext.getPropertySet().getProperty(UIUtils.PROPERTY_SOURCE_PRODUCT); if (property != null) { property.setValue(productChangedHandler.currentProduct); } } catch (ValidationException e) { throw new IllegalStateException("Property '" + UIUtils.PROPERTY_SOURCE_PRODUCT + "' must be of type " + Product.class + ".", e); } } private void addParameters() { final PropertySet propertySet = parameterSupport.getPropertySet(); final List<SourceProductSelector> sourceProductSelectorList = ioParametersPanel.getSourceProductSelectorList(); if (sourceProductSelectorList.isEmpty()) { Dialogs.showError("SourceProduct @Parameter not found in operator"); } else { sourceProductSelectorList.get(0).addSelectionChangeListener(new AbstractSelectionChangeListener() { @Override public void selectionChanged(SelectionChangeEvent event) { final Product selectedProduct = (Product) event.getSelection().getSelectedValue(); if (selectedProduct != null) { //&& form != null) { final TargetProductSelectorModel targetProductSelectorModel = getTargetProductSelector().getModel(); targetProductSelectorModel.setProductName(selectedProduct.getName() + getTargetProductNameSuffix()); opUI.setSourceProducts(new Product[]{selectedProduct}); } } }); } if (propertySet.getProperties().length > 0) { if (!sourceProductSelectorList.isEmpty()) { Property[] properties = propertySet.getProperties(); List<PropertyDescriptor> rdnTypeProperties = new ArrayList<>(properties.length); for (Property property : properties) { PropertyDescriptor parameterDescriptor = property.getDescriptor(); if (parameterDescriptor.getAttribute(RasterDataNodeValues.ATTRIBUTE_NAME) != null) { rdnTypeProperties.add(parameterDescriptor); } } rasterDataNodeTypeProperties = rdnTypeProperties.toArray( new PropertyDescriptor[rdnTypeProperties.size()]); } } } private boolean validateUI() { final UIValidation validation = opUI.validateParameters(); if (validation.getState() == UIValidation.State.WARNING) { final String msg = "Warning: " + validation.getMsg() + "\n\nWould you like to continue?"; return Dialogs.requestDecision("Warning", msg, false, null) == Dialogs.Answer.YES; } else if (validation.getState() == UIValidation.State.ERROR) { final String msg = "Error: " + validation.getMsg(); Dialogs.showError(msg); return false; } return true; } @Override protected void onApply() { if (!canApply()) { return; } String productDir = targetProductSelector.getModel().getProductDir().getAbsolutePath(); SnapApp.getDefault().getPreferences().put(SaveProductAsAction.PREFERENCES_KEY_LAST_PRODUCT_DIR, productDir); statusLabel.setText(""); Product targetProduct = null; try { targetProduct = createTargetProduct(); //if (targetProduct == null) { //throw new NullPointerException("Target product is null."); //} } catch (Throwable t) { handleInitialisationError(t); } if (targetProduct == null) { return; } targetProduct.setName(targetProductSelector.getModel().getProductName()); if (targetProductSelector.getModel().isSaveToFileSelected()) { targetProduct.setFileLocation(targetProductSelector.getModel().getProductFile()); final ProgressMonitorSwingWorker worker = new ProductWriterWorker(targetProduct); //worker.executeWithBlocking(); worker.execute(); } else if (targetProductSelector.getModel().isOpenInAppSelected()) { appContext.getProductManager().addProduct(targetProduct); showOpenInAppInfo(); } } private class ProductWriterWorker extends ProgressMonitorSwingWorker<Product, Object> { private final Product targetProduct; private Date executeStartTime; private ProductWriterWorker(Product targetProduct) { super(getJDialog(), "Writing Target Product"); this.targetProduct = targetProduct; } @Override protected Product doInBackground(com.bc.ceres.core.ProgressMonitor pm) throws Exception { final TargetProductSelectorModel model = getTargetProductSelector().getModel(); pm.beginTask("Writing...", model.isOpenInAppSelected() ? 100 : 95); Product product = null; try { // free cache // NESTMOD JAI.getDefaultInstance().getTileCache().flush(); System.gc(); executeStartTime = Calendar.getInstance().getTime(); long t0 = System.currentTimeMillis(); Operator operator = null; if (targetProduct.getProductReader() instanceof OperatorProductReader) { final OperatorProductReader opReader = (OperatorProductReader) targetProduct.getProductReader(); Operator op = opReader.getOperatorContext().getOperator(); OperatorDescriptor descriptor = op.getSpi().getOperatorDescriptor(); if (descriptor.isAutoWriteDisabled()) { operator = op; } } if (operator == null) { WriteOp writeOp = new WriteOp(targetProduct, model.getProductFile(), model.getFormatName()); writeOp.setDeleteOutputOnFailure(true); writeOp.setWriteEntireTileRows(true); writeOp.setClearCacheAfterRowWrite(false); operator = writeOp; } final OperatorExecutor executor = OperatorExecutor.create(operator); executor.execute(SubProgressMonitor.create(pm, 95)); File targetFile = model.getProductFile(); if (model.isOpenInAppSelected() && targetFile.exists()) { product = CommonReaders.readProduct(targetFile); if (product == null) { product = targetProduct; // todo - check - this cannot be ok!!! (nf) } pm.worked(5); } } finally { // free cache JAI.getDefaultInstance().getTileCache().flush(); System.gc(); pm.done(); if (product != targetProduct) { targetProduct.dispose(); } } return product; } @Override protected void done() { final TargetProductSelectorModel model = getTargetProductSelector().getModel(); try { final Product targetProduct = get(); if(targetProduct != null) { final Date now = Calendar.getInstance().getTime(); final long totalSeconds = (now.getTime() - executeStartTime.getTime()) / 1000; final long totalBytes = ProductFunctions.getRawStorageSize(targetProduct); final long totalPixels = ProductFunctions.getTotalPixels(targetProduct); statusLabel.setText(ProductFunctions.getProcessingStatistics(totalSeconds, totalBytes, totalPixels)); if (model.isOpenInAppSelected()) { appContext.getProductManager().addProduct(targetProduct); //showSaveAndOpenInAppInfo(saveTime); } else { //showSaveInfo(saveTime); } } } catch (InterruptedException e) { // ignore } catch (ExecutionException e) { handleProcessingError(e.getCause()); } catch (Throwable t) { handleProcessingError(t); } } } private class ProductChangedHandler extends AbstractSelectionChangeListener implements ProductNodeListener { private Product currentProduct; void releaseProduct() { if (currentProduct != null) { currentProduct.removeProductNodeListener(this); currentProduct = null; updateSourceProduct(); } } @Override public void selectionChanged(SelectionChangeEvent event) { Selection selection = event.getSelection(); if (selection != null) { final Product selectedProduct = (Product) selection.getSelectedValue(); if (selectedProduct != currentProduct) { if (currentProduct != null) { currentProduct.removeProductNodeListener(this); } currentProduct = selectedProduct; if (currentProduct != null) { currentProduct.addProductNodeListener(this); } updateTargetProductName(); updateValueSets(currentProduct); updateSourceProduct(); } } } @Override public void nodeAdded(ProductNodeEvent event) { handleProductNodeEvent(); } @Override public void nodeChanged(ProductNodeEvent event) { handleProductNodeEvent(); } @Override public void nodeDataChanged(ProductNodeEvent event) { handleProductNodeEvent(); } @Override public void nodeRemoved(ProductNodeEvent event) { handleProductNodeEvent(); } private void updateTargetProductName() { String productName = ""; if (currentProduct != null) { productName = currentProduct.getName(); } final TargetProductSelectorModel targetProductSelectorModel = getTargetProductSelector().getModel(); targetProductSelectorModel.setProductName(productName + getTargetProductNameSuffix()); } private void handleProductNodeEvent() { updateValueSets(currentProduct); } private void updateValueSets(Product product) { if (rasterDataNodeTypeProperties != null) { for (PropertyDescriptor propertyDescriptor : rasterDataNodeTypeProperties) { updateValueSet(propertyDescriptor, product); } } } } private static void updateValueSet(PropertyDescriptor propertyDescriptor, Product product) { String[] values = new String[0]; if (product != null) { Object object = propertyDescriptor.getAttribute(RasterDataNodeValues.ATTRIBUTE_NAME); if (object != null) { @SuppressWarnings("unchecked") Class<? extends RasterDataNode> rasterDataNodeType = (Class<? extends RasterDataNode>) object; boolean includeEmptyValue = !propertyDescriptor.isNotNull() && !propertyDescriptor.isNotEmpty() && !propertyDescriptor.getType().isArray(); values = RasterDataNodeValues.getNames(product, rasterDataNodeType, includeEmptyValue); } } propertyDescriptor.setValueSet(new ValueSet(values)); } private class GraphBuilderParameterUpdater implements ParameterUpdater { @Override public void handleParameterSaveRequest(Map<String, Object> parameterMap) { opUI.updateParameters(); } @Override public void handleParameterLoadRequest(Map<String, Object> parameterMap) throws ValidationException, ConversionException { opUI.initParameters(); } } }
21,179
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BatchGraphDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/BatchGraphDialog.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.graphbuilder.rcp.dialogs; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.core.SubProgressMonitor; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorException; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.util.StringUtils; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.engine_utilities.gpf.CommonReaders; import org.esa.snap.engine_utilities.gpf.ProcessTimeMonitor; import org.esa.snap.engine_utilities.util.ResourceUtils; import org.esa.snap.graphbuilder.rcp.dialogs.support.*; import org.esa.snap.graphbuilder.rcp.progress.LabelBarProgressMonitor; import org.esa.snap.rcp.SnapApp; import org.esa.snap.remote.execution.operator.RemoteExecutionDialog; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.FileChooserFactory; import org.esa.snap.ui.ModelessDialog; import javax.swing.*; import java.awt.*; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Provides the dialog for executing a graph on a list of products */ public class BatchGraphDialog extends ModelessDialog implements GraphDialog, LabelBarProgressMonitor.ProgressBarListener { protected final static Path defaultGraphPath = ResourceUtils.getGraphFolder(""); protected final List<GraphExecuter> graphExecutorList = new ArrayList<>(10); private final AppContext appContext; private final String baseTitle; private final List<BatchProcessListener> listenerList = new ArrayList<>(1); private final boolean closeOnDone; protected ProductSetPanel productSetPanel; protected File graphFile; protected boolean openProcessedProducts; private JTabbedPane tabbedPane; private JLabel statusLabel, bottomStatusLabel; private JPanel progressPanel; private JProgressBar progressBar; private LabelBarProgressMonitor progBarMonitor; private Map<File, File[]> slaveFileMap; private boolean skipExistingTargetFiles; private boolean replaceWritersWithUniqueTargetProduct; private boolean isProcessing; public BatchGraphDialog(final AppContext theAppContext, final String title, final String helpID, final boolean closeOnDone) { super(theAppContext.getApplicationWindow(), title, ID_YES | ID_APPLY_CLOSE_HELP, getRunRemoteIfWindows(), helpID); this.appContext = theAppContext; this.baseTitle = title; this.closeOnDone = closeOnDone; openProcessedProducts = true; setContent(createUI()); if (getJDialog().getJMenuBar() == null) { final GraphsMenu operatorMenu = new GraphsMenu(getJDialog(), this); getJDialog().setJMenuBar(operatorMenu.createDefaultMenu()); } super.getJDialog().setMinimumSize(new Dimension(600, 400)); } private static String[] getRunRemoteIfWindows() { if (org.apache.commons.lang3.SystemUtils.IS_OS_WINDOWS || org.apache.commons.lang3.SystemUtils.IS_OS_LINUX) { return new String[]{"Run remote"}; } return null; } private static File getFilePath(Component component, String title) { final File graphPath = new File(SnapApp.getDefault().getPreferences().get("batch.last_graph_path", defaultGraphPath.toFile().getAbsolutePath())); final JFileChooser chooser = FileChooserFactory.getInstance().createFileChooser(graphPath); chooser.setMultiSelectionEnabled(false); chooser.setDialogTitle(title); if (chooser.showDialog(component, "OK") == JFileChooser.APPROVE_OPTION) { final File file = chooser.getSelectedFile(); SnapApp.getDefault().getPreferences().put("batch.last_graph_path", file.getAbsolutePath()); return file; } return null; } /** * For coregistration * * @param graphEx the graph executer * @param productSetID the product set reader * @param masterFile master file * @param slaveFiles slave file list */ protected static void setSlaveIO(final GraphExecuter graphEx, final String productSetID, final File masterFile, final File[] slaveFiles) { final GraphNode productSetNode = graphEx.getGraphNodeList().findGraphNodeByOperator(productSetID); if (productSetNode != null) { StringBuilder str = new StringBuilder(masterFile.getAbsolutePath()); for (File slaveFile : slaveFiles) { str.append(','); str.append(slaveFile.getAbsolutePath()); } graphEx.setOperatorParam(productSetNode.getID(), "fileList", str.toString()); } } @Override protected void onOther() { final List<File> sourceProductFiles = getSourceProductFiles(); if (sourceProductFiles.isEmpty()) { showErrorDialog("Please add at least one source product."); } else if (this.graphFile == null) { showErrorDialog("Please add the graph file."); } else { final Window parentWindow = getJDialog().getOwner(); close(); final RemoteExecutionDialog dialog = new RemoteExecutionDialog(appContext, parentWindow) { @Override protected void onAboutToShow() { super.onAboutToShow(); setData(sourceProductFiles, graphFile, productSetPanel.getTargetFormat()); } }; dialog.show(); } } private JPanel createUI() { final JPanel mainPanel = new JPanel(new BorderLayout(4, 4)); tabbedPane = new JTabbedPane(); tabbedPane.addChangeListener(e -> validateAllNodes()); mainPanel.add(tabbedPane, BorderLayout.CENTER); // status statusLabel = new JLabel(""); statusLabel.setForeground(new Color(255, 0, 0)); mainPanel.add(statusLabel, BorderLayout.NORTH); bottomStatusLabel = new JLabel(""); getButtonPanel().add(bottomStatusLabel, 0); // progress Bar progressBar = new JProgressBar(); progressBar.setName(getClass().getName() + "progressBar"); progressBar.setStringPainted(true); progressPanel = new JPanel(); progressPanel.setLayout(new BorderLayout(2, 2)); progressPanel.add(progressBar, BorderLayout.CENTER); final JLabel progressMsgLabel = new JLabel(); progressPanel.add(progressMsgLabel, BorderLayout.NORTH); progBarMonitor = new LabelBarProgressMonitor(progressBar, progressMsgLabel); progBarMonitor.addListener(this); final JButton progressCancelBtn = new JButton("Cancel"); progressCancelBtn.addActionListener(e -> cancelProcessing()); progressPanel.add(progressCancelBtn, BorderLayout.EAST); progressPanel.setVisible(false); mainPanel.add(progressPanel, BorderLayout.SOUTH); productSetPanel = new ProductSetPanel(appContext, null, new FileTable(), false, true); tabbedPane.add("I/O Parameters", productSetPanel); getButton(ID_APPLY).setText("Run"); getButton(ID_YES).setText("Load Graph"); return mainPanel; } @Override public int show() { return super.show(); } @Override public void hide() { if (progBarMonitor != null) { progBarMonitor.setCanceled(true); } notifyMSG(BatchProcessListener.BatchMSG.CLOSE); super.hide(); } @Override public void onApply() { if (isProcessing) { return; } productSetPanel.onApply(); skipExistingTargetFiles = false; replaceWritersWithUniqueTargetProduct = true; try { doProcessing(); } catch (Exception e) { statusLabel.setText(e.getMessage()); bottomStatusLabel.setText(""); } } public boolean isProcessing() { return isProcessing; } public void addListener(final BatchProcessListener listener) { if (!listenerList.contains(listener)) { listenerList.add(listener); } } public void removeListener(final BatchProcessListener listener) { listenerList.remove(listener); } private void notifyMSG(final BatchProcessListener.BatchMSG msg, final String text) { for (final BatchProcessListener listener : listenerList) { listener.notifyMSG(msg, text); } } private void notifyMSG(final BatchProcessListener.BatchMSG msg) { for (final BatchProcessListener listener : listenerList) { listener.notifyMSG(msg, productSetPanel.getFileList(), getAllBatchProcessedTargetProducts()); } } /** * OnLoad */ @Override protected void onYes() { loadGraph(); } public void setInputFiles(final File[] productFileList) { productSetPanel.setProductFileList(productFileList); } public void setTargetFolder(final File path) { productSetPanel.setTargetFolder(path); } public void loadGraph() { if (isProcessing) return; final File file = getFilePath(this.getContent(), "Graph File"); if (file != null) { loadGraph(file); } } public void loadGraph(final File file) { try { graphFile = file; initGraphs(); addGraphTabs("", true); setTitle(file.getName()); } catch (Exception e) { SnapApp.getDefault().handleError("Unable to load graph " + file.toString(), e); } } @Override public void setTitle(final String title) { super.setTitle(baseTitle + " : " + title); } public boolean canSaveGraphs() { return false; } public void saveGraph() { } public String getGraphAsString() throws GraphException, IOException { if (!graphExecutorList.isEmpty()) { return graphExecutorList.get(0).getGraphAsString(); } return ""; } @Override protected void onClose() { cancelProcessing(); super.onClose(); } private void initGraphs() { try { deleteGraphs(); createGraphs(); } catch (Exception e) { statusLabel.setText(e.getMessage()); bottomStatusLabel.setText(""); } } /** * Validates the input and then call the GPF to execute the graph */ private void doProcessing() { if (validateAllNodes()) { SystemUtils.freeAllMemory(); progressBar.setValue(0); final SwingWorker<Boolean, Object> processThread = new ProcessThread(progBarMonitor); processThread.execute(); } else { if (statusLabel.getText() != null && !statusLabel.getText().isEmpty()) showErrorDialog(statusLabel.getText()); } } public void notifyProgressStart() { progressPanel.setVisible(true); } public void notifyProgressDone() { progressPanel.setVisible(false); } private void cancelProcessing() { if (progBarMonitor != null) progBarMonitor.setCanceled(true); } private void deleteGraphs() { for (GraphExecuter gex : graphExecutorList) { gex.clearGraph(); } graphExecutorList.clear(); } /** * Loads a new graph from a file * * @param executer the GraphExcecuter * @param graphFile the graph file to load * @param addUI add a user interface */ protected void loadGraph(final GraphExecuter executer, final File graphFile, final boolean addUI) { try { executer.loadGraph(new FileInputStream(graphFile), graphFile, addUI, true); ensureWriteNodeTargetReset(executer.getGraphNodes()); } catch (Exception e) { showErrorDialog(e.getMessage()); } } static void ensureWriteNodeTargetReset(GraphNode[] graphNodes) { for (final GraphNode node : graphNodes) { if (node.getID().equals("Write")) { Map<String, Object> parameterMap = node.getParameterMap(); parameterMap.remove("file"); } } } private boolean validateAllNodes() { if (isProcessing) { return false; } if (productSetPanel == null) { return false; } if (graphExecutorList.isEmpty()) { return false; } boolean result; statusLabel.setText(""); try { cloneGraphs(); assignParameters(); // first graph must pass result = graphExecutorList.get(0).initGraph(); } catch (Exception e) { statusLabel.setText(e.getMessage()); bottomStatusLabel.setText(""); result = false; } return result; } private List<File> getSourceProductFiles() { final File[] sourceFiles = productSetPanel.getFileList(); final List<File> sourceProductFiles = new ArrayList<>(); for (final File sourceFile : sourceFiles) { if (StringUtils.isNotNullAndNotEmpty(sourceFile.getPath())) { sourceProductFiles.add(sourceFile); } } return sourceProductFiles; } protected ProductSetPanel getProductSetPanel() { return productSetPanel; } public void setTargetProductNameSuffix(final String suffix) { productSetPanel.setTargetProductNameSuffix(suffix); } private void createGraphs() throws GraphException { try { final GraphExecuter graphEx = new GraphExecuter(); loadGraph(graphEx, graphFile, true); graphExecutorList.add(graphEx); } catch (Exception e) { throw new GraphException(e.getMessage()); } } private void addGraphTabs(final String title, final boolean addUI) { if (graphExecutorList.isEmpty()) { return; } tabbedPane.setSelectedIndex(0); while (tabbedPane.getTabCount() > 1) { tabbedPane.remove(tabbedPane.getTabCount() - 1); } final GraphExecuter graphEx = graphExecutorList.get(0); for (GraphNode n : graphEx.getGraphNodes()) { if (n.getOperatorUI() == null) continue; if (n.getNode().getOperatorName().equals("Read") || (replaceWritersWithUniqueTargetProduct && n.getNode().getOperatorName().equals("Write")) || n.getNode().getOperatorName().equals("ProductSet-Reader")) { n.setOperatorUI(null); continue; } if (addUI) { String tabTitle = title; if (tabTitle.isEmpty()) tabTitle = n.getOperatorName(); tabbedPane.addTab(tabTitle, null, n.getOperatorUI().CreateOpTab(n.getOperatorName(), n.getParameterMap(), appContext), n.getID() + " Operator"); } } } public void setSlaveFileMap(Map<File, File[]> fileMap) { slaveFileMap = fileMap; } protected void assignParameters() { final File targetFolder = productSetPanel.getTargetFolder(); if (targetFolder != null && !targetFolder.exists()) { if (!targetFolder.mkdirs()) { final String msg = "Unable to create folders in " + targetFolder; SystemUtils.LOG.severe(msg); throw new OperatorException(msg); } } final File[] fileList = productSetPanel.getFileList(); int graphIndex = 0; for (File file : fileList) { final String name = FileUtils.getFilenameWithoutExtension(file); final File targetFile = targetFolder == null ? null : new File(targetFolder, name); final String targetFormat = productSetPanel.getTargetFormat(); setIO(graphExecutorList.get(graphIndex), file, targetFile, targetFormat); if (slaveFileMap != null) { final File[] slaveFiles = slaveFileMap.get(file); if (slaveFiles != null) { setSlaveIO(graphExecutorList.get(graphIndex), "ProductSet-Reader", file, slaveFiles); } } ++graphIndex; } } protected void setIO(final GraphExecuter graphEx, final File readPath, final File writePath, final String format) { final GraphNode readNode = graphEx.getGraphNodeList().findGraphNodeByOperator("Read"); if (readNode != null) { graphEx.setOperatorParam(readNode.getID(), "file", readPath.getAbsolutePath()); } if (replaceWritersWithUniqueTargetProduct) { final GraphNode[] writeNodes = graphEx.getGraphNodeList().findAllGraphNodeByOperator("Write"); for (GraphNode writeNode : writeNodes) { if (format != null) { graphEx.setOperatorParam(writeNode.getID(), "formatName", format); } if (writePath != null) { graphEx.setOperatorParam(writeNode.getID(), "file", writePath.getAbsolutePath()); } } } } private void openTargetProducts() { final File[] fileList = getAllBatchProcessedTargetProducts(); for (File file : fileList) { try { final Product product = CommonReaders.readProduct(file); if (product != null) { appContext.getProductManager().addProduct(product); } } catch (IOException e) { showErrorDialog(e.getMessage()); } } } protected void cloneGraphs() throws Exception { final GraphExecuter graphEx = graphExecutorList.get(0); for (int graphIndex = 1; graphIndex < graphExecutorList.size(); ++graphIndex) { final GraphExecuter cloneGraphEx = graphExecutorList.get(graphIndex); cloneGraphEx.clearGraph(); } graphExecutorList.clear(); graphExecutorList.add(graphEx); final File[] fileList = productSetPanel.getFileList(); for (int graphIndex = 1; graphIndex < fileList.length; ++graphIndex) { final GraphExecuter cloneGraphEx = new GraphExecuter(); loadGraph(cloneGraphEx, graphFile, false); graphExecutorList.add(cloneGraphEx); // copy UI parameter to clone final GraphNode[] cloneGraphNodes = cloneGraphEx.getGraphNodes(); for (GraphNode cloneNode : cloneGraphNodes) { final GraphNode node = graphEx.getGraphNodeList().findGraphNode(cloneNode.getID()); if (node != null) { cloneNode.setOperatorUI(node.getOperatorUI()); } } } } private File[] getAllBatchProcessedTargetProducts() { final List<File> targetFileList = new ArrayList<>(); for (GraphExecuter graphEx : graphExecutorList) { targetFileList.addAll(graphEx.getProductsToOpenInDAT()); } return targetFileList.toArray(new File[0]); } ///// public interface BatchProcessListener { void notifyMSG(final BatchMSG msg, final File[] inputFileList, final File[] targetFileList); void notifyMSG(final BatchMSG msg, final String text); enum BatchMSG {DONE, UPDATE, CLOSE} } private class ProcessThread extends SwingWorker<Boolean, Object> { final List<String> errMsgs = new ArrayList<>(); private final ProgressMonitor pm; private final ProcessTimeMonitor timeMonitor = new ProcessTimeMonitor(); private boolean errorOccured = false; public ProcessThread(final ProgressMonitor pm) { this.pm = pm; } @Override protected Boolean doInBackground() { pm.beginTask("Processing Graph...", graphExecutorList.size()); try { timeMonitor.start(); isProcessing = true; final File[] existingFiles = productSetPanel.getTargetFolder() != null ? productSetPanel.getTargetFolder().listFiles(File::isFile) : null; final File[] fileList = productSetPanel.getFileList(); int graphIndex = 0; for (GraphExecuter graphEx : graphExecutorList) { if (pm.isCanceled()) { break; } final String nOfm = (graphIndex + 1) + " of " + graphExecutorList.size() + ' '; final String statusText = nOfm + fileList[graphIndex].getName(); try { graphEx.initGraph(); graphEx.initGraph(); if (shouldSkip(graphEx, existingFiles)) { statusLabel.setText("Skipping " + statusText); notifyMSG(BatchProcessListener.BatchMSG.UPDATE, statusText); pm.worked(1); ++graphIndex; continue; } else { statusLabel.setText("Processing " + statusText); notifyMSG(BatchProcessListener.BatchMSG.UPDATE, statusText); graphEx.executeGraph(SubProgressMonitor.create(pm, 1)); graphEx.disposeGraphContext(); SystemUtils.freeAllMemory(); } } catch (Exception e) { SystemUtils.LOG.severe(e.getMessage()); String filename = fileList[graphIndex].getName(); errMsgs.add(filename + " -> " + e.getMessage()); } ++graphIndex; // calculate time remaining final long duration = timeMonitor.getCurrentDuration(); final double timePerGraph = duration / (double) graphIndex; final long timeLeft = (long) (timePerGraph * (graphExecutorList.size() - graphIndex)); if (timeLeft > 0) { String remainingStr = "Estimated " + ProcessTimeMonitor.formatDuration(timeLeft) + " remaining"; if (!errMsgs.isEmpty()) remainingStr += " (Errors occurred)"; bottomStatusLabel.setText(remainingStr); } } } catch (Exception e) { SystemUtils.LOG.severe(e.getMessage()); if (e.getMessage() != null && !e.getMessage().isEmpty()) statusLabel.setText(e.getMessage()); else statusLabel.setText(e.toString()); errorOccured = true; } finally { final long duration = timeMonitor.stop(); statusLabel.setText("Processing completed in " + ProcessTimeMonitor.formatDuration(duration)); isProcessing = false; pm.done(); if (openProcessedProducts) { bottomStatusLabel.setText("Opening resulting products..."); } } return true; } @Override public void done() { if (!errorOccured) { if (openProcessedProducts) { openTargetProducts(); } bottomStatusLabel.setText(""); } if (!errMsgs.isEmpty()) { final StringBuilder msg = new StringBuilder("The following errors occurred:\n"); for (String errStr : errMsgs) { msg.append(errStr); msg.append('\n'); } showErrorDialog(msg.toString()); } notifyMSG(BatchProcessListener.BatchMSG.DONE); if (closeOnDone) { close(); } if (SnapApp.getDefault().getPreferences().getBoolean(GPF.BEEP_AFTER_PROCESSING_PROPERTY, false)) { Toolkit.getDefaultToolkit().beep(); } } private boolean shouldSkip(final GraphExecuter graphEx, final File[] existingFiles) { if (skipExistingTargetFiles) { if (existingFiles != null) { final File[] targetFiles = graphEx.getPotentialOutputFiles(); boolean allTargetsExist = true; for (File targetFile : targetFiles) { final String targetPath = targetFile.getAbsolutePath(); boolean fileExists = false; for (File existingFile : existingFiles) { if (existingFile.getAbsolutePath().equalsIgnoreCase(targetPath)) { fileExists = true; break; } } if (!fileExists) { allTargetsExist = false; break; } } return allTargetsExist; } } return false; } } }
26,562
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ActionFileSystem.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/ActionFileSystem.java
package org.esa.snap.graphbuilder.rcp.dialogs.support; import org.esa.snap.core.util.SystemUtils; import org.openide.filesystems.FileObject; import org.openide.filesystems.FileUtil; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class ActionFileSystem { final Map<String, FileObject> operatorFileMap = new HashMap<>(); public ActionFileSystem() { this("Actions/Operators"); } public ActionFileSystem(final String path) { final FileObject fileObj = FileUtil.getConfigFile(path); if (fileObj == null) { return; } final FileObject[] files = fileObj.getChildren(); for (FileObject file : files) { final String operatorName = (String) file.getAttribute("operatorName"); if(operatorName != null) { operatorFileMap.put(operatorName, file); } } } public FileObject getOperatorFile(final String opName) { return operatorFileMap.get(opName); } public static FileObject findOperatorFile(final String opName) { final FileObject fileObj = FileUtil.getConfigFile("Actions/Operators"); if (fileObj == null) { SystemUtils.LOG.warning("No Operator Actions found."); return null; } final FileObject[] files = fileObj.getChildren(); final List<FileObject> orderedFiles = FileUtil.getOrder(Arrays.asList(files), true); for (FileObject file : orderedFiles) { final String operatorName = (String) file.getAttribute("operatorName"); if(opName.equals(operatorName)) { return file; } } return null; } }
1,746
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphStruct.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GraphStruct.java
package org.esa.snap.graphbuilder.rcp.dialogs.support; import java.util.ArrayList; import java.util.List; public class GraphStruct { private List<String> leafs; private String id; private GraphStruct(String id, List<String> leafs) { this.id = id; this.leafs = leafs; } public GraphStruct copy() { ArrayList<String> leafs = new ArrayList<>(); for (String gs : this.leafs) { leafs.add(gs); } return new GraphStruct(this.id, leafs); } @Override public boolean equals(Object obj) { if (obj instanceof GraphStruct) { GraphStruct gs = (GraphStruct) obj; if (gs.id.equals(this.id) && gs.leafs.size() == this.leafs.size()) { for (String child : gs.leafs) { if (!this.leafs.contains(child)) return false; } return true; } } return false; } static public List<GraphStruct> copyGraphStruct(GraphNode[] nodes) { ArrayList<GraphStruct> list = new ArrayList<>(); for (GraphNode g: nodes) { ArrayList<String> children = new ArrayList<>(g.getSources()); list.add(new GraphStruct(g.getID(), children)); } return list; } static public boolean deepEqual(List<GraphStruct> a, List<GraphStruct> b) { if (a.size() == b.size()) { for (GraphStruct key: a) { if (!b.contains(key)) return false; } return true; } return false; } }
1,629
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
BaseFileModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/BaseFileModel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import org.esa.snap.core.datamodel.Product; import org.esa.snap.engine_utilities.gpf.CommonReaders; import org.esa.snap.rcp.SnapApp; import javax.swing.*; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableColumnModel; import java.io.File; import java.util.ArrayList; import java.util.List; public abstract class BaseFileModel extends AbstractTableModel implements FileTableModel { protected String titles[] = null; protected Class types[] = null; protected int widths[] = null; protected final List<File> fileList = new ArrayList<>(10); private final List<TableData> dataList = new ArrayList<>(10); public BaseFileModel() { setColumnData(); addBlankFile(); } protected abstract void setColumnData(); protected abstract TableData createFileStats(final File file); public File[] getFileList() { return fileList.toArray(new File[fileList.size()]); } public void addFile(final File file) { fileList.add(file); clearBlankFile(); dataList.add(createFileStats(file)); fireTableDataChanged(); } public void addFile(final File file, final String[] values) { fileList.add(file); clearBlankFile(); dataList.add(new TableData(values)); fireTableDataChanged(); } public void removeFile(final int index) { fileList.remove(index); dataList.remove(index); fireTableDataChanged(); } public void move(final int oldIndex, final int newIndex) { if ((oldIndex < 1 && oldIndex > newIndex) || oldIndex > fileList.size() || newIndex < 0 || newIndex >= fileList.size()) return; final File file = fileList.get(oldIndex); final TableData data = dataList.get(oldIndex); fileList.remove(oldIndex); dataList.remove(oldIndex); fileList.add(newIndex, file); dataList.add(newIndex, data); fireTableDataChanged(); } public int getIndexOf(final File file) { return fileList.indexOf(file); } /** * Needed for drag and drop */ private void addBlankFile() { addFile(new File("")); } private void clearBlankFile() { if (fileList.size() > 1 && fileList.get(0).getName().isEmpty()) { removeFile(0); } } public void refresh() { for(TableData data : dataList) { data.refresh(); } } public void clear() { fileList.clear(); dataList.clear(); addBlankFile(); fireTableDataChanged(); } // Implement the methods of the TableModel interface we're interested // in. Only getRowCount(), getColumnCount() and getValueAt() are // required. The other methods tailor the look of the table. public int getRowCount() { return dataList.size(); } public int getColumnCount() { return titles.length; } @Override public String getColumnName(final int c) { return titles[c]; } @Override public Class getColumnClass(final int c) { return types[c]; } public Object getValueAt(final int r, final int c) { return dataList.get(r).data[c]; } public File getFileAt(final int index) { return fileList.get(index); } public File[] getFilesAt(final int[] indices) { final List<File> files = new ArrayList<>(indices.length); for (int i : indices) { files.add(fileList.get(i)); } return files.toArray(new File[files.size()]); } public void setColumnWidths(final TableColumnModel columnModel) { for (int i = 0; i < widths.length; ++i) { columnModel.getColumn(i).setMinWidth(widths[i]); columnModel.getColumn(i).setPreferredWidth(widths[i]); columnModel.getColumn(i).setWidth(widths[i]); } } public class TableData { protected final String data[] = new String[titles.length]; protected final File file; public TableData(final File file) { this.file = file; updateData(); } TableData(final String[] values) { System.arraycopy(values, 0, data, 0, data.length); this.file = null; } public void refresh() { readProduct(file); } protected void updateData() { } protected void updateData(final Product product) { } private void readProduct(final File file) { if(file == null) return; final SwingWorker worker = new SwingWorker() { @Override protected Object doInBackground() throws Exception { try { if (!file.getName().isEmpty()) { try { Product product = getProductFromProductManager(file); if (product == null) { product = CommonReaders.readProduct(file); } updateData(product); } catch (Exception ex) { updateData(); } } } finally { fireTableDataChanged(); } return null; } }; worker.execute(); } Product getProductFromProductManager(final File file) { final SnapApp app = SnapApp.getDefault(); if(app != null) { final Product[] products = app.getProductManager().getProducts(); for(Product p : products) { if(file.equals(p.getFileLocation())) { return p; } } } return null; } } }
6,815
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphExecuter.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GraphExecuter.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.binding.dom.XppDomElement; import com.bc.ceres.core.ProgressMonitor; import com.thoughtworks.xstream.io.xml.xppdom.XppDom; import org.apache.commons.math3.util.FastMath; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.OperatorSpiRegistry; import org.esa.snap.core.gpf.annotations.OperatorMetadata; import org.esa.snap.core.gpf.common.WriteOp; import org.esa.snap.core.gpf.graph.Graph; import org.esa.snap.core.gpf.graph.GraphContext; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.gpf.graph.GraphIO; import org.esa.snap.core.gpf.graph.GraphProcessor; import org.esa.snap.core.gpf.graph.Node; import org.esa.snap.core.util.io.FileUtils; import org.esa.snap.core.util.io.SnapFileFilter; import org.esa.snap.engine_utilities.gpf.ReaderUtils; import org.esa.snap.graphbuilder.gpf.ui.OperatorUI; import org.esa.snap.graphbuilder.gpf.ui.OperatorUIRegistry; import org.esa.snap.rcp.util.Dialogs; import javax.swing.*; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Observable; import java.util.Set; public class GraphExecuter extends Observable { private final GPF gpf; private Graph graph; private GraphContext graphContext = null; private GraphProcessor processor; private String graphDescription = ""; private File lastLoadedGraphFile = null; private final GraphNodeList graphNodeList = new GraphNodeList(); private final static String LAST_GRAPH_PATH = "graphbuilder.last_graph_path"; public enum events {ADD_EVENT, REMOVE_EVENT, SELECT_EVENT, CONNECT_EVENT, REFRESH_EVENT} public GraphExecuter() { gpf = GPF.getDefaultInstance(); graph = new Graph("Graph"); } public GraphNode[] getGraphNodes() { return graphNodeList.getGraphNodes(); } public GraphNodeList getGraphNodeList() { return graphNodeList; } public void clearGraph() { graph = null; graph = new Graph("Graph"); lastLoadedGraphFile = null; graphNodeList.clear(); } public void setSelectedNode(GraphNode node) { if (node == null) return; notifyGraphEvent(new GraphEvent(events.SELECT_EVENT, node)); } /** * Gets the list of operators * * @return set of operator names */ public Set<String> GetOperatorList() { return gpf.getOperatorSpiRegistry().getAliases(); } boolean isOperatorInternal(String alias) { final OperatorSpiRegistry registry = gpf.getOperatorSpiRegistry(); final OperatorSpi operatorSpi = registry.getOperatorSpi(alias); final OperatorMetadata operatorMetadata = operatorSpi.getOperatorClass().getAnnotation(OperatorMetadata.class); return !(operatorMetadata != null && !operatorMetadata.internal()); } String getOperatorCategory(String alias) { final OperatorSpiRegistry registry = gpf.getOperatorSpiRegistry(); final OperatorSpi operatorSpi = registry.getOperatorSpi(alias); final OperatorMetadata operatorMetadata = operatorSpi.getOperatorClass().getAnnotation(OperatorMetadata.class); if (operatorMetadata != null) return operatorMetadata.category(); return ""; } public GraphNode addOperator(final String opName) { String id = opName; int cnt = 1; while (graphNodeList.findGraphNode(id) != null) { ++cnt; id = opName + '(' + cnt + ')'; } final GraphNode newGraphNode = createNewGraphNode(graph, opName, id); notifyGraphEvent(new GraphEvent(events.ADD_EVENT, newGraphNode)); return newGraphNode; } static GraphNode createNewGraphNode(final Graph graph, final GraphNodeList graphNodeList, final String opName, final String id) { final Node newNode = new Node(id, opName); final XppDomElement parameters = new XppDomElement("parameters"); newNode.setConfiguration(parameters); graph.addNode(newNode); final GraphNode newGraphNode = new GraphNode(newNode); graphNodeList.add(newGraphNode); newGraphNode.setOperatorUI(OperatorUIRegistry.CreateOperatorUI(newGraphNode.getOperatorName())); return newGraphNode; } private GraphNode createNewGraphNode(final Graph graph, final String opName, final String id) { final Node newNode = new Node(id, opName); final XppDomElement parameters = new XppDomElement("parameters"); newNode.setConfiguration(parameters); graph.addNode(newNode); final GraphNode newGraphNode = new GraphNode(newNode); graphNodeList.add(newGraphNode); newGraphNode.setOperatorUI(OperatorUIRegistry.CreateOperatorUI(newGraphNode.getOperatorName())); moveWriterToLast(graph); return newGraphNode; } private void moveWriterToLast(final Graph graph) { final String writeOperatorAlias = OperatorSpi.getOperatorAlias(WriteOp.class); final GraphNode writerNode = graphNodeList.findGraphNode(writeOperatorAlias); if (writerNode != null) { removeNode(writerNode); graphNodeList.add(writerNode); graph.addNode(writerNode.getNode()); } } public void removeOperator(final GraphNode node) { notifyGraphEvent(new GraphEvent(events.REMOVE_EVENT, node)); removeNode(node); } private void removeNode(final GraphNode node) { graphNodeList.remove(node); graph.removeNode(node.getID()); } void autoConnectGraph() { final List<GraphNode> nodeList = Arrays.asList(getGraphNodes()); Collections.sort(nodeList, new GraphNodePosComparator()); final GraphNode[] nodes = nodeList.toArray(new GraphNode[nodeList.size()]); for (int i = 0; i < nodes.length - 1; ++i) { if (!nodes[i].hasSources()) { nodes[i].connectOperatorSource(nodes[i + 1].getID()); } } notifyConnection(); } void notifyConnection() { if(graphNodeList.getGraphNodes().length > 0) { notifyGraphEvent(new GraphEvent(events.CONNECT_EVENT, graphNodeList.getGraphNodes()[0])); } } private void notifyGraphEvent(final GraphEvent event) { setChanged(); notifyObservers(event); clearChanged(); } public void setOperatorParam(final String id, final String paramName, final String value) { final Node node = graph.getNode(id); DomElement xml = node.getConfiguration().getChild(paramName); if (xml == null) { xml = new XppDomElement(paramName); node.getConfiguration().addChild(xml); } xml.setValue(value); } public String getOperatorParam(final String id, final String paramName) { final Node node = graph.getNode(id); DomElement xml = node.getConfiguration().getChild(paramName); return xml == null ? null : xml.getValue(); } private void assignAllParameters() throws GraphException { final XppDom presentationXML = new XppDom("Presentation"); // save graph description final XppDom descXML = new XppDom("Description"); descXML.setValue(graphDescription); presentationXML.addChild(descXML); graphNodeList.assignParameters(presentationXML); graph.setAppData("Presentation", presentationXML); } public boolean initGraph() throws GraphException { if (graphNodeList.isGraphComplete()) { assignAllParameters(); ProductSetUIHandler productSetHandler = new ProductSetUIHandler(graph, graphNodeList); SubGraphHandler subGraphHandler = new SubGraphHandler(graph, graphNodeList); try { recreateGraphContext(); graphNodeList.updateGraphNodes(graphContext); //todo recreateGraphContext(); } catch (Exception e) { e.printStackTrace(); throw new GraphException(e.getMessage()); } finally { subGraphHandler.restore(); productSetHandler.restore(); } return true; } return false; } private void recreateGraphContext() throws GraphException { if (graphContext != null) graphContext.dispose(); processor = new GraphProcessor(); graphContext = new GraphContext(graph); } public void disposeGraphContext() { graphContext.dispose(); } /** * Begins graph processing * * @param pm The ProgressMonitor */ public void executeGraph(ProgressMonitor pm) { processor.executeGraph(graphContext, pm); } public File[] getPotentialOutputFiles() { final List<File> fileList = new ArrayList<>(); final Node[] nodes = graph.getNodes(); for (Node n : nodes) { if (n.getOperatorName().startsWith(OperatorSpi.getOperatorAlias(WriteOp.class))) { final DomElement config = n.getConfiguration(); final DomElement fileParam = config.getChild("file"); if (fileParam != null) { final String filePath = fileParam.getValue(); if (filePath != null && !filePath.isEmpty()) { final File file = new File(filePath); fileList.add(file); } } } } return fileList.toArray(new File[fileList.size()]); } public File saveGraph() throws GraphException { String filename = "myGraph"; if (lastLoadedGraphFile != null) filename = lastLoadedGraphFile.getAbsolutePath(); final SnapFileFilter fileFilter = new SnapFileFilter("XML", "xml", "Graph"); final File filePath = Dialogs.requestFileForSave("Save Graph", false, fileFilter, ".xml", filename, null, LAST_GRAPH_PATH); if (filePath != null) writeGraph(filePath.getAbsolutePath()); return filePath; } private void writeGraph(final String filePath) throws GraphException { try (FileWriter fileWriter = new FileWriter(filePath)) { assignAllParameters(); GraphIO.write(graph, fileWriter); } catch (Exception e) { throw new GraphException("Unable to write graph to " + filePath + '\n' + e.getMessage()); } } public String getGraphAsString() throws GraphException, IOException { final StringWriter stringWriter = new StringWriter(); try { assignAllParameters(); GraphIO.write(graph, stringWriter); } catch (Exception e) { throw new GraphException("Unable to write graph to string" + '\n' + e.getMessage()); } finally { stringWriter.close(); } return stringWriter.toString(); } public void loadGraph(final InputStream fileStream, final File file, final boolean addUI, final boolean wait) throws GraphException { try { if (fileStream == null) return; final LoadGraphThread loadGraphThread = new LoadGraphThread(fileStream, addUI); loadGraphThread.execute(); if(wait) { loadGraphThread.get(); } lastLoadedGraphFile = file; } catch (Throwable e) { throw new GraphException("Unable to load graph " + fileStream + '\n' + e.getMessage()); } } private class LoadGraphThread extends SwingWorker<Graph, Object> { private final InputStream fileStream; private final boolean addUI; LoadGraphThread(final InputStream fileStream, final boolean addUI) { this.fileStream = fileStream; this.addUI = addUI; } @Override protected Graph doInBackground() throws Exception { final Graph graphFromFile = GPFProcessor.readGraph(new InputStreamReader(fileStream), null); setGraph(graphFromFile, addUI); notifyGraphEvent(new GraphEvent(events.REFRESH_EVENT, null)); return graphFromFile; } } private void setGraph(final Graph graphFromFile, final boolean addUI) throws GraphException { if (graphFromFile != null) { graph = graphFromFile; graphNodeList.clear(); final XppDom presentationXML = graph.getApplicationData("Presentation"); if (presentationXML != null) { // get graph description final XppDom descXML = presentationXML.getChild("Description"); if (descXML != null && descXML.getValue() != null) { graphDescription = descXML.getValue(); } } final Node[] nodes = graph.getNodes(); for (Node n : nodes) { final GraphNode newGraphNode = new GraphNode(n); if (presentationXML != null) newGraphNode.setDisplayParameters(presentationXML); graphNodeList.add(newGraphNode); if (addUI) { OperatorUI ui = OperatorUIRegistry.CreateOperatorUI(newGraphNode.getOperatorName()); if (ui == null) { throw new GraphException("Unable to load " + newGraphNode.getOperatorName()); } newGraphNode.setOperatorUI(ui); } notifyGraphEvent(new GraphEvent(events.ADD_EVENT, newGraphNode)); } } } public String getGraphDescription() { return graphDescription; } public void setGraphDescription(final String text) { graphDescription = text; } public List<File> getProductsToOpenInDAT() { final List<File> fileList = new ArrayList<>(2); final Node[] nodes = graph.getNodes(); for (Node n : nodes) { if (n.getOperatorName().equalsIgnoreCase(OperatorSpi.getOperatorAlias(WriteOp.class))) { final DomElement config = n.getConfiguration(); final DomElement fileParam = config.getChild("file"); if (fileParam != null) { final String filePath = fileParam.getValue(); if (filePath != null && !filePath.isEmpty()) { final File file = new File(filePath); if (file.exists()) { fileList.add(file); } else { final DomElement formatParam = config.getChild("formatName"); final String format = formatParam.getValue(); final String ext = ReaderUtils.findExtensionForFormat(format); File newFile = new File(file.getAbsolutePath() + ext); if (newFile.exists()) { fileList.add(newFile); } else { final String name = FileUtils.getFilenameWithoutExtension(file); newFile = new File(name + ext); if (newFile.exists()) fileList.add(newFile); } } } } } } return fileList; } /** * Update the nodes in the graph with the given reader file and writer file */ public static void setGraphIO(final GraphExecuter graphEx, final String readID, final File readPath, final String writeID, final File writePath, final String format) { final GraphNode readNode = graphEx.getGraphNodeList().findGraphNode(readID); if (readNode != null) { graphEx.setOperatorParam(readNode.getID(), "file", readPath.getAbsolutePath()); } if (writeID != null) { final GraphNode writeNode = graphEx.getGraphNodeList().findGraphNode(writeID); if (writeNode != null) { graphEx.setOperatorParam(writeNode.getID(), "formatName", format); graphEx.setOperatorParam(writeNode.getID(), "file", writePath.getAbsolutePath()); } } } public static class GraphEvent { private final events eventType; private final Object data; GraphEvent(events type, Object d) { eventType = type; data = d; } public Object getData() { return data; } public events getEventType() { return eventType; } } static class GraphNodePosComparator implements Comparator<GraphNode> { public int compare(GraphNode o1, GraphNode o2) { double x1 = o1.getPos().getX(); double y1 = o1.getPos().getY(); double x2 = o2.getPos().getX(); double y2 = o2.getPos().getY(); double h1 = FastMath.hypot(x1, y1); double h2 = FastMath.hypot(x2, y2); return Double.compare(h2, h1); } } }
18,518
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphsMenu.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GraphsMenu.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.graphbuilder.rcp.dialogs.support; import org.esa.snap.ui.AbstractDialog; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.UIUtils; import org.esa.snap.engine_utilities.util.ResourceUtils; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JScrollPane; import javax.swing.JTextArea; import java.awt.Component; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; /** * Provides a dynamic graphs menu reflecting the graph file contents of ./snap/graphs * * @author Luis Veci */ public class GraphsMenu { private final Component parentComponent; private final GraphDialog graphDialog; private final Action loadAction; private final Action saveAction; private final Action viewGraphXMLAction; public GraphsMenu(final Component parentComponent, final GraphDialog graphDialog) { this.parentComponent = parentComponent; this.graphDialog = graphDialog; loadAction = new LoadAction(); saveAction = new SaveAction(); viewGraphXMLAction = new ViewGraphXMLAction(); } /** * Creates the default menu. * * @return The menu */ public JMenuBar createDefaultMenu() { JMenu fileMenu = new JMenu("File"); fileMenu.add(loadAction); fileMenu.add(saveAction); fileMenu.addSeparator(); fileMenu.add(viewGraphXMLAction); JMenu graphMenu = new JMenu("Graphs"); createGraphMenu(graphMenu, ResourceUtils.getGraphFolder("").toFile()); final JMenuBar menuBar = new JMenuBar(); menuBar.add(fileMenu); menuBar.add(graphMenu); return menuBar; } private void createGraphMenu(final JMenu menu, final File path) { final File[] filesList = path.listFiles(); if (filesList == null || filesList.length == 0) return; for (final File file : filesList) { final String name = file.getName(); if (file.isDirectory() && !file.isHidden() && !name.equalsIgnoreCase("internal")) { final JMenu subMenu = new JMenu(name); menu.add(subMenu); createGraphMenu(subMenu, file); } else if (name.toLowerCase().endsWith(".xml")) { final JMenuItem item = new JMenuItem(name.substring(0, name.indexOf(".xml"))); item.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { graphDialog.loadGraph(file); } }); menu.add(item); } } } private class LoadAction extends AbstractAction { LoadAction() { super("Load Graph"); } @Override public void actionPerformed(ActionEvent event) { graphDialog.loadGraph(); } @Override public boolean isEnabled() { return super.isEnabled(); } } private class SaveAction extends AbstractAction { SaveAction() { super("Save Graph"); } @Override public void actionPerformed(ActionEvent event) { graphDialog.saveGraph(); } @Override public boolean isEnabled() { return super.isEnabled() && graphDialog.canSaveGraphs(); } } private class ViewGraphXMLAction extends AbstractAction { ViewGraphXMLAction() { super("View Graph XML"); } @Override public void actionPerformed(ActionEvent event) { String xml = ""; try { xml = graphDialog.getGraphAsString(); } catch (Exception e) { xml = "Unable to diaplay graph "+ e.toString(); } JTextArea textArea = new JTextArea(xml); textArea.setEditable(false); JScrollPane textAreaScrollPane = new JScrollPane(textArea); textAreaScrollPane.setPreferredSize(new Dimension(360, 360)); showInformationDialog("Graph XML", textAreaScrollPane); } @Override public boolean isEnabled() { return super.isEnabled(); } } private void showInformationDialog(String title, Component component) { final ModalDialog modalDialog = new ModalDialog(UIUtils.getRootWindow(parentComponent), title, AbstractDialog.ID_OK, null); /*I18N*/ modalDialog.setContent(component); modalDialog.show(); } }
5,579
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
TargetFolderSelector.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/TargetFolderSelector.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.bc.ceres.swing.TableLayout; import org.esa.snap.core.gpf.ui.TargetProductSelector; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JLabel; import javax.swing.JPanel; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; /** * Target folder selector */ public class TargetFolderSelector extends TargetProductSelector { private JCheckBox skipExistingCBox = new JCheckBox("Skip existing target files"); private JCheckBox replaceWritersWithUniqueTargetProductCBox = new JCheckBox("Keep source product name"); public JPanel createPanel() { replaceWritersWithUniqueTargetProductCBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { getFormatNameComboBox().setEnabled(replaceWritersWithUniqueTargetProductCBox.isSelected()); getProductDirTextField().setEnabled(replaceWritersWithUniqueTargetProductCBox.isSelected()); } }); final JPanel subPanel2 = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); subPanel2.add(new JLabel("Save as: ")); subPanel2.add(getFormatNameComboBox()); final JPanel subPanel3 = new JPanel(new BorderLayout(3, 3)); subPanel3.add(getProductDirLabel(), BorderLayout.NORTH); subPanel3.add(getProductDirTextField(), BorderLayout.CENTER); subPanel3.add(getProductDirChooserButton(), BorderLayout.EAST); final JPanel subPanel4 = new JPanel(new FlowLayout(FlowLayout.LEADING, 0, 0)); subPanel4.add(skipExistingCBox); subPanel4.add(replaceWritersWithUniqueTargetProductCBox); replaceWritersWithUniqueTargetProductCBox.setSelected(true); final TableLayout tableLayout = new TableLayout(1); tableLayout.setTableAnchor(TableLayout.Anchor.WEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTableWeightX(1.0); tableLayout.setCellPadding(0, 0, new Insets(3, 3, 3, 3)); tableLayout.setCellPadding(1, 0, new Insets(3, 3, 3, 3)); tableLayout.setCellPadding(2, 0, new Insets(3, 3, 3, 3)); tableLayout.setCellPadding(3, 0, new Insets(0, 24, 3, 3)); tableLayout.setCellPadding(4, 0, new Insets(3, 3, 3, 3)); final JPanel panel = new JPanel(tableLayout); panel.setBorder(BorderFactory.createTitledBorder("Target Folder")); panel.add(subPanel2); panel.add(subPanel3); panel.add(subPanel4); panel.add(getOpenInAppCheckBox()); return panel; } public boolean isSkippingExistingTargetFiles() { return skipExistingCBox.isSelected(); } public boolean isReplacingWritersWithUniqueTargetProduct() { return replaceWritersWithUniqueTargetProductCBox.isSelected(); } }
3,721
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GraphDialog.java
package org.esa.snap.graphbuilder.rcp.dialogs.support; import java.io.File; /** * dialogs which are able to handle graphs */ public interface GraphDialog { void loadGraph(); void loadGraph(final File file); boolean canSaveGraphs(); void saveGraph(); String getGraphAsString() throws Exception; }
325
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphNodeList.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GraphNodeList.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.thoughtworks.xstream.io.xml.xppdom.XppDom; import org.esa.snap.core.gpf.graph.GraphContext; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.gpf.graph.NodeContext; import java.util.ArrayList; import java.util.List; /** * Keeps track of GraphNodes */ public class GraphNodeList { private final List<GraphNode> nodeList = new ArrayList<>(10); GraphNode[] getGraphNodes() { return nodeList.toArray(new GraphNode[nodeList.size()]); } void clear() { nodeList.clear(); } public void add(final GraphNode newGraphNode) { nodeList.add(newGraphNode); } public void remove(final GraphNode node) { // remove as a source from all nodes for (GraphNode n : nodeList) { n.disconnectOperatorSources(node.getID()); } nodeList.remove(node); } public GraphNode findGraphNode(String id) { for (GraphNode n : nodeList) { if (n.getID().equals(id)) { return n; } } return null; } public GraphNode findGraphNodeByOperator(String operatorName) { for (GraphNode n : nodeList) { if (n.getOperatorName().equals(operatorName)) { return n; } } return null; } public GraphNode[] findAllGraphNodeByOperator(String operatorName) { final List<GraphNode> resultList = new ArrayList<>(); for (GraphNode n : nodeList) { if (n.getOperatorName().equals(operatorName)) { resultList.add(n); } } return resultList.toArray(new GraphNode[0]); } boolean isGraphComplete() { int nodesWithoutSources = 0; for (GraphNode n : nodeList) { if (!n.hasSources()) { ++nodesWithoutSources; if (!IsNodeASource(n)) return false; } } return nodesWithoutSources != nodeList.size(); } void assignParameters(final XppDom presentationXML) throws GraphException { for (GraphNode n : nodeList) { if (n.getOperatorUI() != null) { n.assignParameters(presentationXML); } } } void updateGraphNodes(final GraphContext graphContext) throws GraphException { if (graphContext != null) { for (GraphNode node : nodeList) { final NodeContext context = graphContext.getNodeContext(node.getNode()); if(context.getOperator() != null) { node.setSourceProducts(context.getSourceProducts()); } node.updateParameters(); } } } private boolean IsNodeASource(final GraphNode sourceNode) { for (GraphNode n : nodeList) { if (n.isNodeSource(sourceNode)) return true; } return false; } GraphNode[] findConnectedNodes(final GraphNode sourceNode) { final List<GraphNode> connectedNodes = new ArrayList<>(); for (GraphNode n : nodeList) { if (n.isNodeSource(sourceNode)) connectedNodes.add(n); } return connectedNodes.toArray(new GraphNode[connectedNodes.size()]); } void switchConnections(final GraphNode oldNode, final String newNodeID) { final GraphNode[] connectedNodes = findConnectedNodes(oldNode); for (GraphNode node : connectedNodes) { node.connectOperatorSource(newNodeID); } } }
4,345
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GraphPanel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import org.esa.snap.core.gpf.graph.NodeSource; import org.esa.snap.core.util.StringUtils; import org.esa.snap.graphbuilder.gpf.ui.OperatorUIRegistry; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.ui.help.HelpDisplayer; import org.openide.filesystems.FileObject; import javax.swing.ImageIcon; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.SwingWorker; import javax.swing.border.BevelBorder; import javax.swing.event.PopupMenuEvent; import javax.swing.event.PopupMenuListener; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.Rectangle2D; import java.util.Arrays; import java.util.Set; /** * Draws and Edits the graph graphically * User: lveci * Date: Jan 15, 2008 */ public class GraphPanel extends JPanel implements ActionListener, PopupMenuListener, MouseListener, MouseMotionListener { private final GraphExecuter graphEx; private JMenu addMenu; private Point lastMousePos = null; private final AddMenuListener addListener = new AddMenuListener(this); private final ConnectMenuListener connectListener = new ConnectMenuListener(this); private final RemoveSourceMenuListener removeSourceListener = new RemoveSourceMenuListener(this); private static final ImageIcon opIcon = new ImageIcon(GraphPanel.class.getClassLoader(). getResource("org/esa/snap/graphbuilder/icons/operator.png")); private static final ImageIcon folderIcon = new ImageIcon(GraphPanel.class.getClassLoader(). getResource("org/esa/snap/graphbuilder/icons/folder.png")); private static final Font font = new Font("Ariel", Font.BOLD, 10); private static final Color opColor = new Color(0, 177, 255, 128); private static final Color selColor = new Color(200, 255, 200, 150); private static final char[] folderDelim = new char[]{'/'};//'\\'}; private GraphNode selectedNode = null; private boolean showHeadHotSpot = false; private boolean showTailHotSpot = false; private boolean connectingSourceFromHead = false; private boolean connectingSourceFromTail = false; private Point connectingSourcePos = null; private GraphNode connectSourceTargetNode = null; private boolean showRightClickHelp = false; private final ActionFileSystem actionFileSystem; public GraphPanel(GraphExecuter graphExec) { graphEx = graphExec; createAddOpMenu(); addMouseListener(this); addMouseMotionListener(this); actionFileSystem = new ActionFileSystem(); } /** * Creates a menu containing the list of operators to the addMenu */ private void createAddOpMenu() { addMenu = new JMenu("Add"); final SwingWorker<Boolean, Object> menuThread = new MenuThread(addMenu, addListener, graphEx); menuThread.execute(); } private static class MenuThread extends SwingWorker<Boolean, Object> { private final JMenu addMenu; private final AddMenuListener addListener; private final GraphExecuter graphEx; MenuThread(final JMenu addMenu, final AddMenuListener addListener, final GraphExecuter graphEx) { this.addMenu = addMenu; this.addListener = addListener; this.graphEx = graphEx; } @Override protected Boolean doInBackground() { // get operator list from graph executor final Set<String> gpfOperatorSet = graphEx.GetOperatorList(); final String[] gpfOperatorList = new String[gpfOperatorSet.size()]; gpfOperatorSet.toArray(gpfOperatorList); Arrays.sort(gpfOperatorList); // add operators for (String anAlias : gpfOperatorList) { if (!graphEx.isOperatorInternal(anAlias) && OperatorUIRegistry.showInGraphBuilder(anAlias)) { final String category = graphEx.getOperatorCategory(anAlias); JMenu menu = addMenu; if (!category.isEmpty()) { final String[] categoryPath = StringUtils.split(category, folderDelim, true); for (String folder : categoryPath) { menu = getMenuFolder(folder, menu); } } final JMenuItem item = new JMenuItem(anAlias, opIcon); item.setHorizontalTextPosition(JMenuItem.RIGHT); item.addActionListener(addListener); menu.add(item); } } return true; } } private static JMenu getMenuFolder(final String folderName, final JMenu currentMenu) { int insertPnt = 0; for (int i = 0; i < currentMenu.getItemCount(); ++i) { JMenuItem item = currentMenu.getItem(i); if (item instanceof JMenu) { int comp = item.getText().compareToIgnoreCase(folderName); if (comp == 0) { return (JMenu) item; } else if (comp < 0) { insertPnt++; } } } final JMenu newMenu = new JMenu(folderName); newMenu.setIcon(folderIcon); currentMenu.insert(newMenu, insertPnt); return newMenu; } private void addOperatorAction(String name) { final GraphNode newGraphNode = graphEx.addOperator(name); newGraphNode.setPos(lastMousePos); repaint(); } private void removeSourceAction(String id) { if (selectedNode != null) { final GraphNode source = graphEx.getGraphNodeList().findGraphNode(id); selectedNode.disconnectOperatorSources(source.getID()); repaint(); } } private void autoConnectGraph() { if (!graphEx.getGraphNodeList().isGraphComplete()) { graphEx.autoConnectGraph(); repaint(); } } /** * Handles menu item pressed events * * @param event the action event */ public void actionPerformed(ActionEvent event) { final String name = event.getActionCommand(); switch (name) { case "Delete": graphEx.removeOperator(selectedNode); repaint(); break; case "Operator Help": callOperatorHelp(selectedNode.getID()); break; } } private void callOperatorHelp(final String id) { FileObject file = ActionFileSystem.findOperatorFile(id); if(file != null) { HelpDisplayer.show((String) file.getAttribute("helpId")); } else { Dialogs.showWarning("Operator help for " + id +" not found."); } } private void checkPopup(MouseEvent e) { if (e.isPopupTrigger()) { final JPopupMenu popup = new JPopupMenu(); popup.add(addMenu); if (selectedNode != null) { final JMenuItem item = new JMenuItem("Delete"); popup.add(item); item.setHorizontalTextPosition(JMenuItem.RIGHT); item.addActionListener(this); if(actionFileSystem.getOperatorFile(selectedNode.getID()) != null) { final JMenuItem operatorHelp = new JMenuItem("Operator Help"); popup.add(operatorHelp); operatorHelp.setHorizontalTextPosition(JMenuItem.RIGHT); operatorHelp.addActionListener(this); } final NodeSource[] sources = selectedNode.getNode().getSources(); if (sources.length > 0) { final JMenu removeSourcedMenu = new JMenu("Remove Source"); for (NodeSource ns : sources) { final JMenuItem nsItem = new JMenuItem(ns.getSourceNodeId()); removeSourcedMenu.add(nsItem); nsItem.setHorizontalTextPosition(JMenuItem.RIGHT); nsItem.addActionListener(removeSourceListener); } popup.add(removeSourcedMenu); } } if (!graphEx.getGraphNodeList().isGraphComplete()) { final JMenuItem connectItem = new JMenuItem("Connect Graph", null); connectItem.setHorizontalTextPosition(JMenuItem.RIGHT); connectItem.addActionListener(connectListener); popup.add(connectItem); } popup.setLabel("Justification"); popup.setBorder(new BevelBorder(BevelBorder.RAISED)); popup.addPopupMenuListener(this); popup.show(this, e.getX(), e.getY()); showRightClickHelp = false; } } public void popupMenuWillBecomeVisible(PopupMenuEvent e) { } public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { } public void popupMenuCanceled(PopupMenuEvent e) { } /** * Paints the panel component * * @param g The Graphics */ @Override protected void paintComponent(java.awt.Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); drawGraph(g2, graphEx.getGraphNodes()); } /** * Draw the graphical representation of the Graph * * @param g the Graphics * @param nodeList the list of graphNodes */ private void drawGraph(Graphics2D g, GraphNode[] nodeList) { if(nodeList.length == 0) return; g.setFont(font); if (showRightClickHelp) { drawHelp(g); } for (GraphNode n : nodeList) { if (n == selectedNode) n.drawNode(g, selColor); else n.drawNode(g, opColor); } // first pass sets the Size in drawNode according to string length for (GraphNode n : nodeList) { // connect source nodes g.setColor(Color.red); final NodeSource[] nSources = n.getNode().getSources(); for (NodeSource nSource : nSources) { final GraphNode srcNode = graphEx.getGraphNodeList().findGraphNode(nSource.getSourceNodeId()); if (srcNode != null) n.drawConnectionLine(g, srcNode); } } if (showHeadHotSpot && selectedNode != null) { selectedNode.drawHeadHotspot(g, Color.red); } if (showTailHotSpot && selectedNode != null) { selectedNode.drawTailHotspot(g, Color.red); } if (connectingSourceFromHead && connectSourceTargetNode != null) { final Point p1 = connectSourceTargetNode.getPos(); final Point p2 = connectingSourcePos; if (p1 != null && p2 != null) { g.setColor(Color.red); g.drawLine(p1.x, p1.y + connectSourceTargetNode.getHalfNodeHeight(), p2.x, p2.y); } } else if (connectingSourceFromTail && connectSourceTargetNode != null) { final Point p1 = connectSourceTargetNode.getPos(); final Point p2 = connectingSourcePos; if (p1 != null && p2 != null) { g.setColor(Color.red); g.drawLine(p1.x + connectSourceTargetNode.getWidth(), p1.y + connectSourceTargetNode.getHalfNodeHeight(), p2.x, p2.y); } } } public void showRightClickHelp(boolean flag) { showRightClickHelp = flag; } private static void drawHelp(final Graphics g) { final int x = (int) (g.getClipBounds().getWidth() / 2); final int y = (int) (g.getClipBounds().getHeight() / 2); final FontMetrics metrics = g.getFontMetrics(); final String name = "Right click here to add an operator"; final Rectangle2D rect = metrics.getStringBounds(name, g); final int stringWidth = (int) rect.getWidth(); g.setColor(Color.black); g.drawString(name, x - stringWidth / 2, y); } /** * Handle mouse pressed event * * @param e the mouse event */ public void mousePressed(MouseEvent e) { checkPopup(e); if (showHeadHotSpot) { connectingSourceFromHead = true; } else if (showTailHotSpot) { connectingSourceFromTail = true; } lastMousePos = e.getPoint(); } /** * Handle mouse clicked event * * @param e the mouse event */ public void mouseClicked(MouseEvent e) { checkPopup(e); showRightClickHelp = false; if (e.getButton() == 1 && selectedNode != null) { graphEx.setSelectedNode(selectedNode); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } /** * Handle mouse released event * * @param e the mouse event */ public void mouseReleased(MouseEvent e) { checkPopup(e); if (connectingSourceFromHead) { final GraphNode n = findNode(e.getPoint()); if (n != null && selectedNode != n) { connectSourceTargetNode.connectOperatorSource(n.getID()); } } else if (connectingSourceFromTail) { final GraphNode n = findNode(e.getPoint()); if (n != null && selectedNode != n) { n.connectOperatorSource(connectSourceTargetNode.getID()); } } connectingSourceFromHead = false; connectingSourceFromTail = false; connectSourceTargetNode = null; if (graphEx.getGraphNodeList().isGraphComplete()) { graphEx.notifyConnection(); } repaint(); } /** * Handle mouse dragged event * * @param e the mouse event */ public void mouseDragged(MouseEvent e) { if (selectedNode != null && !connectingSourceFromHead && !connectingSourceFromTail) { final Point p = new Point(e.getX() - (lastMousePos.x - selectedNode.getPos().x), e.getY() - (lastMousePos.y - selectedNode.getPos().y)); selectedNode.setPos(p); lastMousePos = e.getPoint(); repaint(); } if (connectingSourceFromHead || connectingSourceFromTail) { connectingSourcePos = e.getPoint(); repaint(); } } /** * Handle mouse moved event * * @param e the mouse event */ public void mouseMoved(MouseEvent e) { final GraphNode n = findNode(e.getPoint()); if (selectedNode != n) { showHeadHotSpot = false; showTailHotSpot = false; selectedNode = n; repaint(); } if (selectedNode != null) { final int hotspotSize = GraphNode.getHotSpotSize(); final Point headPoint = new Point(n.getPos().x, n.getPos().y + selectedNode.getHotSpotOffset()); final Point tailPoint = new Point(n.getPos().x + n.getWidth() - hotspotSize, n.getPos().y + selectedNode.getHotSpotOffset()); if (isWithinRect(headPoint, hotspotSize, hotspotSize, e.getPoint())) { showHeadHotSpot = true; connectSourceTargetNode = selectedNode; repaint(); } else if (isWithinRect(tailPoint, hotspotSize, hotspotSize, e.getPoint())) { showTailHotSpot = true; connectSourceTargetNode = selectedNode; repaint(); } else if (showHeadHotSpot || showTailHotSpot) { showHeadHotSpot = false; showTailHotSpot = false; repaint(); } } } private GraphNode findNode(Point p) { for (GraphNode n : graphEx.getGraphNodes()) { if (isWithinRect(n.getPos(), n.getWidth(), n.getHeight(), p)) return n; } return null; } private static boolean isWithinRect(Point o, int width, int height, Point p) { return p.x > o.x && p.y > o.y && p.x < o.x + width && p.y < o.y + height; } static class AddMenuListener implements ActionListener { final GraphPanel graphPanel; AddMenuListener(GraphPanel panel) { graphPanel = panel; } public void actionPerformed(java.awt.event.ActionEvent event) { graphPanel.addOperatorAction(event.getActionCommand()); } } static class ConnectMenuListener implements ActionListener { final GraphPanel graphPanel; ConnectMenuListener(GraphPanel panel) { graphPanel = panel; } public void actionPerformed(java.awt.event.ActionEvent event) { graphPanel.autoConnectGraph(); } } static class RemoveSourceMenuListener implements ActionListener { final GraphPanel graphPanel; RemoveSourceMenuListener(GraphPanel panel) { graphPanel = panel; } public void actionPerformed(java.awt.event.ActionEvent event) { graphPanel.removeSourceAction(event.getActionCommand()); } } }
18,695
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
SubGraphHandler.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/SubGraphHandler.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.bc.ceres.binding.dom.DomElement; import org.esa.snap.core.gpf.graph.Graph; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.gpf.graph.GraphIO; import org.esa.snap.core.gpf.graph.Node; import org.esa.snap.core.gpf.graph.NodeSource; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Replaces SubGraphOp with operators from the sub-graph */ class SubGraphHandler { private final Graph graph; private final GraphNodeList graphNodeList; private final GraphNode[] savedSubGraphList; private Map<GraphNode, GraphNode[]> subGraphNodesToRemoveMap = new HashMap<>(); SubGraphHandler(final Graph graph, final GraphNodeList graphNodeList) throws GraphException { this.graph = graph; this.graphNodeList = graphNodeList; this.savedSubGraphList = replaceAllSubGraphs(); } private GraphNode[] replaceAllSubGraphs() throws GraphException { final SubGraphData[] dataList = findSubGraphs("SubGraph"); final List<GraphNode> savedList = new ArrayList<>(); for (SubGraphData data : dataList) { final GraphNode sourceNode = graphNodeList.findGraphNode(data.nodeID); if (data.subGraph != null) { replaceSubGraph(sourceNode, data.subGraph); removeNode(sourceNode); savedList.add(sourceNode); } } return savedList.toArray(new GraphNode[savedList.size()]); } private SubGraphData[] findSubGraphs(final String opName) throws GraphException { try { final List<SubGraphData> dataList = new ArrayList<>(); for (Node n : graph.getNodes()) { if (n.getOperatorName().equalsIgnoreCase(opName)) { final SubGraphData data = new SubGraphData(); data.nodeID = n.getId(); final DomElement config = n.getConfiguration(); final DomElement[] params = config.getChildren(); for (DomElement p : params) { if (p.getName().equals("graphFile") && p.getValue() != null) { data.subGraph = GraphIO.read(new FileReader(p.getValue())); break; } } dataList.add(data); } } return dataList.toArray(new SubGraphData[dataList.size()]); } catch (Exception e) { throw new GraphException(e.getMessage(), e); } } void restore() { for (GraphNode savedNode : savedSubGraphList) { final GraphNode[] nodesToRemove = subGraphNodesToRemoveMap.get(savedNode); for (GraphNode n : nodesToRemove) { final GraphNode[] connectedNodes = graphNodeList.findConnectedNodes(n); for (GraphNode node : connectedNodes) { node.connectOperatorSource(savedNode.getID()); final String name = node.getSourceName(n.getID()); node.setSourceName(name, savedNode.getNode().getId()); } removeNode(n); } graphNodeList.add(savedNode); graph.addNode(savedNode.getNode()); } } private void replaceSubGraph(final GraphNode subGraphOpNode, final Graph subGraph) { final List<GraphNode> toRemove = new ArrayList<>(); final Node[] nodes = subGraph.getNodes(); final Node firstNode = nodes[0]; final Node lastNode = nodes[nodes.length - 1]; final GraphNode[] connectedNodes = graphNodeList.findConnectedNodes(subGraphOpNode); final NodeSource[] sources = subGraphOpNode.getNode().getSources(); for (NodeSource source : sources) { final Map<String, Node> subGraphNodeMap = new HashMap<>(); for (Node subNode : nodes) { final Node newNode = new Node(source.getSourceNodeId() + subNode.getId(), subNode.getOperatorName()); subGraphNodeMap.put(subNode.getId(), newNode); newNode.setConfiguration(subNode.getConfiguration()); graph.addNode(newNode); GraphNode newGraphNode = new GraphNode(newNode); graphNodeList.add(newGraphNode); toRemove.add(newGraphNode); for (NodeSource ns : subNode.getSources()) { Node src = subGraphNodeMap.get(ns.getSourceNodeId()); if (src != null) { newGraphNode.connectOperatorSource(src.getId()); } } if (subNode == firstNode) { newNode.addSource(source); } else if (subNode == lastNode) { // switch connections for (GraphNode node : connectedNodes) { node.connectOperatorSource(newNode.getId()); final String name = node.getSourceName(subGraphOpNode.getID()); node.setSourceName(name, newNode.getId()); } } } } subGraphNodesToRemoveMap.put(subGraphOpNode, toRemove.toArray(new GraphNode[toRemove.size()])); } private void removeNode(final GraphNode node) { graphNodeList.remove(node); graph.removeNode(node.getID()); } private static class SubGraphData { String nodeID = null; Graph subGraph = null; } }
6,401
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FileTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/FileTableModel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import javax.swing.table.TableColumnModel; import javax.swing.table.TableModel; import java.io.File; /** * Interfrace for FileModel */ public interface FileTableModel extends TableModel { void addFile(final File file); void removeFile(final int index); File[] getFileList(); void refresh(); void clear(); void setColumnWidths(final TableColumnModel columnModel); File getFileAt(final int index); File[] getFilesAt(final int[] indices); int getIndexOf(final File file); void move(final int oldIndex, final int newIndex); }
1,353
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductSetUIHandler.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/ProductSetUIHandler.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.binding.dom.XppDomElement; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.common.ReadOp; import org.esa.snap.core.gpf.graph.Graph; import org.esa.snap.core.gpf.graph.Node; import org.esa.snap.core.gpf.internal.ProductSetHandler; import org.esa.snap.engine_utilities.gpf.CommonReaders; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; /** * Replaces ProductSetReader with ReadOp */ public class ProductSetUIHandler { private final Graph graph; private final GraphNodeList graphNodeList; private final GraphNode[] savedProductSetList; public ProductSetUIHandler(final Graph graph, final GraphNodeList graphNodeList) { this.graph = graph; this.graphNodeList = graphNodeList; this.savedProductSetList = replaceProductSetReaders(); } private GraphNode[] replaceProductSetReaders() { final ProductSetData[] productSetDataList = findProductSets(ProductSetHandler.PRODUCT_SET_READER_NAME); final List<GraphNode> savedProductSetList = new ArrayList<>(); int cnt = 0; for (ProductSetData psData : productSetDataList) { final GraphNode sourceNode = graphNodeList.findGraphNode(psData.nodeID); for (String filePath : psData.fileList) { replaceProductSetWithReaders(sourceNode, "inserted--" + sourceNode.getID() + "--" + cnt++, filePath); } if (!psData.fileList.isEmpty()) { removeNode(sourceNode); savedProductSetList.add(sourceNode); } } return savedProductSetList.toArray(new GraphNode[savedProductSetList.size()]); } private ProductSetData[] findProductSets(final String readerName) { final List<ProductSetData> productSetDataList = new ArrayList<>(); for (Node n : graph.getNodes()) { if (n.getOperatorName().equalsIgnoreCase(readerName)) { final ProductSetData psData = new ProductSetData(); psData.nodeID = n.getId(); final DomElement config = n.getConfiguration(); final DomElement[] params = config.getChildren(); for (DomElement p : params) { if (p.getName().equals("fileList") && p.getValue() != null) { final StringTokenizer st = new StringTokenizer(p.getValue(), ProductSetHandler.SEPARATOR); int length = st.countTokens(); for (int i = 0; i < length; i++) { final String str = st.nextToken().replace(ProductSetHandler.SEPARATOR_ESC, ProductSetHandler.SEPARATOR); psData.fileList.add(str); } break; } } productSetDataList.add(psData); } } return productSetDataList.toArray(new ProductSetData[productSetDataList.size()]); } void restore() { for (GraphNode multiSrcNode : savedProductSetList) { final List<GraphNode> nodesToRemove = new ArrayList<>(); for (GraphNode n : graphNodeList.getGraphNodes()) { final String id = n.getID(); if (id.startsWith("inserted--" + multiSrcNode.getID()) && id.contains(multiSrcNode.getID())) { graphNodeList.switchConnections(n, multiSrcNode.getID()); nodesToRemove.add(n); } } for (GraphNode r : nodesToRemove) { removeNode(r); } graphNodeList.add(multiSrcNode); graph.addNode(multiSrcNode.getNode()); } } private void replaceProductSetWithReaders(final GraphNode sourceNode, final String id, final String value) { final GraphNode newReaderNode = GraphExecuter.createNewGraphNode(graph, graphNodeList, OperatorSpi.getOperatorAlias(ReadOp.class), id); newReaderNode.setOperatorUI(null); final DomElement config = newReaderNode.getNode().getConfiguration(); final DomElement fileParam = new XppDomElement("file"); fileParam.setValue(value); config.addChild(fileParam); final String format = CommonReaders.findCommonProductFormat(new File(value)); if(format != null) { final DomElement formatParam = new XppDomElement("formatName"); formatParam.setValue(format); config.addChild(formatParam); } graphNodeList.switchConnections(sourceNode, newReaderNode.getID()); } private void removeNode(final GraphNode node) { graphNodeList.remove(node); graph.removeNode(node.getID()); } private static class ProductSetData { String nodeID = null; final List<String> fileList = new ArrayList<>(10); } }
5,767
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FileModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/FileModel.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import org.esa.snap.core.datamodel.MetadataElement; import org.esa.snap.core.datamodel.Product; import org.esa.snap.engine_utilities.datamodel.AbstractMetadata; import org.esa.snap.engine_utilities.gpf.OperatorUtils; import java.io.File; public class FileModel extends BaseFileModel implements FileTableModel { protected void setColumnData() { titles = new String[]{ "File Name", "Type", "Acquisition", "Track", "Orbit" }; types = new Class[]{ String.class, String.class, String.class, String.class, String.class }; widths = new int[]{ 75, 10, 20, 3, 5 }; } protected TableData createFileStats(final File file) { return new FileStats(file); } private class FileStats extends TableData { FileStats(final File file) { super(file); } protected void updateData() { if (file != null) { data[0] = file.getName(); } } protected void updateData(final Product product) { if (product != null) { data[0] = product.getName(); data[1] = product.getProductType(); if(AbstractMetadata.hasAbstractedMetadata(product)) { final MetadataElement absRoot = AbstractMetadata.getAbstractedMetadata(product); if (absRoot != null) { data[2] = OperatorUtils.getAcquisitionDate(absRoot); data[3] = String.valueOf(absRoot.getAttributeInt(AbstractMetadata.REL_ORBIT, 0)); data[4] = String.valueOf(absRoot.getAttributeInt(AbstractMetadata.ABS_ORBIT, 0)); } } } } } }
2,575
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
FileTable.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/FileTable.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import org.esa.snap.engine_utilities.util.ProductFunctions; import org.esa.snap.graphbuilder.rcp.utils.ClipboardUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.nodes.PNode; import org.esa.snap.rcp.util.Dialogs; import org.openide.util.datatransfer.MultiTransferObject; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; import java.awt.datatransfer.Transferable; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.io.File; /** * Table for listing product files */ public class FileTable extends JTable { private final FileTableModel fileModel; public FileTable() { this(new FileModel()); } public FileTable(FileTableModel fileModel) { this(fileModel, new Dimension(500, 100)); } public FileTable(FileTableModel fileModel, Dimension dim) { if (fileModel == null) { fileModel = new FileModel(); } this.fileModel = fileModel; this.setModel(fileModel); setPreferredScrollableViewportSize(dim); fileModel.setColumnWidths(getColumnModel()); setColumnSelectionAllowed(true); setDropMode(DropMode.ON); setDragEnabled(true); setComponentPopupMenu(createTablePopup()); setTransferHandler(new ProductSetTransferHandler(fileModel)); } @Override public String getToolTipText(MouseEvent e) { String tip = null; java.awt.Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); try { tip = getValueAt(rowIndex, colIndex).toString(); } catch (RuntimeException e1) { //catch null pointer exception if mouse is over an empty line } return tip; } public void setFiles(final File[] fileList) { if (fileList != null) { fileModel.clear(); for (File file : fileList) { fileModel.addFile(file); } } } public void setFiles(final String[] fileList) { if (fileList != null) { fileModel.clear(); for (String str : fileList) { fileModel.addFile(new File(str)); } } } public int getFileCount() { int cnt = fileModel.getRowCount(); if (cnt == 1) { File file = fileModel.getFileAt(0); if (file != null && file.getName().isEmpty()) return 0; } return cnt; } public File[] getFileList() { return fileModel.getFileList(); } public FileTableModel getModel() { return fileModel; } private JPopupMenu createTablePopup() { final JPopupMenu popup = new JPopupMenu(); final JMenuItem pastelItem = new JMenuItem("Paste"); pastelItem.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { paste(); } }); popup.add(pastelItem); return popup; } private void paste() { try { final File[] fileList = ClipboardUtils.getClipboardFileList(); if (fileList != null) { setFiles(fileList); } } catch (Exception e) { if (SnapApp.getDefault() != null) { Dialogs.showError("Unable to paste from clipboard: " + e.getMessage()); } } } public static class ProductSetTransferHandler extends TransferHandler { private final FileTableModel fileModel; ProductSetTransferHandler(FileTableModel model) { fileModel = model; } @Override public boolean canImport(TransferHandler.TransferSupport info) { if(info.isDataFlavorSupported(DataFlavor.stringFlavor)) return true; try { if(info.getDataFlavors().length > 0) { Object transferData = info.getTransferable().getTransferData(info.getDataFlavors()[0]); if (transferData instanceof PNode) { return true; } else if(transferData instanceof MultiTransferObject) { final MultiTransferObject multi = (MultiTransferObject) transferData; boolean allPNode = true; DataFlavor dataFlavor = multi.getTransferDataFlavors(0)[0]; for(int i=0; i < multi.getCount(); ++i) { Object data = multi.getTransferData(i, dataFlavor); if(!(data instanceof PNode)) { allPNode = false; break; } } return allPNode; } } } catch (Exception e) { return false; } return false; } @Override public int getSourceActions(JComponent c) { return TransferHandler.COPY; } /** * Perform the actual import */ @Override public boolean importData(TransferHandler.TransferSupport info) { if (!info.isDrop()) { return false; } // Get the string that is being dropped. final Transferable t = info.getTransferable(); try { if (info.isDataFlavorSupported(DataFlavor.stringFlavor)) { String data = (String) t.getTransferData(DataFlavor.stringFlavor); // Wherever there is a newline in the incoming data, // break it into a separate item in the list. final String[] values = data.split("\n"); for (String value : values) { final File file = new File(value); if (file.exists()) { if (ProductFunctions.isValidProduct(file)) { fileModel.addFile(file); } } } } else { Object transferData = t.getTransferData(info.getDataFlavors()[0]); if (transferData instanceof PNode) { final PNode node = (PNode)transferData; File file = node.getProduct().getFileLocation(); if (file.exists()) { fileModel.addFile(file); } } else if(transferData instanceof MultiTransferObject) { final MultiTransferObject multi = (MultiTransferObject) transferData; DataFlavor dataFlavor = multi.getTransferDataFlavors(0)[0]; for(int i=0; i < multi.getCount(); ++i) { Object data = multi.getTransferData(i, dataFlavor); if(data instanceof PNode) { final PNode node = (PNode)data; File file = node.getProduct().getFileLocation(); if (file.exists()) { fileModel.addFile(file); } } } } } if(fileModel.getRowCount() < 100) { fileModel.refresh(); } } catch (Exception e) { return false; } return true; } // export @Override protected Transferable createTransferable(JComponent c) { final JTable table = (JTable) c; final int[] rows = table.getSelectedRows(); final StringBuilder listStr = new StringBuilder(256); for (int row : rows) { final File file = fileModel.getFileAt(row); listStr.append(file.getAbsolutePath()); listStr.append('\n'); } if (rows.length != 0) { return new StringSelection(listStr.toString()); } return null; } } }
9,240
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GraphNode.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GraphNode.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.bc.ceres.binding.ConversionException; import com.bc.ceres.binding.Converter; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.dom.DomConverter; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.binding.dom.XppDomElement; import com.thoughtworks.xstream.io.xml.xppdom.XppDom; import org.apache.commons.math3.util.FastMath; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.gpf.graph.Node; import org.esa.snap.core.gpf.graph.NodeSource; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.graphbuilder.gpf.ui.OperatorUI; import org.esa.snap.graphbuilder.gpf.ui.UIValidation; import java.awt.*; import java.awt.geom.Rectangle2D; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Represents a node of the graph for the GraphBuilder * Stores, saves and loads the display position for the node * User: lveci * Date: Jan 17, 2008 */ public class GraphNode { private final Node node; private final Map<String, Object> parameterMap = new HashMap<>(10); private OperatorUI operatorUI = null; private int nodeWidth = 60; private int nodeHeight = 25; private int halfNodeHeight = 0; private int halfNodeWidth = 0; private static final int hotSpotSize = 10; private static final int halfHotSpotSize = hotSpotSize / 2; private int hotSpotOffset = 0; private Point displayPosition = new Point(0, 0); private XppDom displayParameters; private static Color shadowColor = new Color(0, 0, 0, 64); public GraphNode(final Node n) throws IllegalArgumentException { node = n; displayParameters = new XppDom("node"); displayParameters.setAttribute("id", node.getId()); initParameters(); } public void setOperatorUI(final OperatorUI ui) { operatorUI = ui; } public OperatorUI getOperatorUI() { return operatorUI; } private void initParameters() throws IllegalArgumentException { final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(node.getOperatorName()); if (operatorSpi == null) return; final ParameterDescriptorFactory parameterDescriptorFactory = new ParameterDescriptorFactory(); final PropertyContainer valueContainer = PropertyContainer.createMapBacked(parameterMap, operatorSpi.getOperatorClass(), parameterDescriptorFactory); final DomElement config = node.getConfiguration(); final int count = config.getChildCount(); for (int i = 0; i < count; ++i) { final DomElement child = config.getChild(i); final String name = child.getName(); final String value = child.getValue(); if (name == null || value == null || value.startsWith("$")) { continue; } try { if (child.getChildCount() == 0) { final Converter converter = getConverter(valueContainer, name); if (converter == null) { final String msg = "Graph parameter " + name + " not found for Operator " + operatorSpi.getOperatorAlias(); //throw new IllegalArgumentException(msg); SystemUtils.LOG.warning(msg); } else { parameterMap.put(name, converter.parse(value)); } } else { final DomConverter domConverter = getDomConverter(valueContainer, name); if(domConverter != null) { try { final Object obj = domConverter.convertDomToValue(child, null); parameterMap.put(name, obj); } catch (Exception e) { SystemUtils.LOG.warning(e.getMessage()); } } else { final Converter converter = getConverter(valueContainer, name); final Object[] objArray = new Object[child.getChildCount()]; int c = 0; for (DomElement ch : child.getChildren()) { final String v = ch.getValue(); if (converter != null) { objArray[c++] = converter.parse(v); } else { objArray[c++] = v; } } parameterMap.put(name, objArray); } } } catch (ConversionException e) { throw new IllegalArgumentException(name); } } } private static Converter getConverter(final PropertyContainer valueContainer, final String name) { final Property[] properties = valueContainer.getProperties(); for (Property p : properties) { final PropertyDescriptor descriptor = p.getDescriptor(); if (descriptor != null && (descriptor.getName().equals(name) || (descriptor.getAlias() != null && descriptor.getAlias().equals(name)))) { return descriptor.getConverter(); } } return null; } private static DomConverter getDomConverter(final PropertyContainer valueContainer, final String name) { final Property[] properties = valueContainer.getProperties(); for (Property p : properties) { final PropertyDescriptor descriptor = p.getDescriptor(); if (descriptor != null && (descriptor.getName().equals(name) || (descriptor.getAlias() != null && descriptor.getAlias().equals(name)))) { return descriptor.getDomConverter(); } } return null; } void setDisplayParameters(final XppDom presentationXML) { for (XppDom params : presentationXML.getChildren()) { final String id = params.getAttribute("id"); if (id != null && id.equals(node.getId())) { displayParameters = params; final XppDom dpElem = displayParameters.getChild("displayPosition"); if (dpElem != null) { displayPosition.x = (int) Float.parseFloat(dpElem.getAttribute("x")); displayPosition.y = (int) Float.parseFloat(dpElem.getAttribute("y")); } return; } } } void updateParameters() throws GraphException { if (operatorUI != null) { final XppDomElement config = new XppDomElement("parameters"); updateParameterMap(config); node.setConfiguration(config); } } void assignParameters(final XppDom presentationXML) throws GraphException { updateParameters(); assignDisplayParameters(presentationXML); } private void assignDisplayParameters(final XppDom presentationXML) { XppDom nodeElem = null; for (XppDom elem : presentationXML.getChildren()) { final String id = elem.getAttribute("id"); if (id != null && id.equals(node.getId())) { nodeElem = elem; break; } } if (nodeElem == null) { presentationXML.addChild(displayParameters); } XppDom dpElem = displayParameters.getChild("displayPosition"); if (dpElem == null) { dpElem = new XppDom("displayPosition"); displayParameters.addChild(dpElem); } dpElem.setAttribute("y", String.valueOf(displayPosition.getY())); dpElem.setAttribute("x", String.valueOf(displayPosition.getX())); } /** * Gets the display position of a node * * @return Point The position of the node */ public Point getPos() { return displayPosition; } /** * Sets the display position of a node and writes it to the xml * * @param p The position of the node */ public void setPos(Point p) { displayPosition = p; } public Node getNode() { return node; } public int getWidth() { return nodeWidth; } public int getHeight() { return nodeHeight; } static int getHotSpotSize() { return hotSpotSize; } private int getHalfNodeWidth() { return halfNodeWidth; } int getHalfNodeHeight() { return halfNodeHeight; } private void setSize(final int width, final int height) { nodeWidth = width; nodeHeight = height; halfNodeHeight = nodeHeight / 2; halfNodeWidth = nodeWidth / 2; hotSpotOffset = halfNodeHeight - halfHotSpotSize; } int getHotSpotOffset() { return hotSpotOffset; } /** * Gets the unique node identifier. * * @return the identifier */ public String getID() { return node.getId(); } /** * Gets the name of the operator. * * @return the name of the operator. */ public String getOperatorName() { return node.getOperatorName(); } public Map<String, Object> getParameterMap() { return parameterMap; } public Map<String, Object> getOperatorUIParameterMap() { this.operatorUI.updateParameters(); return this.operatorUI.getParameters(); } public List<String> getSources() { ArrayList<String> srcList = new ArrayList<>(); for (NodeSource src: this.node.getSources()) { srcList.add(src.getSourceNodeId()); } return srcList; } private boolean canConnect() { return !node.getOperatorName().equals("Read") && !node.getOperatorName().equals("ProductSet-Reader"); } String getSourceName(final String sourceID) { for (int i = 0; i < node.getSources().length; ++i) { final NodeSource ns = node.getSource(i); if (ns.getSourceNodeId().equals(sourceID)) { return ns.getName(); } } return null; } void setSourceName(final String sourceName, final String sourceID) { for (int i = 0; i < node.getSources().length; ++i) { final NodeSource ns = node.getSource(i); if (ns.getSourceNodeId().equals(sourceID)) { ns.setName(sourceName); } } } public void connectOperatorSource(final String id) { if(!canConnect()) { return; } // check if already a source for this node disconnectOperatorSources(id); //check if connected sources exists String cntStr = ""; if(node.getSources().length > 0) { cntStr = "."+node.getSources().length; } final NodeSource ns = new NodeSource("sourceProduct"+cntStr, id); node.addSource(ns); } public void disconnectOperatorSources(final String id) { for (NodeSource ns : node.getSources()) { if (ns.getSourceNodeId().equals(id)) { node.removeSource(ns); } } } public void disconnectAllSources() { final NodeSource[] sources = node.getSources(); for (NodeSource source : sources) { node.removeSource(source); } } boolean isNodeSource(final GraphNode source) { final NodeSource[] sources = node.getSources(); for (NodeSource ns : sources) { if (ns.getSourceNodeId().equals(source.getID())) { return true; } } return false; } boolean hasSources() { return node.getSources().length > 0; } public UIValidation validateParameterMap() { if (operatorUI != null) return operatorUI.validateParameters(); return new UIValidation(UIValidation.State.OK, ""); } void setSourceProducts(final Product[] products) { if (operatorUI != null) { operatorUI.setSourceProducts(products); } } private void updateParameterMap(final XppDomElement parentElement) throws GraphException { //if(operatorUI.hasSourceProducts()) operatorUI.updateParameters(); operatorUI.convertToDOM(parentElement); } /** * Draw a GraphNode as a rectangle with a name * * @param g The Java2D Graphics * @param col The color to draw */ void drawNode(final Graphics2D g, final Color col) { final int x = displayPosition.x; final int y = displayPosition.y; g.setFont(g.getFont().deriveFont(Font.BOLD, 11)); final FontMetrics metrics = g.getFontMetrics(); final String name = node.getId(); final Rectangle2D rect = metrics.getStringBounds(name, g); final int stringWidth = (int) rect.getWidth(); setSize(Math.max(stringWidth, 50) + 10, 25); int step = 4; int alpha = 96; for (int i = 0; i < step; ++i) { g.setColor(new Color(0, 0, 0, alpha - (32 * i))); g.drawLine(x + i + 1, y + nodeHeight + i, x + nodeWidth + i - 1, y + nodeHeight + i); g.drawLine(x + nodeWidth + i, y + i, x + nodeWidth + i, y + nodeHeight + i); } Shape clipShape = new Rectangle(x, y, nodeWidth, nodeHeight); g.setComposite(AlphaComposite.SrcAtop); g.setPaint(new GradientPaint(x, y, col, x + nodeWidth, y + nodeHeight, col.darker())); g.fill(clipShape); g.setColor(Color.blue); g.draw3DRect(x, y, nodeWidth - 1, nodeHeight - 1, true); g.setColor(Color.BLACK); g.drawString(name, x + (nodeWidth - stringWidth) / 2, y + 15); } /** * Draws the hotspot where the user can join the node to a source node * * @param g The Java2D Graphics * @param col The color to draw */ void drawHeadHotspot(final Graphics g, final Color col) { final Point p = displayPosition; g.setColor(col); g.drawOval(p.x - halfHotSpotSize, p.y + hotSpotOffset, hotSpotSize, hotSpotSize); } /** * Draws the hotspot where the user can join the node to a source node * * @param g The Java2D Graphics * @param col The color to draw */ void drawTailHotspot(final Graphics g, final Color col) { final Point p = displayPosition; g.setColor(col); final int x = p.x + nodeWidth; final int y = p.y + halfNodeHeight; final int[] xpoints = {x, x + hotSpotOffset, x, x}; final int[] ypoints = {y - halfHotSpotSize, y, y + halfHotSpotSize, y - halfHotSpotSize}; g.fillPolygon(xpoints, ypoints, xpoints.length); } /** * Draw a line between source and target nodes * * @param g The Java2D Graphics * @param src the source GraphNode */ void drawConnectionLine(final Graphics2D g, final GraphNode src) { final Point nodePos = displayPosition; final Point srcPos = src.displayPosition; final int nodeEndX = nodePos.x + nodeWidth; final int nodeMidY = nodePos.y + halfNodeHeight; final int srcEndX = srcPos.x + src.getWidth(); final int srcMidY = srcPos.y + src.getHalfNodeHeight(); if (srcEndX <= nodePos.x) { if (srcPos.y > nodePos.y + nodeHeight) { // to UR drawArrow(g, nodePos.x + halfNodeWidth, nodePos.y + nodeHeight, srcEndX, srcMidY); } else if (srcPos.y + src.getHeight() < nodePos.y) { // to DR drawArrow(g, nodePos.x + halfNodeWidth, nodePos.y, srcEndX, srcMidY); } else { // to R drawArrow(g, nodePos.x, nodeMidY, srcEndX, srcMidY); } } else if (srcPos.x >= nodeEndX) { if (srcPos.y > nodePos.y + nodeHeight) { // to UL drawArrow(g, nodePos.x + halfNodeWidth, nodePos.y + nodeHeight, srcPos.x, srcPos.y + halfNodeHeight); } else if (srcPos.y + src.getHeight() < nodePos.y) { // to DL drawArrow(g, nodePos.x + halfNodeWidth, nodePos.y, srcPos.x, srcPos.y + halfNodeHeight); } else { // to L drawArrow(g, nodeEndX, nodeMidY, srcPos.x, srcPos.y + halfNodeHeight); } } else { if (srcPos.y > nodePos.y + nodeHeight) { // U drawArrow(g, nodePos.x + halfNodeWidth, nodePos.y + nodeHeight, srcPos.x + src.getHalfNodeWidth(), srcPos.y); } else { // D drawArrow(g, nodePos.x + halfNodeWidth, nodePos.y, srcPos.x + src.getHalfNodeWidth(), srcPos.y + src.getHeight()); } } } /** * Draws an arrow head at the correct angle * * @param g The Java2D Graphics * @param tailX position X on target node * @param tailY position Y on target node * @param headX position X on source node * @param headY position Y on source node */ private static void drawArrow(final Graphics2D g, final int tailX, final int tailY, final int headX, final int headY) { final double t1 = Math.abs(headY - tailY); final double t2 = Math.abs(headX - tailX); double theta = Math.atan(t1 / t2); if (headX >= tailX) { if (headY > tailY) theta = Math.PI + theta; else theta = -(Math.PI + theta); } else if (headX < tailX && headY > tailY) theta = 2 * Math.PI - theta; final double cosTheta = FastMath.cos(theta); final double sinTheta = FastMath.sin(theta); final Point p2 = new Point(-8, -3); final Point p3 = new Point(-8, +3); int x = (int) Math.round((cosTheta * p2.x) - (sinTheta * p2.y)); p2.y = (int) Math.round((sinTheta * p2.x) + (cosTheta * p2.y)); p2.x = x; x = (int) Math.round((cosTheta * p3.x) - (sinTheta * p3.y)); p3.y = (int) Math.round((sinTheta * p3.x) + (cosTheta * p3.y)); p3.x = x; p2.translate(tailX, tailY); p3.translate(tailX, tailY); Stroke oldStroke = g.getStroke(); g.setStroke(new BasicStroke(2)); g.drawLine(tailX, tailY, headX, headY); g.drawLine(tailX, tailY, p2.x, p2.y); g.drawLine(p3.x, p3.y, tailX, tailY); g.setStroke(oldStroke); } }
19,874
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
GPFProcessor.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-graph-builder/src/main/java/org/esa/snap/graphbuilder/rcp/dialogs/support/GPFProcessor.java
/* * Copyright (C) 2014 by Array Systems Computing Inc. http://www.array.ca * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.graphbuilder.rcp.dialogs.support; import com.bc.ceres.binding.dom.DefaultDomElement; import com.bc.ceres.binding.dom.DomElement; import com.bc.ceres.core.ProgressMonitor; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.common.ReadOp; import org.esa.snap.core.gpf.common.WriteOp; import org.esa.snap.core.gpf.graph.Graph; import org.esa.snap.core.gpf.graph.GraphException; import org.esa.snap.core.gpf.graph.GraphIO; import org.esa.snap.core.gpf.graph.GraphProcessor; import org.esa.snap.core.gpf.graph.Node; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.Map; /** * Processes a graph */ public class GPFProcessor { private final Graph graph; private final GraphProcessor processor = new GraphProcessor(); public GPFProcessor(final File graphFile, final Map<String, String> parameterMap) throws GraphException, IOException { graph = readGraph(new FileReader(graphFile), parameterMap); } public static Graph readGraph(final Reader fileReader, final Map<String, String> parameterMap) throws GraphException, IOException { Graph graph = null; try { graph = GraphIO.read(fileReader, parameterMap); } finally { fileReader.close(); } return graph; } public void setIO(final File srcFile, final File tgtFile, final String format) { final String readOperatorAlias = OperatorSpi.getOperatorAlias(ReadOp.class); final Node readerNode = findNode(graph, readOperatorAlias); if (readerNode != null) { final DomElement param = new DefaultDomElement("parameters"); param.createChild("file").setValue(srcFile.getAbsolutePath()); readerNode.setConfiguration(param); } final String writeOperatorAlias = OperatorSpi.getOperatorAlias(WriteOp.class); final Node writerNode = findNode(graph, writeOperatorAlias); if (writerNode != null && tgtFile != null) { final DomElement origParam = writerNode.getConfiguration(); origParam.getChild("file").setValue(tgtFile.getAbsolutePath()); if (format != null) origParam.getChild("formatName").setValue(format); } } public void executeGraph(final ProgressMonitor pm) throws GraphException { processor.executeGraph(graph, pm); } private static Node findNode(final Graph graph, final String alias) { for (Node n : graph.getNodes()) { if (n.getOperatorName().equals(alias)) return n; } return null; } }
3,407
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-graph-builder/src/main/java/org/esa/snap/graphbuilder/docs/package-info.java
@HelpSetRegistration(helpSet = "help.hs", position = 2420) package org.esa.snap.graphbuilder.docs; import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
161
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-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/docs/package-info.java
@HelpSetRegistration(helpSet = "help.hs", position = 2395) package org.esa.snap.pixex.docs; import eu.esa.snap.netbeans.javahelp.api.HelpSetRegistration;
155
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelExtractionAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/PixelExtractionAction.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.pixex.visat; import org.esa.snap.rcp.actions.AbstractSnapAction; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionRegistration; import org.openide.util.NbBundle; import java.awt.event.ActionEvent; @ActionID(category = "Tools", id = "org.esa.snap.pixex.visat.PixelExtractionAction" ) @ActionRegistration(displayName = "#CTL_PixelExtractionAction_Text") @ActionReference(path = "Menu/Raster/Export", position = 0) @NbBundle.Messages({"CTL_PixelExtractionAction_Text=Extract Pixel Values"}) public class PixelExtractionAction extends AbstractSnapAction { public PixelExtractionAction() { putValue(SHORT_DESCRIPTION, "Extract pixel values given a list of geographical points from one or more data products."); putValue(HELP_ID, "pixelExtraction"); } @Override public void actionPerformed(ActionEvent e) { new PixelExtractionDialog(getAppContext(), "Pixel Extraction", getHelpId()).show(); } }
1,735
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelExtractionDialog.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/PixelExtractionDialog.java
/* * Copyright (C) 2014 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.pixex.visat; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.core.ProgressMonitor; import com.bc.ceres.swing.progress.ProgressMonitorSwingWorker; import org.esa.snap.core.dataio.ProductIO; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.gpf.GPF; import org.esa.snap.core.gpf.OperatorSpi; import org.esa.snap.core.gpf.annotations.ParameterDescriptorFactory; import org.esa.snap.core.gpf.ui.OperatorMenu; import org.esa.snap.core.gpf.ui.OperatorParameterSupport; import org.esa.snap.core.gpf.ui.ParameterUpdater; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.WildcardMatcher; import org.esa.snap.pixex.Coordinate; import org.esa.snap.pixex.PixExOp; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.ModelessDialog; import javax.swing.AbstractButton; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.border.EmptyBorder; import javax.swing.event.ListDataEvent; import javax.swing.event.ListDataListener; import java.awt.Component; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.TreeSet; import java.util.concurrent.ExecutionException; import java.util.logging.Logger; class PixelExtractionDialog extends ModelessDialog implements ParameterUpdater { private static final String OPERATOR_NAME = "PixEx"; private final Map<String, Object> parameterMap; private final AppContext appContext; private final PixelExtractionIOForm ioForm; private final PixelExtractionParametersForm parametersForm; PixelExtractionDialog(AppContext appContext, String title, String helpID) { super(appContext.getApplicationWindow(), title, ID_OK | ID_CLOSE | ID_HELP, helpID); this.appContext = appContext; AbstractButton button = getButton(ID_OK); button.setText("Extract"); button.setMnemonic('E'); parameterMap = new HashMap<>(); final OperatorSpi operatorSpi = GPF.getDefaultInstance().getOperatorSpiRegistry().getOperatorSpi(OPERATOR_NAME); final PropertyContainer propertyContainer = createParameterMap(parameterMap); final OperatorParameterSupport parameterSupport = new OperatorParameterSupport(operatorSpi.getOperatorDescriptor(), propertyContainer, parameterMap, this); final OperatorMenu operatorMenu = new OperatorMenu(this.getJDialog(), operatorSpi.getOperatorDescriptor(), parameterSupport, appContext, getHelpID()); getJDialog().setJMenuBar(operatorMenu.createDefaultMenu()); ListDataListener changeListener = new ListDataListener() { @Override public void intervalAdded(ListDataEvent e) { contentsChanged(e); } @Override public void intervalRemoved(ListDataEvent e) { contentsChanged(e); } @Override public void contentsChanged(ListDataEvent e) { final Product[] sourceProducts = ioForm.getSourceProducts(); if (sourceProducts.length > 0) { parametersForm.setActiveProduct(sourceProducts[0]); return; } else { if (parameterMap.containsKey("sourceProductPaths")) { final String[] inputPaths = (String[]) parameterMap.get("sourceProductPaths"); if (inputPaths.length > 0) { Product firstProduct = openFirstProduct(inputPaths); if (firstProduct != null) { parametersForm.setActiveProduct(firstProduct); return; } } } } parametersForm.setActiveProduct(null); } }; ioForm = new PixelExtractionIOForm(appContext, propertyContainer, changeListener); parametersForm = new PixelExtractionParametersForm(appContext, propertyContainer); final JPanel ioPanel = ioForm.getPanel(); ioPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); final JPanel parametersPanel = parametersForm.getPanel(); parametersPanel.setBorder(new EmptyBorder(4, 4, 4, 4)); JTabbedPane tabbedPanel = new JTabbedPane(); tabbedPanel.addTab("Input/Output", ioPanel); tabbedPanel.addTab("Parameters", parametersPanel); setContent(tabbedPanel); } private Product openFirstProduct(String[] inputPaths) { if (inputPaths != null) { final Logger logger = SystemUtils.LOG; for (String inputPath : inputPaths) { if (inputPath == null || inputPath.trim().length() == 0) { continue; } try { final TreeSet<File> fileSet = new TreeSet<>(); WildcardMatcher.glob(inputPath, fileSet); for (File file : fileSet) { final Product product = ProductIO.readProduct(file); if (product != null) { return product; } } } catch (IOException e) { logger.severe("I/O problem occurred while scanning source product files: " + e.getMessage()); } } } return null; } @Override protected void onOK() { handleParameterSaveRequest(parameterMap); ProgressMonitorSwingWorker worker = new MyProgressMonitorSwingWorker(getParent(), "Creating output file(s)..."); worker.executeWithBlocking(); } @Override public void close() { super.close(); ioForm.clear(); } @Override public int show() { ioForm.addProduct(appContext.getSelectedProduct()); return super.show(); } private static PropertyContainer createParameterMap(Map<String, Object> map) { ParameterDescriptorFactory parameterDescriptorFactory = new ParameterDescriptorFactory(); final PropertyContainer container = PropertyContainer.createMapBacked(map, PixExOp.class, parameterDescriptorFactory); container.setDefaultValues(); return container; } @Override public void handleParameterSaveRequest(Map<String, Object> parameterMap) { parameterMap.put("expression", parametersForm.getExpression()); parameterMap.put("exportExpressionResult", parametersForm.isExportExpressionResultSelected()); parameterMap.put("timeDifference", parametersForm.getAllowedTimeDifference()); parameterMap.put("coordinates", parametersForm.getCoordinates()); } @Override public void handleParameterLoadRequest(Map<String, Object> parameterMap) { Object expressionObject = parameterMap.get("expression"); String expression = ""; if (expressionObject instanceof String) { expression = (String) expressionObject; } parametersForm.setExpression(expression); Object outputDirObject = parameterMap.get("outputDir"); if (outputDirObject instanceof File) { ioForm.setOutputDirPath(outputDirObject.toString()); } Object exportExpressionResultObject = parameterMap.get("exportExpressionResult"); if (exportExpressionResultObject instanceof Boolean) { parametersForm.setExportExpressionResultSelected((Boolean) exportExpressionResultObject); } Object timeDifferenceObject = parameterMap.get("timeDifference"); String timeDifference = null; if (timeDifferenceObject instanceof String) { timeDifference = (String) timeDifferenceObject; } parametersForm.setAllowedTimeDifference(timeDifference); Object coordinatesObject = parameterMap.get("coordinates"); Coordinate[] coordinates = new Coordinate[0]; if (coordinatesObject instanceof Coordinate[]) { coordinates = (Coordinate[]) coordinatesObject; } parametersForm.setCoordinates(coordinates); parametersForm.updateUi(); } private class MyProgressMonitorSwingWorker extends ProgressMonitorSwingWorker<Void, Void> { protected MyProgressMonitorSwingWorker(Component parentComponent, String title) { super(parentComponent, title); } @Override protected Void doInBackground(ProgressMonitor pm) throws Exception { pm.beginTask("Computing pixel values...", -1); AbstractButton runButton = getButton(ID_OK); runButton.setEnabled(false); try { GPF.createProduct("PixEx", parameterMap, ioForm.getSourceProducts()); pm.worked(1); } finally { pm.done(); } return null; } @Override protected void done() { try { get(); Object outputDir = parameterMap.get("outputDir"); String message; if (outputDir != null) { message = String.format( "The pixel extraction tool has run successfully and written the result file(s) to %s.", outputDir.toString()); } else { message = "The pixel extraction tool has run successfully and written the result file to to std.out."; } showInformationDialog(message); } catch (InterruptedException ignore) { } catch (ExecutionException e) { appContext.handleError(e.getMessage(), e); } finally { AbstractButton runButton = getButton(ID_OK); runButton.setEnabled(true); } } } }
11,247
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelExtractionIOForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/PixelExtractionIOForm.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.pixex.visat; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.jidesoft.swing.FolderChooser; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.product.SourceProductList; import javax.swing.AbstractButton; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.ListDataListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Insets; import java.io.File; import java.io.IOException; class PixelExtractionIOForm { static final String PROPERTY_NAME_LAST_OPEN_INPUT_DIR = "snap.petOp.lastOpenInputDir"; static final String PROPERTY_NAME_LAST_OPEN_OUTPUT_DIR = "snap.petOp.lastOpenOutputDir"; static final String PROPERTY_NAME_LAST_OPEN_FORMAT = "snap.petOp.lastOpenFormat"; private final AppContext appContext; private final JPanel panel; private final JTextField outputDirTextField; private final PropertyContainer container; private final BindingContext context; private final SourceProductList sourceProductList; PixelExtractionIOForm(final AppContext appContext, PropertyContainer container, ListDataListener changeListener) { this.appContext = appContext; this.container = container; context = new BindingContext(container); final TableLayout tableLayout = new TableLayout(3); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTablePadding(4, 4); tableLayout.setColumnPadding(0, new Insets(3, 4, 4, 4)); tableLayout.setTableWeightX(0.0); tableLayout.setTableWeightY(0.0); tableLayout.setColumnWeightX(1, 1.0); tableLayout.setCellWeightY(0, 1, 1.0); tableLayout.setCellFill(0, 1, TableLayout.Fill.BOTH); tableLayout.setCellColspan(3, 1, 2); panel = new JPanel(tableLayout); sourceProductList = new SourceProductList(appContext); sourceProductList.setProductFilter(product -> !product.isMultiSize()); sourceProductList.setPropertyNameLastOpenedFormat(PROPERTY_NAME_LAST_OPEN_FORMAT); sourceProductList.setPropertyNameLastOpenInputDir(PROPERTY_NAME_LAST_OPEN_INPUT_DIR); sourceProductList.addChangeListener(changeListener); sourceProductList.setXAxis(true); context.bind("sourceProductPaths", sourceProductList); JComponent[] components = sourceProductList.getComponents(); panel.add(new JLabel("Source Paths:")); panel.add(components[0]); panel.add(components[1]); panel.add(new JLabel("Time extraction:")); panel.add(new TimeExtractionPane(container)); panel.add(new JLabel("")); JLabel outputDirLabel = new JLabel("Output directory:"); panel.add(outputDirLabel); outputDirTextField = new JTextField(); outputDirTextField.setEditable(false); outputDirTextField.setPreferredSize(new Dimension(80, outputDirTextField.getPreferredSize().height)); String path = getDefaultOutputPath(appContext); setOutputDirPath(path); panel.add(outputDirTextField); AbstractButton outputDirChooserButton = createOutputDirChooserButton(container.getProperty("outputDir")); panel.add(outputDirChooserButton); JLabel filePrefixLabel = new JLabel("File prefix:"); JTextField filePrefixField = createFilePrefixField(container.getProperty("outputFilePrefix")); panel.add(filePrefixLabel); panel.add(filePrefixField); } JPanel getPanel() { return panel; } void clear() { sourceProductList.clear(); setOutputDirPath(""); } void addProduct(Product selectedProduct) { sourceProductList.addProduct(selectedProduct); } Product[] getSourceProducts() { return sourceProductList.getSourceProducts(); } private String getDefaultOutputPath(AppContext appContext) { final Property dirProperty = container.getProperty("outputDir"); String userHomePath = SystemUtils.getUserHomeDir().getAbsolutePath(); String lastDir = appContext.getPreferences().getPropertyString(PROPERTY_NAME_LAST_OPEN_OUTPUT_DIR, userHomePath); String path; try { path = new File(lastDir).getCanonicalPath(); } catch (IOException ignored) { path = userHomePath; } try { dirProperty.setValue(new File(path)); } catch (ValidationException ignore) { } return path; } void setOutputDirPath(String path) { outputDirTextField.setText(path); outputDirTextField.setToolTipText(path); } private AbstractButton createOutputDirChooserButton(final Property outputFileProperty) { AbstractButton button = new JButton("..."); button.addActionListener(e -> { FolderChooser folderChooser = new FolderChooser(); folderChooser.setCurrentDirectory(new File(getDefaultOutputPath(appContext))); folderChooser.setDialogTitle("Select output directory"); folderChooser.setMultiSelectionEnabled(false); int result = folderChooser.showDialog(appContext.getApplicationWindow(), "Select"); /*I18N*/ if (result != JFileChooser.APPROVE_OPTION) { return; } File selectedFile = folderChooser.getSelectedFile(); setOutputDirPath(selectedFile.getAbsolutePath()); try { outputFileProperty.setValue(selectedFile); appContext.getPreferences().setPropertyString(PROPERTY_NAME_LAST_OPEN_OUTPUT_DIR, selectedFile.getAbsolutePath()); } catch (ValidationException ve) { // not expected to ever come here appContext.handleError("Invalid input path", ve); } }); return button; } private JTextField createFilePrefixField(Property property) { return createTextFieldBinding(property); } private JTextField createTextFieldBinding(Property property) { final JTextField textField = new JTextField(); context.bind(property.getName(), textField); return textField; } private JCheckBox createCheckBoxBinding(Property property) { final JCheckBox checkBox = new JCheckBox(property.getDescriptor().getDisplayName()); context.bind(property.getName(), checkBox); return checkBox; } private class TimeExtractionPane extends JPanel { public TimeExtractionPane(PropertyContainer container) { super(new BorderLayout(0, 5)); final JCheckBox extractTime = createCheckBoxBinding(container.getProperty("extractTimeFromFilename")); final Property datePattern = container.getProperty("dateInterpretationPattern"); final String dateDN = datePattern.getDescriptor().getDisplayName(); final JPanel datePanel = new JPanel(new BorderLayout(0, 2)); final JLabel dateLabel = new JLabel(dateDN + ":"); final JTextField datePatternField = createTextFieldBinding(datePattern); dateLabel.setEnabled(false); datePatternField.setEnabled(false); datePanel.add(dateLabel, BorderLayout.NORTH); datePanel.add(datePatternField, BorderLayout.CENTER); final Property filenamePattern = container.getProperty("filenameInterpretationPattern"); final String filenameDN = filenamePattern.getDescriptor().getDisplayName(); final JPanel filenamePanel = new JPanel(new BorderLayout(0, 2)); final JLabel filenameLabel = new JLabel(filenameDN + ":"); final JTextField filenamePatternField = createTextFieldBinding(filenamePattern); filenameLabel.setEnabled(false); filenamePatternField.setEnabled(false); filenamePanel.add(filenameLabel, BorderLayout.NORTH); filenamePanel.add(filenamePatternField, BorderLayout.CENTER); extractTime.addChangeListener(e -> { final boolean selected = extractTime.isSelected(); dateLabel.setEnabled(selected); datePatternField.setEnabled(selected); filenameLabel.setEnabled(selected); filenamePatternField.setEnabled(selected); }); add(extractTime, BorderLayout.NORTH); add(datePanel, BorderLayout.CENTER); add(filenamePanel, BorderLayout.SOUTH); } } }
9,780
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AddCsvFileAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/AddCsvFileAction.java
package org.esa.snap.pixex.visat; import org.esa.snap.core.datamodel.GenericPlacemarkDescriptor; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.core.util.io.SnapFileFilter; import org.esa.snap.pixex.PixExOpUtils; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.SnapFileChooser; import org.opengis.feature.simple.SimpleFeature; import javax.swing.AbstractAction; import javax.swing.JFileChooser; import javax.swing.JPanel; import java.awt.event.ActionEvent; import java.io.File; import java.io.IOException; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.List; class AddCsvFileAction extends AbstractAction { private static final String LAST_OPEN_CSV_DIR = "beam.pixex.lastOpenCsvDir"; private static final String ISO8601_PATTERN = "yyyy-MM-dd'T'HH:mm:ss"; private static final DateFormat dateFormat = ProductData.UTC.createDateFormat(ISO8601_PATTERN); private final AppContext appContext; private final JPanel parent; private final CoordinateTableModel tableModel; AddCsvFileAction(AppContext appContext, CoordinateTableModel tableModel, JPanel parent) { super("Add measurements from CSV file..."); this.appContext = appContext; this.parent = parent; this.tableModel = tableModel; } @Override public void actionPerformed(ActionEvent e) { PropertyMap preferences = appContext.getPreferences(); final SnapFileChooser fileChooser = getFileChooser( preferences.getPropertyString(LAST_OPEN_CSV_DIR, SystemUtils.getUserHomeDir().getPath())); int answer = fileChooser.showDialog(parent, "Select"); if (answer == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); preferences.setPropertyString(LAST_OPEN_CSV_DIR, selectedFile.getParent()); try { final List<SimpleFeature> extendedFeatures = PixExOpUtils.extractFeatures(selectedFile); for (SimpleFeature extendedFeature : extendedFeatures) { final GenericPlacemarkDescriptor placemarkDescriptor = new GenericPlacemarkDescriptor( extendedFeature.getFeatureType()); final Placemark placemark = placemarkDescriptor.createPlacemark(extendedFeature); setName(extendedFeature, placemark); setDateTime(extendedFeature, placemark); setPlacemarkGeoPos(extendedFeature, placemark); tableModel.addPlacemark(placemark); } } catch (IOException exception) { appContext.handleError(String.format("Error occurred while reading file: %s \n" + exception.getLocalizedMessage() + "\nPossible reason: Other char separator than tabulator used", selectedFile), exception); } } } private void setName(SimpleFeature extendedFeature, Placemark placemark) { if (extendedFeature.getAttribute("Name") != null) { placemark.setName(extendedFeature.getAttribute("Name").toString()); } } private void setDateTime(SimpleFeature extendedFeature, Placemark placemark) { Object dateTime = extendedFeature.getAttribute("DateTime"); if (dateTime != null && dateTime instanceof String) { try { final Date date = dateFormat.parse((String) dateTime); placemark.getFeature().setAttribute(Placemark.PROPERTY_NAME_DATETIME, date); } catch (ParseException ignored) { } } } private void setPlacemarkGeoPos(SimpleFeature extendedFeature, Placemark placemark) throws IOException { final GeoPos geoPos = PixExOpUtils.getGeoPos(extendedFeature); placemark.setGeoPos(geoPos); } private SnapFileChooser getFileChooser(String lastDir) { final SnapFileChooser fileChooser = new SnapFileChooser(); fileChooser.setFileFilter(new SnapFileFilter("CSV", new String[]{".csv", ".txt", ".ascii"}, "CSV files")); fileChooser.setCurrentDirectory(new File(lastDir)); return fileChooser; } }
4,548
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AddPlacemarkFileAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/AddPlacemarkFileAction.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.pixex.visat; import org.esa.snap.core.dataio.placemark.PlacemarkIO; import org.esa.snap.core.datamodel.PinDescriptor; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.util.PropertyMap; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.ui.AppContext; import javax.swing.AbstractAction; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JPanel; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.List; class AddPlacemarkFileAction extends AbstractAction { private static final String LAST_OPEN_PLACEMARK_DIR = "beam.pixex.lastOpenPlacemarkDir"; private final CoordinateTableModel tableModel; private final AppContext appContext; private final JComponent parentComponent; AddPlacemarkFileAction(AppContext appContext, CoordinateTableModel tableModel, JPanel parentComponent) { super("Add coordinates from file..."); this.tableModel = tableModel; this.appContext = appContext; this.parentComponent = parentComponent; } @Override public void actionPerformed(ActionEvent e) { PropertyMap preferences = appContext.getPreferences(); String lastDir = preferences.getPropertyString(LAST_OPEN_PLACEMARK_DIR, SystemUtils.getUserHomeDir().getPath()); final JFileChooser fileChooser = new JFileChooser(); fileChooser.addChoosableFileFilter(PlacemarkIO.createPlacemarkFileFilter()); fileChooser.setFileFilter(PlacemarkIO.createTextFileFilter()); fileChooser.setCurrentDirectory(new File(lastDir)); int answer = fileChooser.showDialog(parentComponent, "Select"); if (answer == JFileChooser.APPROVE_OPTION) { File selectedFile = fileChooser.getSelectedFile(); preferences.setPropertyString(LAST_OPEN_PLACEMARK_DIR, selectedFile.getParent()); FileReader reader = null; try { reader = new FileReader(selectedFile); final List<Placemark> placemarks = PlacemarkIO.readPlacemarks(reader, null, PinDescriptor.getInstance()); for (Placemark placemark : placemarks) { tableModel.addPlacemark(placemark); } } catch (IOException ioe) { appContext.handleError(String.format("Error occurred while reading file: %s", selectedFile), ioe); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } } } }
3,500
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
CoordinateTableModel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/CoordinateTableModel.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.pixex.visat; import org.locationtech.jts.geom.Point; import org.esa.snap.core.datamodel.PinDescriptor; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.ui.product.AbstractPlacemarkTableModel; import java.util.Date; class CoordinateTableModel extends AbstractPlacemarkTableModel { CoordinateTableModel() { super(PinDescriptor.getInstance(), null, null, null); } @Override public String[] getStandardColumnNames() { return new String[]{"Name", "Latitude", "Longitude", "DateTime (UTC)"}; } @Override public Class getColumnClass(int columnIndex) { switch (columnIndex) { case 0: return String.class; case 1: case 2: return Double.class; case 3: return Date.class; default: throw new IllegalArgumentException(String.format("Invalid columnIndex = %d", columnIndex)); } } @Override public boolean isCellEditable(int rowIndex, int columnIndex) { return placemarkHasGeoPos(rowIndex); } @Override public void setValueAt(Object value, int rowIndex, int columnIndex) { final Placemark placemark = getPlacemarkAt(rowIndex); switch (columnIndex) { case 0: placemark.setName((String) value); break; case 1: setGeoPosLat(value, placemark); break; case 2: setGeoPosLon(value, placemark); break; case 3: setDateTime((Date) value, placemark); break; default: throw new IllegalArgumentException(String.format("Invalid columnIndex = %d", columnIndex)); } fireTableCellUpdated(rowIndex, columnIndex); } protected void setDateTime(Date value, Placemark placemark) { placemark.getFeature().setAttribute(Placemark.PROPERTY_NAME_DATETIME, value); } @Override protected Object getStandardColumnValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return getPlacemarkAt(rowIndex).getName(); case 1: if (placemarkHasGeoPos(rowIndex)) { return getPlacemarkAt(rowIndex).getGeoPos().getLat(); } return ((Point) getPlacemarkAt(rowIndex).getFeature().getDefaultGeometry()).getY(); case 2: if (placemarkHasGeoPos(rowIndex)) { return getPlacemarkAt(rowIndex).getGeoPos().getLon(); } return ((Point) getPlacemarkAt(rowIndex).getFeature().getDefaultGeometry()).getX(); case 3: return getPlacemarkAt(rowIndex).getFeature().getAttribute(Placemark.PROPERTY_NAME_DATETIME); default: throw new IllegalArgumentException(String.format("Invalid columnIndex = %d", columnIndex)); } } private boolean placemarkHasGeoPos(int rowIndex) { return getPlacemarkAt(rowIndex).getGeoPos() != null; } }
3,896
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
PixelExtractionParametersForm.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/PixelExtractionParametersForm.java
/* * Copyright (C) 2014 Brockmann Consult GmbH ([email protected]) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 3 of the License, or (at your option) * any later version. * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, see http://www.gnu.org/licenses/ */ package org.esa.snap.pixex.visat; import com.bc.ceres.binding.Property; import com.bc.ceres.binding.PropertyContainer; import com.bc.ceres.binding.PropertyDescriptor; import com.bc.ceres.binding.ValidationException; import com.bc.ceres.binding.ValueRange; import com.bc.ceres.swing.TableLayout; import com.bc.ceres.swing.binding.BindingContext; import com.bc.ceres.swing.binding.Enablement; import org.locationtech.jts.geom.Point; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.Placemark; import org.esa.snap.core.datamodel.PlacemarkDescriptor; import org.esa.snap.core.datamodel.PlacemarkGroup; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductData; import org.esa.snap.pixex.Coordinate; import org.esa.snap.pixex.PixExOp; import org.esa.snap.rcp.util.DateCellRenderer; import org.esa.snap.rcp.util.DateTimePickerCellEditor; import org.esa.snap.ui.AppContext; import org.esa.snap.ui.DecimalCellEditor; import org.esa.snap.ui.DecimalTableCellRenderer; import org.esa.snap.ui.ModalDialog; import org.esa.snap.ui.UIUtils; import org.esa.snap.ui.product.ProductExpressionPane; import org.esa.snap.ui.tool.ToolButtonFactory; import org.geotools.feature.NameImpl; import org.geotools.feature.simple.SimpleFeatureBuilder; import org.geotools.feature.type.AttributeDescriptorImpl; import org.geotools.feature.type.AttributeTypeImpl; import org.opengis.feature.simple.SimpleFeature; import org.opengis.feature.simple.SimpleFeatureType; import org.opengis.feature.type.AttributeDescriptor; import org.opengis.feature.type.AttributeType; import javax.swing.AbstractButton; import javax.swing.BoxLayout; import javax.swing.ButtonGroup; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JCheckBox; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JRadioButton; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.SpinnerNumberModel; import javax.swing.SwingConstants; import javax.swing.SwingUtilities; import java.awt.Component; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Insets; import java.awt.Rectangle; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.DateFormat; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; class PixelExtractionParametersForm { private static final ImageIcon ADD_ICON = UIUtils.loadImageIcon("icons/Plus24.gif"); private static final ImageIcon REMOVE_ICON = UIUtils.loadImageIcon("icons/Minus24.gif"); private JPanel mainPanel; private JLabel windowLabel; private JSpinner windowSpinner; private final AppContext appContext; private final CoordinateTableModel coordinateTableModel; private JButton editExpressionButton; private JCheckBox useExpressionCheckBox; private JTextArea expressionArea; private JRadioButton expressionAsFilterButton; private JRadioButton exportExpressionResultButton; private Product activeProduct; private JLabel expressionNoteLabel; private JSpinner timeSpinner; private JComboBox<String> timeUnitComboBox; private JCheckBox includeOriginalInputBox; private Enablement aggregationEneblement; private JCheckBox timeBox; PixelExtractionParametersForm(AppContext appContext, PropertyContainer container) { this.appContext = appContext; coordinateTableModel = new CoordinateTableModel(); createUi(container); updateUi(); } public JPanel getPanel() { return mainPanel; } public Coordinate[] getCoordinates() { Coordinate[] coordinates = new Coordinate[coordinateTableModel.getRowCount()]; for (int i = 0; i < coordinateTableModel.getRowCount(); i++) { final Placemark placemark = coordinateTableModel.getPlacemarkAt(i); SimpleFeature feature = placemark.getFeature(); final Date dateTime = (Date) feature.getAttribute(Placemark.PROPERTY_NAME_DATETIME); final Coordinate.OriginalValue[] originalValues = PixExOp.getOriginalValues(feature); if (placemark.getGeoPos() == null) { final Point point = (Point) feature.getDefaultGeometry(); coordinates[i] = new Coordinate(placemark.getName(), point.getY(), point.getX(), dateTime, originalValues); } else { coordinates[i] = new Coordinate(placemark.getName(), placemark.getGeoPos().getLat(), placemark.getGeoPos().getLon(), dateTime, originalValues); } } return coordinates; } void setCoordinates(Coordinate[] coordinates) { Placemark[] toDelete = coordinateTableModel.getPlacemarks(); for (Placemark placemark : toDelete) { coordinateTableModel.removePlacemark(placemark); } PlacemarkDescriptor placemarkDescriptor = coordinateTableModel.getPlacemarkDescriptor(); final SimpleFeatureType placemarkFT = placemarkDescriptor.getBaseFeatureType(); SimpleFeatureBuilder fb = new SimpleFeatureBuilder(placemarkFT); AttributeType at = new AttributeTypeImpl(new NameImpl("label"), String.class, false, false, null, null, null); for (Coordinate coordinate : coordinates) { List<AttributeDescriptor> attributeDescriptors = new ArrayList<>(); List<String> attributeValues = new ArrayList<>(); for (Coordinate.OriginalValue originalValue : coordinate.getOriginalValues()) { attributeDescriptors.add(new AttributeDescriptorImpl(at, new NameImpl(originalValue.getVariableName()), 0, 1, false, null)); attributeValues.add(originalValue.getValue()); } placemarkFT.getUserData().put("originalAttributeDescriptors", attributeDescriptors); int attributeCount = placemarkFT.getAttributeCount(); final SimpleFeature f = fb.buildFeature(coordinate.getName(), new Object[attributeCount]); f.getUserData().put("originalAttributes", attributeValues); f.setAttribute(Placemark.PROPERTY_NAME_DATETIME, coordinate.getDateTime()); final Placemark placemark = placemarkDescriptor.createPlacemark(f); placemark.setGeoPos(new GeoPos(coordinate.getLat(), coordinate.getLon())); placemark.setName(coordinate.getName()); coordinateTableModel.addPlacemark(placemark); } } public String getExpression() { if (useExpressionCheckBox.isSelected()) { return expressionArea.getText(); } else { return null; } } void setExpression(String expression) { useExpressionCheckBox.setSelected(expression != null); expressionArea.setText(expression); } public String getAllowedTimeDifference() { return createAllowedTimeDifferenceString(); } void setAllowedTimeDifference(String timeDifference) { if (timeDifference != null && !timeDifference.isEmpty()) { timeBox.setSelected(true); String timePart = timeDifference.substring(0, timeDifference.length() - 1); timeSpinner.setValue(Integer.parseInt(timePart)); char lastChar = timeDifference.charAt(timeDifference.length() - 1); int index = 0; switch (lastChar) { case 'D': index = 0; break; case 'H': index = 1; break; case 'M': index = 2; break; } timeUnitComboBox.setSelectedIndex(index); } else { timeBox.setSelected(false); } } public boolean isExportExpressionResultSelected() { return exportExpressionResultButton.isSelected(); } void setExportExpressionResultSelected(boolean isSelected) { exportExpressionResultButton.setSelected(isSelected); } private void createUi(PropertyContainer container) { final TableLayout tableLayout = new TableLayout(3); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setTableFill(TableLayout.Fill.HORIZONTAL); tableLayout.setTablePadding(4, 4); tableLayout.setTableWeightX(0.0); tableLayout.setTableWeightY(0.0); tableLayout.setColumnWeightX(1, 1.0); tableLayout.setCellFill(0, 1, TableLayout.Fill.BOTH); // coordinate table tableLayout.setCellWeightY(0, 1, 7.0); tableLayout.setCellPadding(6, 0, new Insets(8, 4, 4, 4)); // expression label tableLayout.setCellPadding(6, 1, new Insets(0, 0, 0, 0)); // expression panel tableLayout.setCellWeightX(6, 1, 1.0); tableLayout.setCellWeightY(6, 1, 3.0); tableLayout.setCellFill(6, 1, TableLayout.Fill.BOTH); tableLayout.setCellPadding(7, 0, new Insets(8, 4, 4, 4)); // Sub-scene label tableLayout.setCellPadding(7, 1, new Insets(0, 0, 0, 0)); tableLayout.setCellPadding(8, 0, new Insets(8, 4, 4, 4)); // kmz export label tableLayout.setCellPadding(8, 1, new Insets(0, 0, 0, 0)); tableLayout.setCellPadding(9, 0, new Insets(8, 4, 4, 4)); // output match label tableLayout.setCellPadding(9, 1, new Insets(0, 0, 0, 0)); mainPanel = new JPanel(tableLayout); mainPanel.add(new JLabel("Coordinates:")); final JComponent[] coordinatesComponents = createCoordinatesComponents(); mainPanel.add(coordinatesComponents[0]); mainPanel.add(coordinatesComponents[1]); final Component[] timeDeltaComponents = createTimeDeltaComponents(tableLayout); for (Component timeDeltaComponent : timeDeltaComponents) { mainPanel.add(timeDeltaComponent); } coordinateTableModel.addTableModelListener(e -> updateIncludeOriginalInputBox()); final BindingContext bindingContext = new BindingContext(container); mainPanel.add(new JLabel("Export:")); mainPanel.add(createExportPanel(bindingContext)); mainPanel.add(tableLayout.createHorizontalSpacer()); mainPanel.add(new JLabel("Window size:")); windowSpinner = createWindowSizeEditor(bindingContext); windowLabel = new JLabel(); windowLabel.setHorizontalAlignment(SwingConstants.CENTER); windowSpinner.addChangeListener(e -> handleWindowSpinnerChange()); mainPanel.add(windowSpinner); mainPanel.add(windowLabel); mainPanel.add(new JLabel("Pixel value aggregation method:")); JComboBox aggregationStrategyChooser = new JComboBox(); bindingContext.bind("aggregatorStrategyType", aggregationStrategyChooser); aggregationEneblement = bindingContext.bindEnabledState("aggregatorStrategyType", true, new Enablement.Condition() { @Override public boolean evaluate(BindingContext bindingContext) { final Integer windowSize = (Integer) windowSpinner.getValue(); return windowSize > 1; } }); mainPanel.add(aggregationStrategyChooser); mainPanel.add(tableLayout.createVerticalSpacer()); mainPanel.add(new JLabel("Expression:")); mainPanel.add(createExpressionPanel(bindingContext)); mainPanel.add(tableLayout.createHorizontalSpacer()); mainPanel.add(new JLabel("Sub-scenes:")); mainPanel.add(createSubSceneExportPanel(bindingContext)); mainPanel.add(tableLayout.createHorizontalSpacer()); mainPanel.add(new JLabel("Google Earth export:")); mainPanel.add(createKmzExportPanel(bindingContext)); mainPanel.add(tableLayout.createHorizontalSpacer()); mainPanel.add(new JLabel("Match with original input:")); mainPanel.add(createIncludeOriginalInputBox(bindingContext)); mainPanel.add(tableLayout.createHorizontalSpacer()); } private JComponent createIncludeOriginalInputBox(BindingContext bindingContext) { final TableLayout tableLayout = new TableLayout(1); tableLayout.setTablePadding(4, 4); tableLayout.setTableWeightX(1.0); tableLayout.setTableWeightY(0.0); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); final JPanel panel = new JPanel(tableLayout); includeOriginalInputBox = new JCheckBox("Include original input"); bindingContext.bind("includeOriginalInput", includeOriginalInputBox); panel.add(includeOriginalInputBox); updateIncludeOriginalInputBox(); return panel; } private Component createKmzExportPanel(BindingContext bindingContext) { final TableLayout tableLayout = new TableLayout(1); tableLayout.setTablePadding(4, 4); tableLayout.setTableWeightX(1.0); tableLayout.setTableWeightY(0.0); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); final JPanel panel = new JPanel(tableLayout); final JCheckBox exportKmzBox = new JCheckBox("Export output coordinates to Google Earth (KMZ)"); bindingContext.bind("exportKmz", exportKmzBox); panel.add(exportKmzBox); return panel; } private JPanel createSubSceneExportPanel(BindingContext bindingContext) { final TableLayout tableLayout = new TableLayout(4); tableLayout.setTablePadding(4, 4); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setTableWeightX(0.0); tableLayout.setTableWeightY(0.0); tableLayout.setColumnWeightX(1, 0.3); tableLayout.setColumnWeightX(3, 1.0); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); final JPanel exportPanel = new JPanel(tableLayout); final JCheckBox exportSubScenesCheckBox = new JCheckBox("Enable export"); final JLabel borderSizeLabel = new JLabel("Border size:"); final JTextField borderSizeTextField = new JTextField(); borderSizeTextField.setHorizontalAlignment(JTextField.RIGHT); bindingContext.bind("exportSubScenes", exportSubScenesCheckBox); bindingContext.bind("subSceneBorderSize", borderSizeTextField); bindingContext.bindEnabledState("subSceneBorderSize", false, "exportSubScenes", false); exportPanel.add(exportSubScenesCheckBox); exportPanel.add(new JLabel()); exportPanel.add(borderSizeLabel); exportPanel.add(borderSizeTextField); return exportPanel; } private Component[] createTimeDeltaComponents(TableLayout tableLayout) { final JLabel boxLabel = new JLabel("Allowed time difference:"); timeBox = new JCheckBox("Use time difference constraint"); final Component horizontalSpacer = tableLayout.createHorizontalSpacer(); final Component horizontalSpacer2 = tableLayout.createHorizontalSpacer(); timeSpinner = new JSpinner(new SpinnerNumberModel(1, 1, null, 1)); timeSpinner.setEnabled(false); timeUnitComboBox = new JComboBox<>(new String[]{"Day(s)", "Hour(s)", "Minute(s)"}); timeUnitComboBox.setEnabled(false); timeBox.addActionListener(e -> { timeSpinner.setEnabled(timeBox.isSelected()); timeUnitComboBox.setEnabled(timeBox.isSelected()); }); return new Component[]{boxLabel, timeBox, horizontalSpacer, horizontalSpacer2, timeSpinner, timeUnitComboBox}; } private String createAllowedTimeDifferenceString() { return timeBox.isSelected() ? String.valueOf( timeSpinner.getValue()) + timeUnitComboBox.getSelectedItem().toString().charAt(0) : ""; } void updateUi() { handleWindowSpinnerChange(); updateExpressionComponents(); updateIncludeOriginalInputBox(); } private void updateIncludeOriginalInputBox() { includeOriginalInputBox.setEnabled(false); final Coordinate[] coordinates = getCoordinates(); for (Coordinate coordinate : coordinates) { if (coordinate.getOriginalValues().length > 0) { includeOriginalInputBox.setEnabled(true); return; } } } private void updateExpressionComponents() { final boolean useExpressionSelected = useExpressionCheckBox.isSelected(); editExpressionButton.setEnabled(useExpressionSelected && activeProduct != null); String toolTip = null; if (activeProduct == null) { toolTip = String.format("Editor can only be used with a product opened in %s.", appContext.getApplicationName()); } editExpressionButton.setToolTipText(toolTip); expressionArea.setEnabled(useExpressionSelected); expressionNoteLabel.setEnabled(useExpressionSelected); expressionAsFilterButton.setEnabled(useExpressionSelected); exportExpressionResultButton.setEnabled(useExpressionSelected); } private void handleWindowSpinnerChange() { final Integer windowSize = (Integer) windowSpinner.getValue(); windowLabel.setText(String.format("%1$d x %1$d", windowSize)); aggregationEneblement.apply(); } private JPanel createExportPanel(BindingContext bindingContext) { final TableLayout tableLayout = new TableLayout(4); tableLayout.setTablePadding(4, 0); tableLayout.setTableFill(TableLayout.Fill.VERTICAL); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setColumnWeightX(3, 1.0); tableLayout.setTableWeightY(1.0); final JPanel exportPanel = new JPanel(tableLayout); exportPanel.add(createIncludeCheckbox(bindingContext, "Bands", "exportBands")); exportPanel.add(createIncludeCheckbox(bindingContext, "Tie-point grids", "exportTiePoints")); exportPanel.add(createIncludeCheckbox(bindingContext, "Masks", "exportMasks")); exportPanel.add(tableLayout.createHorizontalSpacer()); return exportPanel; } private JCheckBox createIncludeCheckbox(BindingContext bindingContext, String labelText, String propertyName) { final Property windowProperty = bindingContext.getPropertySet().getProperty(propertyName); final Boolean defaultValue = (Boolean) windowProperty.getDescriptor().getDefaultValue(); final JCheckBox checkbox = new JCheckBox(labelText, defaultValue); bindingContext.bind(propertyName, checkbox); return checkbox; } private JPanel createExpressionPanel(BindingContext bindingContext) { final TableLayout tableLayout = new TableLayout(2); tableLayout.setTablePadding(4, 4); tableLayout.setTableFill(TableLayout.Fill.BOTH); tableLayout.setTableWeightX(1.0); tableLayout.setTableWeightY(0.0); tableLayout.setTableAnchor(TableLayout.Anchor.NORTHWEST); tableLayout.setCellAnchor(0, 1, TableLayout.Anchor.NORTHEAST); // edit expression button tableLayout.setRowFill(0, TableLayout.Fill.VERTICAL); tableLayout.setCellFill(1, 0, TableLayout.Fill.BOTH); // expression text area tableLayout.setCellWeightY(1, 0, 1.0); tableLayout.setCellColspan(1, 0, 2); tableLayout.setCellColspan(2, 0, 2); // expression note line 1 tableLayout.setCellColspan(3, 0, 2); // radio button group tableLayout.setCellFill(3, 0, TableLayout.Fill.BOTH); final JPanel panel = new JPanel(tableLayout); useExpressionCheckBox = new JCheckBox("Use expression"); useExpressionCheckBox.addActionListener(e -> updateExpressionComponents()); editExpressionButton = new JButton("Edit Expression..."); final Window parentWindow = SwingUtilities.getWindowAncestor(panel); editExpressionButton.addActionListener(new EditExpressionActionListener(parentWindow)); panel.add(useExpressionCheckBox); panel.add(editExpressionButton); expressionArea = new JTextArea(3, 40); expressionArea.setLineWrap(true); panel.add(new JScrollPane(expressionArea)); expressionNoteLabel = new JLabel("Note: The expression might not be applicable to all products."); panel.add(expressionNoteLabel); final ButtonGroup buttonGroup = new ButtonGroup(); expressionAsFilterButton = new JRadioButton("Use expression as filter", true); buttonGroup.add(expressionAsFilterButton); exportExpressionResultButton = new JRadioButton("Export expression result"); buttonGroup.add(exportExpressionResultButton); final Property exportResultProperty = bindingContext.getPropertySet().getProperty("exportExpressionResult"); final Boolean defaultValue = (Boolean) exportResultProperty.getDescriptor().getDefaultValue(); exportExpressionResultButton.setSelected(defaultValue); exportExpressionResultButton.setToolTipText( "Expression result is exported to the output file for each exported pixel."); expressionAsFilterButton.setSelected(!defaultValue); expressionAsFilterButton.setToolTipText( "Expression is used as filter (all pixels in given window must be valid)."); final JPanel expressionButtonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); expressionButtonPanel.add(expressionAsFilterButton); expressionButtonPanel.add(exportExpressionResultButton); panel.add(expressionButtonPanel); return panel; } private JComponent[] createCoordinatesComponents() { Product selectedProduct = appContext.getSelectedProduct(); if (selectedProduct != null) { final PlacemarkGroup pinGroup = selectedProduct.getPinGroup(); for (int i = 0; i < pinGroup.getNodeCount(); i++) { coordinateTableModel.addPlacemark(pinGroup.get(i)); } } JTable coordinateTable = new JTable(coordinateTableModel); coordinateTable.setName("coordinateTable"); coordinateTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN); coordinateTable.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); coordinateTable.setRowSelectionAllowed(true); coordinateTable.getTableHeader().setReorderingAllowed(false); coordinateTable.setDefaultRenderer(Double.class, new DecimalTableCellRenderer(new DecimalFormat("0.0000"))); coordinateTable.setPreferredScrollableViewportSize(new Dimension(250, 100)); coordinateTable.getColumnModel().getColumn(1).setCellEditor(new DecimalCellEditor(-90, 90)); coordinateTable.getColumnModel().getColumn(2).setCellEditor(new DecimalCellEditor(-180, 180)); final DateFormat dateFormat = ProductData.UTC.createDateFormat("yyyy-MM-dd'T'HH:mm:ss"); // ISO 8601 final DateFormat timeFormat = ProductData.UTC.createDateFormat("HH:mm:ss"); // ISO 8601 DateTimePickerCellEditor cellEditor = new DateTimePickerCellEditor(dateFormat, timeFormat); cellEditor.setClickCountToStart(1); coordinateTable.getColumnModel().getColumn(3).setCellEditor(cellEditor); coordinateTable.getColumnModel().getColumn(3).setPreferredWidth(200); final DateCellRenderer dateCellRenderer = new DateCellRenderer(dateFormat); dateCellRenderer.setHorizontalAlignment(SwingConstants.RIGHT); coordinateTable.getColumnModel().getColumn(3).setCellRenderer(dateCellRenderer); final JScrollPane rasterScrollPane = new JScrollPane(coordinateTable); final AbstractButton addButton = ToolButtonFactory.createButton(ADD_ICON, false); addButton.addActionListener(new AddPopupListener()); final AbstractButton removeButton = ToolButtonFactory.createButton(REMOVE_ICON, false); removeButton.addActionListener(new RemovePlacemarksListener(coordinateTable, coordinateTableModel)); final JPanel buttonPanel = new JPanel(); final BoxLayout layout = new BoxLayout(buttonPanel, BoxLayout.Y_AXIS); buttonPanel.setLayout(layout); buttonPanel.add(addButton); buttonPanel.add(removeButton); return new JComponent[]{rasterScrollPane, buttonPanel}; } private JSpinner createWindowSizeEditor(BindingContext bindingContext) { final PropertyDescriptor windowSizeDescriptor = bindingContext.getPropertySet().getProperty("windowSize").getDescriptor(); windowSizeDescriptor.setValueRange(new ValueRange(1, Double.POSITIVE_INFINITY)); windowSizeDescriptor.setAttribute("stepSize", 2); windowSizeDescriptor.setValidator((property, value) -> { if (((Number) value).intValue() % 2 == 0) { throw new ValidationException("Only odd values allowed as window size."); } }); final JSpinner spinner = new JSpinner(); bindingContext.bind("windowSize", spinner); return spinner; } public void setActiveProduct(Product product) { activeProduct = product; updateExpressionComponents(); } private class AddPopupListener implements ActionListener { @Override public void actionPerformed(ActionEvent e) { final JPopupMenu popup = new JPopupMenu("Add"); final Object source = e.getSource(); if (source instanceof Component) { final Component component = (Component) source; final Rectangle buttonBounds = component.getBounds(); popup.add(new AddCoordinateAction(coordinateTableModel)); popup.add(new AddPlacemarkFileAction(appContext, coordinateTableModel, mainPanel)); popup.add(new AddCsvFileAction(appContext, coordinateTableModel, mainPanel)); popup.show(component, 1, buttonBounds.height + 1); } } } private static class RemovePlacemarksListener implements ActionListener { private final JTable coordinateTable; private final CoordinateTableModel tableModel; private RemovePlacemarksListener(JTable coordinateTable, CoordinateTableModel tableModel) { this.coordinateTable = coordinateTable; this.tableModel = tableModel; } @Override public void actionPerformed(ActionEvent e) { int[] selectedRows = coordinateTable.getSelectedRows(); Placemark[] toRemove = new Placemark[selectedRows.length]; for (int i = 0; i < selectedRows.length; i++) { toRemove[i] = tableModel.getPlacemarkAt(selectedRows[i]); } for (Placemark placemark : toRemove) { tableModel.removePlacemark(placemark); } } } private class EditExpressionActionListener implements ActionListener { private final Window parentWindow; private EditExpressionActionListener(Window parentWindow) { this.parentWindow = parentWindow; } @Override public void actionPerformed(ActionEvent e) { ProductExpressionPane pep = ProductExpressionPane.createBooleanExpressionPane(new Product[]{activeProduct}, activeProduct, appContext.getPreferences()); pep.setCode(expressionArea.getText()); final int i = pep.showModalDialog(parentWindow, "Expression Editor"); if (i == ModalDialog.ID_OK) { expressionArea.setText(pep.getCode()); } } } }
29,199
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AddCoordinateAction.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-pixel-extraction-ui/src/main/java/org/esa/snap/pixex/visat/AddCoordinateAction.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.pixex.visat; import org.esa.snap.core.datamodel.GeoPos; import org.esa.snap.core.datamodel.PinDescriptor; import org.esa.snap.core.datamodel.PixelPos; import org.esa.snap.core.datamodel.Placemark; import javax.swing.AbstractAction; import java.awt.event.ActionEvent; class AddCoordinateAction extends AbstractAction { private final CoordinateTableModel tableModel; AddCoordinateAction(CoordinateTableModel tableModel) { super("Add coordinate"); this.tableModel = tableModel; } @Override public void actionPerformed(ActionEvent e) { final Placemark placemark = Placemark.createPointPlacemark(PinDescriptor.getInstance(), "Coord_" + tableModel.getRowCount(), "", "", new PixelPos(), new GeoPos(0, 0), null); tableModel.addPlacemark(placemark); } }
1,752
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WWAnalysisToolView.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/WWAnalysisToolView.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.worldwind; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.awt.WorldWindowGLCanvas; import gov.nasa.worldwind.event.SelectEvent; import gov.nasa.worldwind.event.SelectListener; import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.layers.LayerList; import gov.nasa.worldwind.layers.placename.PlaceNameLayer; import gov.nasa.worldwindx.examples.WMSLayersPanel; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.rcp.SnapApp; import org.esa.snap.rcp.util.Dialogs; import org.esa.snap.rcp.util.SelectionSupport; import org.esa.snap.worldwind.layers.DefaultProductLayer; import org.esa.snap.worldwind.layers.FixingPlaceNameLayer; import org.esa.snap.worldwind.layers.WWLayer; import org.esa.snap.worldwind.layers.WWLayerDescriptor; import org.esa.snap.worldwind.layers.WWLayerRegistry; import org.netbeans.api.annotations.common.NullAllowed; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JTabbedPane; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.border.EmptyBorder; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.Window; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.net.URISyntaxException; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.VIEW; @TopComponent.Description( preferredID = "WWAnalysisToolView", iconBase = "org/esa/snap/worldwind/icons/worldwind.png", persistenceType = TopComponent.PERSISTENCE_NEVER ) @TopComponent.Registration( mode = "editor", openAtStartup = false, position = 60 ) @ActionID(category = "Window", id = "org.esa.snap.worldwind.WWAnalysisToolView") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 70), @ActionReference(path = "Toolbars/Tool Windows") }) @TopComponent.OpenActionRegistration( displayName = "#CTL_WorldWindAnalysisTopComponentName", preferredID = "WWAnalysisToolView" ) @NbBundle.Messages({ "CTL_WorldWindAnalysisTopComponentName=WorldWind Analysis View", "CTL_WorldWindAnalysisTopComponentDescription=WorldWind Analysis World Map", }) /** * The window displaying the full WorldWind 3D for analysis. * */ public class WWAnalysisToolView extends WWBaseToolView implements WWView { private LayerPanel layerPanel = null; private ProductPanel productPanel = null; private final Dimension wmsPanelSize = new Dimension(400, 600); private final JTabbedPane tabbedPane = new JTabbedPane(); private int previousTabIndex = 0; private static final boolean includeStatusBar = true; private static final boolean includeLayerPanel = false; private static final boolean includeProductPanel = true; private static final boolean includeWMSPanel = false; private static final String[] servers = new String[] { "http://neowms.sci.gsfc.nasa.gov/wms/wms", //"http://mapserver.flightgear.org/cgi-bin/landcover", "http://wms.jpl.nasa.gov/wms.cgi" }; public WWAnalysisToolView() { setDisplayName("WorldWind Analysis"); setLayout(new BorderLayout(4, 4)); setBorder(new EmptyBorder(4, 4, 4, 4)); add(createControl(), BorderLayout.CENTER); //SnapApp.getDefault().getSelectionSupport(ProductSceneView.class).addHandler((oldValue, newValue) -> setCurrentView(newValue)); } public JComponent createControl() { final Window windowPane = SwingUtilities.getWindowAncestor(this); if (windowPane != null) windowPane.setSize(800, 400); final JPanel mainPane = new JPanel(new BorderLayout(4, 4)); mainPane.setSize(new Dimension(300, 300)); // world wind canvas initialize(mainPane); return mainPane; } private static void insertTiledLayer(final WorldWindow wwd, final Layer layer) { int position = 0; final LayerList layers = wwd.getModel().getLayers(); for (Layer l : layers) { if (l instanceof PlaceNameLayer) { position = layers.indexOf(l); break; } } layers.add(position, layer); } private void initialize(final JPanel mainPane) { SystemUtils.LOG.info("INITIALIZE IN WWAnalysisToolView CALLED" + " includeLayerPanel " + includeLayerPanel + " includeProductPanel " + includeProductPanel); // share resources from existing WorldWind Canvas WorldWindowGLCanvas shareWith = findWorldWindView(); final WWView toolView = this; final SwingWorker worker = new SwingWorker() { @Override protected Object doInBackground() { // Create the WorldWindow. try { createWWPanel(shareWith, includeStatusBar, false, false); wwjPanel.addLayerPanelLayer(); wwjPanel.addElevation(); // Put the pieces together. mainPane.add(wwjPanel, BorderLayout.CENTER); final LayerList layerList = getWwd().getModel().getLayers(); final Layer bingLayer = layerList.getLayerByName("Bing Imagery"); bingLayer.setEnabled(true); // final OSMMapnikLayer streetLayer = new OSMMapnikLayer(); // streetLayer.setOpacity(0.7); // streetLayer.setEnabled(false); // streetLayer.setName("Open Street Map"); // insertTiledLayer(getWwd(), streetLayer); final WWLayerDescriptor[] wwLayerDescriptors = WWLayerRegistry.getInstance().getWWLayerDescriptors(); for (WWLayerDescriptor layerDescriptor : wwLayerDescriptors) { if (layerDescriptor.showIn3DToolView()) { final WWLayer wwLayer = layerDescriptor.createWWLayer(); insertTiledLayer(getWwd(), wwLayer); wwLayer.setOpacity(0.8); // CHANGED: otherwise the objects in the product layer won't react to the select listener // wwLayer.setPickEnabled(false); if (wwLayer instanceof DefaultProductLayer) { ((DefaultProductLayer) wwLayer).setEnableSurfaceImages(true); } } } // Instead of the default Place Name layer we use special implementation to replace // wrong names in the original layer. https://senbox.atlassian.net/browse/SNAP-1476 final Layer placeNameLayer = layerList.getLayerByName("Place Names"); layerList.remove(placeNameLayer); final FixingPlaceNameLayer fixingPlaceNameLayer = new FixingPlaceNameLayer(); layerList.add(fixingPlaceNameLayer); fixingPlaceNameLayer.setEnabled(true); if (includeLayerPanel) { layerPanel = new LayerPanel(wwjPanel.getWwd(), null); mainPane.add(layerPanel, BorderLayout.WEST); layerPanel.add(makeControlPanel(), BorderLayout.SOUTH); layerPanel.update(getWwd()); } if (includeProductPanel) { Layer layer = layerList.getLayerByName("Products"); productPanel = new ProductPanel(wwjPanel.getWwd(), (DefaultProductLayer) layer); mainPane.add(productPanel, BorderLayout.WEST); productPanel.add(makeControlPanel(), BorderLayout.SOUTH); productPanel.update(getWwd()); } if (includeWMSPanel) { tabbedPane.add(new JPanel()); tabbedPane.setTitleAt(0, "+"); tabbedPane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent changeEvent) { if (tabbedPane.getSelectedIndex() != 0) { previousTabIndex = tabbedPane.getSelectedIndex(); return; } final String server = JOptionPane.showInputDialog("Enter WMS server URL"); if (server == null || server.length() < 1) { tabbedPane.setSelectedIndex(previousTabIndex); return; } // Respond by adding a new WMSLayerPanel to the tabbed pane. if (addTab(tabbedPane.getTabCount(), server.trim()) != null) tabbedPane.setSelectedIndex(tabbedPane.getTabCount() - 1); } }); // Create a tab for each server and add it to the tabbed panel. for (int i = 0; i < servers.length; i++) { addTab(i + 1, servers[i]); // i+1 to place all server tabs to the right of the Add Server tab } // Display the first server pane by default. tabbedPane.setSelectedIndex(tabbedPane.getTabCount() > 0 ? 1 : 0); previousTabIndex = tabbedPane.getSelectedIndex(); mainPane.add(tabbedPane, BorderLayout.EAST); } wwjPanel.getWwd().addSelectListener(new SelectListener() { public void selected(SelectEvent event) { /* System.out.println("event.getTopObject() " + event.getTopObject()); if (event.getTopObject() instanceof AnalyticSurface.AnalyticSurfaceObject) { System.out.println("pick point: " + event.getPickPoint()); Point pickPoint = event.getPickPoint(); if (pickPoint != null) { System.out.println("position: " + wwjPanel.getWwd().getView().computePositionFromScreenPoint(pickPoint.getX(), pickPoint.getY())); } //AnalyticSurface surface = (AnalyticSurface) event.getTopObject(); //System.out.println("dimensions " + surface.getDimensions()); //System.out.println("getCorners " + surface.getSector().getCorners()); } */ final LayerList layerList = getWwd().getModel().getLayers(); for (Layer layer : layerList) { if (layer instanceof WWLayer) { final WWLayer wwLayer = (WWLayer) layer; wwLayer.updateInfoAnnotation(event); } } } }); // update world map window with the information of the currently activated product scene view. final SnapApp snapApp = SnapApp.getDefault(); snapApp.getProductManager().addListener(new WWProductManagerListener(toolView)); snapApp.getSelectionSupport(ProductNode.class).addHandler(new SelectionSupport.Handler<ProductNode>() { @Override public void selectionChange(@NullAllowed ProductNode oldValue, @NullAllowed ProductNode newValue) { if (newValue != null) { setSelectedProduct(newValue.getProduct()); } else { setSelectedProduct(null); } } }); setProducts(snapApp.getProductManager().getProducts()); setSelectedProduct(snapApp.getSelectedProduct(VIEW)); } catch (Throwable e) { SnapApp.getDefault().handleError("Unable to initialize WWAnalysisToolView: " + e.getMessage(), e); } return null; } }; worker.execute(); } private JPanel makeControlPanel() { final JPanel controlPanel = new JPanel(new GridLayout(2, 1, 5, 5)); controlPanel.setBorder(new EmptyBorder(15, 15, 15, 15)); final LayerList layerList = getWwd().getModel().getLayers(); for (Layer layer : layerList) { if (layer instanceof WWLayer) { final WWLayer wwLayer = (WWLayer) layer; final JPanel layerControlPanel = wwLayer.getControlPanel(getWwd()); controlPanel.add(layerControlPanel); } } return controlPanel; } @Override public void setSelectedProduct(final Product product) { super.setSelectedProduct(product); if (productPanel != null) productPanel.update(getWwd()); } @Override public void setProducts(final Product[] products) { super.setProducts(products); if (productPanel != null) productPanel.update(getWwd()); } @Override public void removeProduct(final Product product) { super.removeProduct(product); if (productPanel != null) productPanel.update(getWwd()); } private WMSLayersPanel addTab(final int position, final String server) { // Add a server to the tabbed dialog. try { final WMSLayersPanel layersPanel = new WMSLayersPanel(wwjPanel.getWwd(), server, wmsPanelSize); this.tabbedPane.add(layersPanel, BorderLayout.CENTER); final String title = layersPanel.getServerDisplayString(); this.tabbedPane.setTitleAt(position, title != null && title.length() > 0 ? title : server); // Add a listener to notice wms layer selections and tell the layer panel to reflect the new state. layersPanel.addPropertyChangeListener("LayersPanelUpdated", new PropertyChangeListener() { public void propertyChange(PropertyChangeEvent propertyChangeEvent) { layerPanel.update(wwjPanel.getWwd()); } }); return layersPanel; } catch (URISyntaxException e) { Dialogs.showError("Invalid Server URL", "Server URL is invalid"); tabbedPane.setSelectedIndex(previousTabIndex); return null; } } }
16,228
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ColorBarLegend.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/ColorBarLegend.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.worldwind; import gov.nasa.worldwind.render.DrawContext; import gov.nasa.worldwind.render.ScreenImage; import gov.nasa.worldwind.util.WWMath; import java.awt.*; import java.awt.image.BufferedImage; /** */ public class ColorBarLegend extends gov.nasa.worldwindx.examples.analytics.AnalyticSurfaceLegend { private double theMinValue; private double theMaxValue; public ColorBarLegend() { super(); } public void setColorGradient(int width, int height, double minValue, double maxValue, double minHue, double maxHue, Color borderColor, Iterable<? extends LabelAttributes> labels, LabelAttributes titleLabel, boolean whiteZero) { //System.out.println("setColorGradient " + minHue + " " + maxHue); screenImage = new ScreenImage(); screenImage.setImageSource(createColorGradientLegendImage(width, height, minHue, maxHue, borderColor, whiteZero)); this.labels = createColorGradientLegendLabels(width, height, minValue, maxValue, labels, titleLabel); theMinValue = minValue; theMaxValue = maxValue; } /* public static ColorBarLegend fromColorGradient(int width, int height, double minValue, double maxValue, double minHue, double maxHue, Color borderColor, Iterable<? extends LabelAttributes> labels, LabelAttributes titleLabel, boolean whiteZero) { //System.out.println("fromColorGradient " + minHue + " " + maxHue); ColorBarLegend legend = new ColorBarLegend(); legend.screenImage = new ScreenImage(); legend.screenImage.setImageSource(legend.createColorGradientLegendImage(width, height, minHue, maxHue, borderColor, whiteZero)); legend.labels = legend.createColorGradientLegendLabels(width, height, minValue, maxValue, labels, titleLabel); return legend; } */ protected BufferedImage createColorGradientLegendImage(final int width, final int height, final double minHue, final double maxHue, final Color borderColor, final boolean whiteZero) { //System.out.println("createColorGradientLegendImage " + minHue + " " + maxHue); final BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR); final Graphics2D g2d = image.createGraphics(); try { for (int y = 0; y < height; y++) { double a = 1d - y / (double) (height - 1); double hue = WWMath.mix(a, minHue, maxHue); double sat = 1.0; if (whiteZero) { sat = Math.abs(WWMath.mix(a, -1, 1)); } g2d.setColor(Color.getHSBColor((float) hue, (float) sat, 1f)); g2d.drawLine(0, y, width - 1, y); } if (borderColor != null) { g2d.setColor(borderColor); g2d.drawRect(0, 0, width - 1, height - 1); } } finally { g2d.dispose(); } return image; } public void render(final DrawContext dc) { //System.out.println("render"); final double x = dc.getView().getViewport().getWidth() - 75.0; final double y = 320.0; setScreenLocation(new Point((int) x, (int) y)); super.render(dc); } public double getMinValue() { return theMinValue; } public double getMaxValue() { return theMaxValue; } }
4,613
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LayerPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/LayerPanel.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.worldwind; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.layers.Layer; import javax.swing.*; import javax.swing.border.CompoundBorder; import javax.swing.border.TitledBorder; import java.awt.*; import java.awt.event.ActionEvent; class LayerPanel extends JPanel { private JPanel layersPanel; private JPanel westPanel; private JScrollPane scrollPane; private Font defaultFont; public LayerPanel(WorldWindow wwd) { // Make a panel at a default size. super(new BorderLayout()); this.makePanel(wwd, new Dimension(100, 400)); } public LayerPanel(WorldWindow wwd, Dimension size) { // Make a panel at a specified size. super(new BorderLayout()); this.makePanel(wwd, size); } private void makePanel(WorldWindow wwd, Dimension size) { // Make and fill the panel holding the layer titles. this.layersPanel = new JPanel(new GridLayout(0, 1, 0, 4)); this.layersPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.fill(wwd); // Must put the layer grid in a container to prevent scroll panel from stretching their vertical spacing. final JPanel dummyPanel = new JPanel(new BorderLayout()); dummyPanel.add(this.layersPanel, BorderLayout.NORTH); // Put the name panel in a scroll bar. this.scrollPane = new JScrollPane(dummyPanel); this.scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); if (size != null) this.scrollPane.setPreferredSize(size); // Add the scroll bar and name panel to a titled panel that will resize with the main window. westPanel = new JPanel(new GridLayout(0, 1, 0, 10)); westPanel.setBorder( new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Layers"))); westPanel.setToolTipText("Layers to Show"); westPanel.add(scrollPane); this.add(westPanel, BorderLayout.CENTER); } private void fill(WorldWindow wwd) { // Fill the layers panel with the titles of all layers in the world window's current model. for (Layer layer : wwd.getModel().getLayers()) { if (layer.getName().equalsIgnoreCase("Atmosphere") || layer.getName().equalsIgnoreCase("World Map") || layer.getName().equalsIgnoreCase("Scale bar") || layer.getName().equalsIgnoreCase("Compass") || layer.getName().equalsIgnoreCase("Stars")) continue; final LayerAction action = new LayerAction(layer, wwd, layer.isEnabled()); final JCheckBox jcb = new JCheckBox(action); jcb.setSelected(action.selected); this.layersPanel.add(jcb); if (defaultFont == null) { this.defaultFont = jcb.getFont(); } } } public void update(WorldWindow wwd) { // Replace all the layer names in the layers panel with the names of the current layers. this.layersPanel.removeAll(); this.fill(wwd); this.westPanel.revalidate(); this.westPanel.repaint(); } @Override public void setToolTipText(String string) { this.scrollPane.setToolTipText(string); } private static class LayerAction extends AbstractAction { final WorldWindow wwd; private final Layer layer; private final boolean selected; public LayerAction(Layer layer, WorldWindow wwd, boolean selected) { super(layer.getName()); this.wwd = wwd; this.layer = layer; this.selected = selected; this.layer.setEnabled(this.selected); } public void actionPerformed(ActionEvent actionEvent) { // Simply enable or disable the layer based on its toggle button. if (((JCheckBox) actionEvent.getSource()).isSelected()) this.layer.setEnabled(true); else this.layer.setEnabled(false); wwd.redraw(); } } }
4,832
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WWWorldViewToolView.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/WWWorldViewToolView.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.worldwind; import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.layers.LayerList; import org.esa.snap.core.datamodel.ProductNode; import org.esa.snap.rcp.SnapApp; import org.esa.snap.runtime.Config; import org.esa.snap.ui.product.ProductSceneView; import org.esa.snap.worldwind.layers.FixingPlaceNameLayer; import org.esa.snap.worldwind.layers.WWLayer; import org.esa.snap.worldwind.layers.WWLayerDescriptor; import org.esa.snap.worldwind.layers.WWLayerRegistry; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.awt.ActionReferences; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.SwingUtilities; import javax.swing.SwingWorker; import javax.swing.border.EmptyBorder; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Window; import static org.esa.snap.rcp.SnapApp.SelectionSourceHint.VIEW; /** * The window displaying the world map. */ @TopComponent.Description( preferredID = "WWWorldMapToolView", iconBase = "org/esa/snap/icons/earth.png", persistenceType = TopComponent.PERSISTENCE_ALWAYS ) @TopComponent.Registration( mode = "navigator", openAtStartup = true, position = 50 ) @ActionID(category = "Window", id = "org.esa.snap.worldwind.WWWorldMapToolView") @ActionReferences({ @ActionReference(path = "Menu/View/Tool Windows", position = 71) }) @TopComponent.OpenActionRegistration( displayName = "#CTL_WorldWindTopComponentName", preferredID = "WWWorldMapToolView" ) @NbBundle.Messages({ "CTL_WorldWindTopComponentName=World View", "CTL_WorldWindTopComponentDescription=WorldWind World View", }) public class WWWorldViewToolView extends WWBaseToolView implements WWView { public static String useFlatEarth = "snap.worldwind.useFlatEarth"; private ProductSceneView currentView; private static final boolean includeStatusBar = true; private final boolean flatWorld; public WWWorldViewToolView() { setDisplayName(Bundle.CTL_WorldWindTopComponentName()); flatWorld = Config.instance().preferences().getBoolean(useFlatEarth, false); initComponents(); SnapApp.getDefault().getSelectionSupport(ProductSceneView.class).addHandler((oldValue, newValue) -> setCurrentView(newValue)); } private void initComponents() { setLayout(new BorderLayout(4, 4)); setBorder(new EmptyBorder(4, 4, 4, 4)); add(createControl(), BorderLayout.CENTER); } public JComponent createControl() { final Window windowPane = SwingUtilities.getWindowAncestor(this); if (windowPane != null) windowPane.setSize(300, 300); final JPanel mainPane = new JPanel(new BorderLayout(4, 4)); mainPane.setSize(new Dimension(300, 300)); // world wind canvas initialize(mainPane); return mainPane; } private void initialize(final JPanel mainPane) { final WWView toolView = this; final SwingWorker<Object, Object> worker = new SwingWorker<Object, Object>() { @Override protected Object doInBackground() { // Create the WorldWindow. try { createWWPanel(null, includeStatusBar, flatWorld, true); // Put the pieces together. mainPane.add(wwjPanel, BorderLayout.CENTER); final LayerList layerList = getWwd().getModel().getLayers(); final Layer bingLayer = layerList.getLayerByName("Bing Imagery"); bingLayer.setEnabled(true); final WWLayerDescriptor[] wwLayerDescriptors = WWLayerRegistry.getInstance().getWWLayerDescriptors(); for (WWLayerDescriptor layerDescriptor : wwLayerDescriptors) { if (layerDescriptor.showInWorldMapToolView()) { final WWLayer wwLayer = layerDescriptor.createWWLayer(); layerList.add(wwLayer); wwLayer.setOpacity(1.0); wwLayer.setPickEnabled(false); } } // Instead of the default Place Name layer we use special implementation to replace // wrong names in the original layer. https://senbox.atlassian.net/browse/SNAP-1476 final Layer placeNameLayer = layerList.getLayerByName("Place Names"); layerList.remove(placeNameLayer); final FixingPlaceNameLayer fixingPlaceNameLayer = new FixingPlaceNameLayer(); layerList.add(fixingPlaceNameLayer); fixingPlaceNameLayer.setEnabled(true); SnapApp.getDefault().getProductManager().addListener(new WWProductManagerListener(toolView)); SnapApp.getDefault().getSelectionSupport(ProductNode.class).addHandler((oldValue, newValue) -> { if (newValue != null) { setSelectedProduct(newValue.getProduct()); } else { setSelectedProduct(null); } }); setProducts(SnapApp.getDefault().getProductManager().getProducts()); setSelectedProduct(SnapApp.getDefault().getSelectedProduct(VIEW)); } catch (Throwable e) { SnapApp.getDefault().handleError("Unable to initialize WWWorldMapToolView: " + e.getMessage(), e); } return null; } }; worker.execute(); } public void setCurrentView(final ProductSceneView newView) { if (currentView != newView) { currentView = newView; } } }
6,699
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WWView.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/WWView.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.worldwind; import org.esa.snap.core.datamodel.Product; /** * Interface for WorldWind ToolView */ public interface WWView { Product getSelectedProduct(); void setSelectedProduct(final Product product); void setProducts(Product[] products); void removeProduct(Product product); }
1,045
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WWProductManagerListener.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/WWProductManagerListener.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.worldwind; import org.esa.snap.core.datamodel.Product; import org.esa.snap.core.datamodel.ProductManager; import org.esa.snap.rcp.SnapApp; /** * WWProductManagerListener */ public class WWProductManagerListener implements ProductManager.Listener { private final WWView wwView; public WWProductManagerListener(final WWView wwView) { this.wwView = wwView; } @Override public void productAdded(ProductManager.Event event) { final Product product = event.getProduct(); wwView.setProducts(SnapApp.getDefault().getProductManager().getProducts()); wwView.setSelectedProduct(product); } @Override public void productRemoved(ProductManager.Event event) { final Product product = event.getProduct(); if (wwView.getSelectedProduct() == product) { wwView.setSelectedProduct(null); } wwView.removeProduct(product); } }
1,669
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
LayerPanelLayer.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/LayerPanelLayer.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.worldwind; import gov.nasa.worldwind.WorldWindow; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.event.SelectEvent; import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.layers.LayerList; import gov.nasa.worldwind.pick.PickedObject; import gov.nasa.worldwind.render.ScreenAnnotation; import gov.nasa.worldwindx.examples.util.LayerManagerLayer; import java.awt.*; /** * Displays the layer list in a viewport corner. */ public class LayerPanelLayer extends LayerManagerLayer { private Layer virtualEarthAerialLayer = null; private Layer virtualEarthRoadsLayer = null; private Layer virtualEarthHybridLayer = null; public LayerPanelLayer(WorldWindow wwd) { super(wwd); } private LayerList getValidLayers() { final LayerList validLayers = new LayerList(); final LayerList allLayers = wwd.getModel().getLayers(); for (Layer l : allLayers) { if (l.getName().equalsIgnoreCase("Atmosphere") || l.getName().equalsIgnoreCase("World Map") || l.getName().equalsIgnoreCase("Scale bar") || l.getName().equalsIgnoreCase("Compass") || l.getName().equalsIgnoreCase("Stars") || l.getName().equalsIgnoreCase("NASA Blue Marble Image")) continue; if (l.getName().equalsIgnoreCase("MS Bing Aerial")) virtualEarthAerialLayer = l; else if (l.getName().equalsIgnoreCase("MS Bing Roads")) virtualEarthRoadsLayer = l; else if (l.getName().equalsIgnoreCase("MS Bing Hybrid")) virtualEarthHybridLayer = l; validLayers.add(l); } return validLayers; } /** * <code>SelectListener</code> implementation. * * @param event the current <code>SelectEvent</code> */ @Override public void selected(SelectEvent event) { //System.out.println("event.getEventAction(): " + event.getEventAction()); final ScreenAnnotation annotation = getAnnotation(); if (event.hasObjects() && event.getTopObject() == annotation) { boolean update = false; if (event.getEventAction().equals(SelectEvent.ROLLOVER) || event.getEventAction().equals(SelectEvent.LEFT_CLICK)) { // Highlight annotation if (!annotation.getAttributes().isHighlighted()) { annotation.getAttributes().setHighlighted(true); update = true; } // Check for text or url final PickedObject po = event.getTopPickedObject(); if (po.getValue(AVKey.URL) != null) { // Set cursor hand on hyperlinks ((Component) this.wwd).setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); int i = Integer.parseInt((String) po.getValue(AVKey.URL)); // Select current hyperlink if (getSelectedIndex() != i) { setSelectedIndex(i); update = true; } // Enable/disable layer on left click if (event.getEventAction().equals(SelectEvent.LEFT_CLICK)) { final LayerList layers = getValidLayers(); if (i >= 0 && i < layers.size()) { final Layer layer = layers.get(i); final boolean enable = !layer.isEnabled(); layer.setEnabled(enable); updateVirtualEarthLayers(layer, enable); update = true; } } } else { // Unselect if not on an hyperlink if (getSelectedIndex() != -1) { setSelectedIndex(-1); update = true; } // Set cursor if (this.isComponentDragEnabled()) ((Component) this.wwd).setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); else ((Component) this.wwd).setCursor(Cursor.getDefaultCursor()); } } if (event.getEventAction().equals(SelectEvent.DRAG) || event.getEventAction().equals(SelectEvent.DRAG_END)) { // Handle dragging if (this.isComponentDragEnabled() || this.isLayerDragEnabled()) { final boolean wasDraggingLayer = this.draggingLayer; this.drag(event); // Update list if dragging a layer, otherwise just redraw the world window if (this.draggingLayer || wasDraggingLayer) update = true; else this.wwd.redraw(); } } // Redraw annotation if needed if (update) this.update(); } else if (event.getEventAction().equals(SelectEvent.ROLLOVER) && annotation.getAttributes().isHighlighted()) { // de-highlight annotation annotation.getAttributes().setHighlighted(false); ((Component) this.wwd).setCursor(Cursor.getDefaultCursor()); this.update(); } } private void updateVirtualEarthLayers(Layer layer, boolean enable) { if (enable && (layer == virtualEarthAerialLayer || layer == virtualEarthRoadsLayer || layer == virtualEarthHybridLayer)) { virtualEarthAerialLayer.setEnabled(layer == virtualEarthAerialLayer); virtualEarthRoadsLayer.setEnabled(layer == virtualEarthRoadsLayer); virtualEarthHybridLayer.setEnabled(layer == virtualEarthHybridLayer); } } @Override protected void drag(SelectEvent event) { if (event.getEventAction().equals(SelectEvent.DRAG)) { if ((this.isComponentDragEnabled() && getSelectedIndex() == -1 && this.dragRefIndex == -1) || this.draggingComponent) { // Dragging the whole list if (!this.draggingComponent) { this.dragRefCursorPoint = event.getMouseEvent().getPoint(); this.dragRefPoint = getAnnotation().getScreenPoint(); this.draggingComponent = true; } final Point cursorOffset = new Point(event.getMouseEvent().getPoint().x - this.dragRefCursorPoint.x, event.getMouseEvent().getPoint().y - this.dragRefCursorPoint.y); final Point targetPoint = new Point(this.dragRefPoint.x + cursorOffset.x, this.dragRefPoint.y - cursorOffset.y); this.moveTo(targetPoint); } else if (this.isLayerDragEnabled()) { // Dragging a layer inside the list if (!this.draggingLayer) { this.dragRefIndex = getSelectedIndex(); this.draggingLayer = true; } if (getSelectedIndex() != -1 && this.dragRefIndex != -1 && this.dragRefIndex != getSelectedIndex()) { // Move dragged layer final LayerList layers = getValidLayers(); final int insertIndex = this.dragRefIndex > getSelectedIndex() ? getSelectedIndex() : getSelectedIndex() + 1; final int removeIndex = this.dragRefIndex > getSelectedIndex() ? this.dragRefIndex + 1 : this.dragRefIndex; layers.add(insertIndex, layers.get(this.dragRefIndex)); layers.remove(removeIndex); this.dragRefIndex = getSelectedIndex(); } } } else if (event.getEventAction().equals(SelectEvent.DRAG_END)) { this.draggingComponent = false; this.draggingLayer = false; this.dragRefIndex = -1; } } /** * Compose the annotation text from the given <code>LayerList</code>. * * @param layers the <code>LayerList</code> to draw names from. * @return the annotation text to be displayed. */ @Override protected String makeAnnotationText(LayerList layers) { // Compose html text final StringBuilder text = new StringBuilder(255); Color color; int i = 0; final LayerList validLayers = getValidLayers(); for (Layer layer : validLayers) { if (!this.isMinimized() || layer == this) { color = (i == getSelectedIndex()) ? getHighlightColor() : getColor(); color = (i == this.dragRefIndex) ? dragColor : color; text.append("<a href=\""); text.append(i); text.append("\"><font color=\""); text.append(encodeHTMLColor(color)); text.append("\">"); text.append((layer.isEnabled() ? getLayerEnabledSymbol() : getLayerDisabledSymbol())); text.append(' '); text.append((layer.isEnabled() ? "<b>" : "<i>")); text.append(layer.getName()); text.append((layer.isEnabled() ? "</b>" : "</i>")); text.append((layer.isMultiResolution() && layer.isAtMaxResolution() ? "*" : "")); text.append("</a><br />"); } i++; } return text.toString(); } }
10,420
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WWActivator.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/WWActivator.java
package org.esa.snap.worldwind; import gov.nasa.worldwind.util.Logging; import org.esa.snap.runtime.Activator; import org.esa.snap.runtime.Config; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Marco Peters */ public class WWActivator implements Activator{ // need to keep it as static field, otherwise it might be removed from logmanager, and therefor the configuration too // seems this is a bug and fixed in Java9 (http://bugs.java.com/view_bug.do?bug_id=8030192) private static final Logger logger = Logging.logger(); private static final String WORLDWIND_LOGLEVEL_KEY = "snap.worldwind.logLevel"; @Override public void start() { // Logger logger = Logger.getLogger(Configuration.DEFAULT_LOGGER_NAME); String level = Config.instance().preferences().get(WORLDWIND_LOGLEVEL_KEY, "OFF"); logger.setLevel(Level.parse(level)); } @Override public void stop() { } }
967
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/ProductPanel.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.worldwind; import gov.nasa.worldwind.WorldWindow; import org.esa.snap.core.util.SystemUtils; import org.esa.snap.worldwind.layers.DefaultProductLayer; import javax.swing.AbstractAction; import javax.swing.BorderFactory; import javax.swing.JCheckBox; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.border.CompoundBorder; import javax.swing.border.TitledBorder; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; class ProductPanel extends JPanel { private final DefaultProductLayer defaultProductLayer; private JPanel layersPanel; private JPanel westPanel; private JScrollPane scrollPane; private Font defaultFont = null; public ProductPanel(WorldWindow wwd, DefaultProductLayer prodLayer) { super(new BorderLayout()); defaultProductLayer = prodLayer; this.makePanel(wwd, new Dimension(100, 400)); } private void makePanel(WorldWindow wwd, Dimension size) { // Make and fill the panel holding the layer titles. this.layersPanel = new JPanel(new GridLayout(0, 1, 0, 4)); this.layersPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5)); this.fill(wwd); // Must put the layer grid in a container to prevent scroll panel from stretching their vertical spacing. final JPanel dummyPanel = new JPanel(new BorderLayout()); dummyPanel.add(this.layersPanel, BorderLayout.NORTH); // Put the name panel in a scroll bar. this.scrollPane = new JScrollPane(dummyPanel); this.scrollPane.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0)); if (size != null) this.scrollPane.setPreferredSize(size); // Add the scroll bar and name panel to a titled panel that will resize with the main window. westPanel = new JPanel(new GridLayout(0, 1, 0, 10)); westPanel.setBorder( new CompoundBorder(BorderFactory.createEmptyBorder(9, 9, 9, 9), new TitledBorder("Products"))); westPanel.setToolTipText("Products to Show"); westPanel.add(scrollPane); this.add(westPanel, BorderLayout.CENTER); } private void fill(WorldWindow wwd) { final String[] productNames = defaultProductLayer.getProductNames(); for (String name : productNames) { final LayerAction action = new LayerAction(defaultProductLayer, wwd, name, defaultProductLayer.getOpacity(name) != 0); final JCheckBox jcb = new JCheckBox(action); jcb.setSelected(action.selected); this.layersPanel.add(jcb); if (defaultFont == null) { this.defaultFont = jcb.getFont(); } } } public void update(WorldWindow wwd) { // Replace all the layer names in the layers panel with the names of the current layers. this.layersPanel.removeAll(); this.fill(wwd); this.westPanel.revalidate(); this.westPanel.repaint(); } @Override public void setToolTipText(String string) { this.scrollPane.setToolTipText(string); } private static class LayerAction extends AbstractAction { final WorldWindow wwd; private final DefaultProductLayer layer; private final boolean selected; private final String name; public LayerAction(DefaultProductLayer layer, WorldWindow wwd, String name, boolean selected) { super(name); this.wwd = wwd; this.layer = layer; this.name = name; this.selected = selected; this.layer.setEnabled(this.selected); } public void actionPerformed(ActionEvent actionEvent) { SystemUtils.LOG.fine("actionPerformed " + actionEvent); // Simply enable or disable the layer based on its toggle button. //System.out.println("Product click " + layer); //System.out.println(layer.getOpacity()); if (((JCheckBox) actionEvent.getSource()).isSelected()) { this.layer.setOpacity(name, this.layer.getOpacity()); } else { this.layer.setOpacity(name, 0); } wwd.redraw(); } } }
5,052
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
WWBaseToolView.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/WWBaseToolView.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.worldwind; import gov.nasa.worldwind.View; import gov.nasa.worldwind.awt.WorldWindowGLCanvas; import gov.nasa.worldwind.geom.Position; import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.layers.LayerList; 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.rcp.SnapApp; import org.esa.snap.rcp.windows.ToolTopComponent; import org.esa.snap.worldwind.layers.WWLayer; import org.openide.windows.WindowManager; import java.awt.Dimension; /** * Base WorldWind ToolView */ public abstract class WWBaseToolView extends ToolTopComponent { private final Dimension canvasSize = new Dimension(800, 600); protected AppPanel wwjPanel = null; private Position eyePosition = null; public WWBaseToolView() { } AppPanel createWWPanel(final WorldWindowGLCanvas shareWith, final boolean includeStatusBar, final boolean flatWorld, final boolean removeExtraLayers) { wwjPanel = new AppPanel(shareWith, includeStatusBar, flatWorld, removeExtraLayers); wwjPanel.setPreferredSize(canvasSize); return wwjPanel; } WorldWindowGLCanvas getWwd() { if (wwjPanel == null) return null; return wwjPanel.getWwd(); } protected WorldWindowGLCanvas findWorldWindView() { final WWWorldViewToolView window = (WWWorldViewToolView) WindowManager.getDefault().findTopComponent("WWWorldMapToolView"); if(window != null) { return window.getWwd(); } return null; } public Product getSelectedProduct() { final LayerList layerList = getWwd().getModel().getLayers(); for (Layer layer : layerList) { if (layer instanceof WWLayer) { final WWLayer wwLayer = (WWLayer) layer; return wwLayer.getSelectedProduct(); } } return null; } private void gotoProduct(final Product product) { if (product == null) return; final View theView = getWwd().getView(); final Position origPos = theView.getEyePosition(); final GeoCoding geoCoding = product.getSceneGeoCoding(); if (geoCoding != null && origPos != null) { final GeoPos centre = product.getSceneGeoCoding().getGeoPos(new PixelPos(product.getSceneRasterWidth() / 2, product.getSceneRasterHeight() / 2), null); centre.normalize(); theView.setEyePosition(Position.fromDegrees(centre.getLat(), centre.getLon(), origPos.getElevation())); } } public void setSelectedProduct(final Product product) { if (product == getSelectedProduct() && eyePosition == getWwd().getView().getEyePosition()) return; final LayerList layerList = getWwd().getModel().getLayers(); layerList.stream().filter(layer -> layer instanceof WWLayer).forEach(layer -> { final WWLayer wwLayer = (WWLayer) layer; wwLayer.setSelectedProduct(product); }); if (isVisible()) { gotoProduct(product); getWwd().redrawNow(); eyePosition = getWwd().getView().getEyePosition(); } } public void setProducts(final Product[] products) { WorldWindowGLCanvas wwd = getWwd(); final LayerList layerList = getWwd().getModel().getLayers(); layerList.stream().filter(layer -> layer instanceof WWLayer).forEach(layer -> { final WWLayer wwLayer = (WWLayer) layer; for (Product prod : products) { try { wwLayer.addProduct(prod, wwd); } catch (Exception e) { SnapApp.getDefault().handleError("WorldWind unable to add product " + prod.getName(), e); } } }); } public void removeProduct(final Product product) { if (getSelectedProduct() == product) setSelectedProduct(null); final LayerList layerList = getWwd().getModel().getLayers(); layerList.stream().filter(layer -> layer instanceof WWLayer).forEach(layer -> { final WWLayer wwLayer = (WWLayer) layer; wwLayer.removeProduct(product); }); if (isVisible()) { getWwd().redrawNow(); } } }
5,242
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
AppPanel.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/AppPanel.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.worldwind; import gov.nasa.worldwind.Configuration; import gov.nasa.worldwind.Model; import gov.nasa.worldwind.WorldWind; import gov.nasa.worldwind.avlist.AVKey; import gov.nasa.worldwind.avlist.AVList; import gov.nasa.worldwind.avlist.AVListImpl; import gov.nasa.worldwind.awt.WorldWindowGLCanvas; import gov.nasa.worldwind.geom.LatLon; import gov.nasa.worldwind.globes.Earth; import gov.nasa.worldwind.globes.EarthFlat; import gov.nasa.worldwind.globes.ElevationModel; import gov.nasa.worldwind.layers.CompassLayer; import gov.nasa.worldwind.layers.Earth.LandsatI3WMSLayer; import gov.nasa.worldwind.layers.Layer; import gov.nasa.worldwind.layers.LayerList; import gov.nasa.worldwind.layers.SkyGradientLayer; import gov.nasa.worldwind.layers.StarsLayer; import gov.nasa.worldwind.layers.WorldMapLayer; import gov.nasa.worldwind.ogc.wms.WMSCapabilities; import gov.nasa.worldwind.terrain.CompoundElevationModel; import gov.nasa.worldwind.terrain.WMSBasicElevationModel; import gov.nasa.worldwind.util.Logging; import gov.nasa.worldwind.util.PlacemarkClutterFilter; import gov.nasa.worldwind.util.StatusBar; import gov.nasa.worldwind.view.orbit.BasicOrbitView; import gov.nasa.worldwind.view.orbit.FlatOrbitView; import gov.nasa.worldwind.wms.CapabilitiesRequest; import gov.nasa.worldwindx.examples.ClickAndGoSelectListener; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.swing.JPanel; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.awt.BorderLayout; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; /** * World Wind App Panel */ public class AppPanel extends JPanel { private WorldWindowGLCanvas wwd = null; private StatusBar statusBar = null; public AppPanel(final WorldWindowGLCanvas shareWith, final boolean includeStatusBar, final boolean flatWorld, final boolean removeExtraLayers) { super(new BorderLayout()); this.wwd = new WorldWindowGLCanvas(shareWith); // Create the default model as described in the current worldwind properties. final Model m = (Model) WorldWind.createConfigurationComponent(AVKey.MODEL_CLASS_NAME); this.wwd.setModel(m); if (flatWorld) { m.setGlobe(new EarthFlat()); this.wwd.setView(new FlatOrbitView()); } else { m.setGlobe(new Earth()); this.wwd.setView(new BasicOrbitView()); } if (removeExtraLayers) { final LayerList layerList = m.getLayers(); for (Layer layer : layerList) { if (layer instanceof CompassLayer || layer instanceof WorldMapLayer || layer instanceof StarsLayer || layer instanceof LandsatI3WMSLayer || layer instanceof SkyGradientLayer) layerList.remove(layer); } } // Setup a select listener for the worldmap click-and-go feature this.wwd.addSelectListener(new ClickAndGoSelectListener(wwd, WorldMapLayer.class)); this.wwd.getSceneController().setClutterFilter(new PlacemarkClutterFilter()); this.add(this.wwd, BorderLayout.CENTER); if (includeStatusBar) { this.statusBar = new MinimalStatusBar(); this.add(statusBar, BorderLayout.PAGE_END); this.statusBar.setEventSource(wwd); } } public void addLayerPanelLayer() { wwd.getModel().getLayers().add(new LayerPanelLayer(getWwd())); } public void addElevation() { try { final ElevationModel em = makeElevationModel(); wwd.getModel().getGlobe().setElevationModel(em); } catch (Exception ignore) { } } public final WorldWindowGLCanvas getWwd() { return wwd; } public final StatusBar getStatusBar() { return statusBar; } private static ElevationModel makeElevationModel() throws URISyntaxException, ParserConfigurationException, IOException, SAXException { final URI serverURI = new URI("http://www.nasa.network.com/elev"); final DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance(); docBuilderFactory.setNamespaceAware(true); if (Configuration.getJavaVersion() >= 1.6) { try { docBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false); } catch (ParserConfigurationException e) { // Note it and continue on. Some Java5 parsers don't support the feature. String message = Logging.getMessage("XML.NonvalidatingNotSupported"); Logging.logger().finest(message); } } final DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder(); // Request the capabilities document from the server. final CapabilitiesRequest req = new CapabilitiesRequest(serverURI); final Document doc = docBuilder.parse(req.toString()); // Parse the DOM as a capabilities document. // CHANGED //final Capabilities caps = Capabilities.parse(doc); final WMSCapabilities caps = new WMSCapabilities(doc); final double HEIGHT_OF_MT_EVEREST = 8850d; // meters final double DEPTH_OF_MARIANAS_TRENCH = -11000d; // meters // Set up and instantiate the elevation model final AVList params = new AVListImpl(); params.setValue(AVKey.LAYER_NAMES, "|srtm3"); params.setValue(AVKey.TILE_WIDTH, 150); params.setValue(AVKey.TILE_HEIGHT, 150); params.setValue(AVKey.LEVEL_ZERO_TILE_DELTA, LatLon.fromDegrees(20, 20)); params.setValue(AVKey.NUM_LEVELS, 8); params.setValue(AVKey.NUM_EMPTY_LEVELS, 0); params.setValue(AVKey.ELEVATION_MIN, DEPTH_OF_MARIANAS_TRENCH); params.setValue(AVKey.ELEVATION_MAX, HEIGHT_OF_MT_EVEREST); final CompoundElevationModel cem = new CompoundElevationModel(); cem.addElevationModel(new WMSBasicElevationModel(caps, params)); return cem; } private static class MinimalStatusBar extends StatusBar { public MinimalStatusBar() { super(); this.remove(altDisplay); } } }
7,091
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z
ProductRenderablesInfo.java
/FileExtraction/Java_unseen/senbox-org_snap-desktop/snap-worldwind/src/main/java/org/esa/snap/worldwind/ProductRenderablesInfo.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.worldwind; import gov.nasa.worldwind.render.Renderable; import gov.nasa.worldwind.util.BufferWrapper; import gov.nasa.worldwindx.examples.analytics.AnalyticSurface; import java.util.ArrayList; import java.util.HashMap; /** */ public class ProductRenderablesInfo { public ArrayList<AnalyticSurface> owiAnalyticSurfaces = null; public ArrayList<AnalyticSurface> oswAnalyticSurfaces = null; public ArrayList<AnalyticSurface> rvlAnalyticSurfaces = null; public ArrayList<BufferWrapper> owiAnalyticSurfaceValueBuffers = null; public ArrayList<BufferWrapper> oswAnalyticSurfaceValueBuffers = null; public ArrayList<BufferWrapper> rvlAnalyticSurfaceValueBuffers = null; public HashMap<String, ArrayList<Renderable>> theRenderableListHash; public ProductRenderablesInfo() { super(); theRenderableListHash = new HashMap<>(); theRenderableListHash.put("owi", new ArrayList<>()); theRenderableListHash.put("osw", new ArrayList<>()); theRenderableListHash.put("rvl", new ArrayList<>()); owiAnalyticSurfaces = new ArrayList<>(); oswAnalyticSurfaces = new ArrayList<>(); rvlAnalyticSurfaces = new ArrayList<>(); owiAnalyticSurfaceValueBuffers = new ArrayList<>(); oswAnalyticSurfaceValueBuffers = new ArrayList<>(); rvlAnalyticSurfaceValueBuffers = new ArrayList<>(); } public void setAnalyticSurfaceAndBuffer(AnalyticSurface analyticSurface, BufferWrapper analyticSurfaceValueBuffer, String comp) { if (comp.equalsIgnoreCase("owi")) { //owiAnalyticSurface = analyticSurface; //owiAnalyticSurfaceValueBuffer = analyticSurfaceValueBuffer; owiAnalyticSurfaces.add(analyticSurface); owiAnalyticSurfaceValueBuffers.add(analyticSurfaceValueBuffer); } else if (comp.equalsIgnoreCase("osw")) { //oswAnalyticSurface = analyticSurface; //oswAnalyticSurfaceValueBuffer = analyticSurfaceValueBuffer; oswAnalyticSurfaces.add(analyticSurface); oswAnalyticSurfaceValueBuffers.add(analyticSurfaceValueBuffer); } else if (comp.equalsIgnoreCase("rvl")) { //rvlAnalyticSurface = analyticSurface; //rvlAnalyticSurfaceValueBuffer = analyticSurfaceValueBuffer; rvlAnalyticSurfaces.add(analyticSurface); rvlAnalyticSurfaceValueBuffers.add(analyticSurfaceValueBuffer); } } }
3,205
Java
.java
senbox-org/snap-desktop
132
60
9
2014-10-30T11:53:56Z
2024-05-07T21:09:33Z